dss89001 2016-10-01 11:24
浏览 39
已采纳

如何在控制器中的命令文件中获取Symfony对象

In my application I want to perform some maintenance tasks.

Therefore I run with a cronjob the overall maintenance function.

protected function execute(InputInterface $input, OutputInterface $output)
{
   Maintenance::checkDowngradeAccounts();
}

In an separate command file I run all my different functions. See here complete command file:

namespace Mtr\MyBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class Maintenance extends ContainerAwareCommand
{
    public function checkDowngradeAccounts() {
        // get downgrade accounts
        $downgrade = $this->getDoctrine()
            ->getRepository('MyBundle:Account')
            ->findAllWithDowngrade();

    }
}

Only the Symfony $this object is not known in this file link in a normal controller. How can I include or get this container object?

  • 写回答

1条回答 默认 最新

  • douchendan0040 2016-10-02 20:09
    关注

    $this is not available with static context, as same as class dependencies(passed via constructor). you should refactor call chain to Maintenance instance instead of static call

    It is bare PHP, no symfony involved

    UPD.

    Your example still shows that you call this function statically. You should call it using instance of object, i.e $maintenance->checkDowngradeAccounts().

    To create proper maintenance variable you should instantiate it manually or pass it as a dependency via DI.

    The easiest way I see here is do like

    class Maintenance
    {
        private $doctrine;
    
        public function __construct(EntityManagerInterface $doctrine)
        {
            $this->doctrine = $doctrine;
        }
    
        public function checkDowngradeAccounts() {
            // get downgrade accounts
            $downgrade = $this->doctrine
                ->getRepository('MyBundle:Account')
                ->findAllWithDowngrade();
        }
    }
    

    And the command code (ContainerAwareCommand already has access to container, so we can use it configure Maintenance instance.

    protected function execute(InputInterface $input, OutputInterface $output)
    {
       $maintenance = new Maintenance($this->getContainer()->get('doctrine.orm.entity_manager');
       $maintenance->checkDowngradeAccounts();
    }
    

    To make this polished you make Maintenance to be a service. Further read http://symfony.com/doc/current/service_container.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?