Symfony Console Application: Dependency Injection

The symphonic newbie is here. After reading some Symfony docs and some answers here in SO, I am now almost completely confused. I am trying to use a console application component and create a small console application with db support.

Many argue that to use the functions of Symfony DI, it would be sufficient to inherit my command class not from Symfony \ Component \ Console \ Command \ Command, but from ContainerAwareCommand. However, when I try to do this, I get a Method Not Found error when I call application :: getKernel ().

I have the feeling that the DI features are not actually available in a console application based on a console component. Is there another Symfony console application, for example, based on a full-blown structure?

I really like the simple structure provided by the symfony \ Component \ Console \ Application console component. But the question then is what to do for dependency injection and DBAL? All the examples that I find relate to the full structure of Symfony and make me linger.

+4
source share
3 answers

Just a quick update of my progress if someone stumbles upon the same problems.

  • PHP-DI, , , , ( ) - .
  • Doctrine\DBAL ( O/RM, , SQL, - ) , , DI.

, , - , , DI, getDefaultCommands(), . , .

+3

ContainerAwareCommand

...
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
...

class MyCommand extends ContainerAwareCommand
{

DI getContainer(). (, ), :

$this->validator = $this->getContainer()->get('validator');
+1

, , , .

​​ \Symfony\Bundle\FrameworkBundle\Console\Application, \Symfony\Component\Console\Application.

<?php
// CronRun.php

require __DIR__.'/../../../../vendor/autoload.php';
require_once __DIR__.'/../../../../app/AppKernel.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();

$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->add(new \KingdomHall\TaskBundle\Command\CronCommand());
$input = new \Symfony\Component\Console\Input\StringInput('k:c:r');
$application->run($input);
0

All Articles