Tom Tom - 2 months ago 13
PHP Question

How to get Symfony object in command file like in controller

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?

Answer

$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