简体   繁体   中英

How to load bundles in a Symfony console component-based application?

I am probably having some fundamental issue with understanding the Symfony Console component. I am trying to write a console-based application and I wanted to add the Doctrine bundle to it to create ORM-based entities, however, I am not able to load the bundle into my application.

What I found is that I should create app/AppKernel.php and add the bundle there:

public function registerBundles()
{
    $bundles = array(
        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
    );
    return $bundles;
}

I have then also added the AppKernel to the composer.json and dumped composer's autoload files:

"classmap": [ "app/AppKernel.php" ]

However, I am still unable to see any Doctrine commands in my console application's entry point. I don't even think the Kernel is loaded properly, the most confusing part to me is the difference between these two files on Github. First you have the Console component's Application.php which uses strings for its constructor parameters:

https://github.com/symfony/console/blob/master/Application.php

And then there's the same file in the Symfony Framework and that one uses the Kernel as a parameter:

https://github.com/symfony/framework-bundle/blob/master/Console/Application.php

So am I completely on the wrong path here? How do I load bundles / Kernels in a Console Component application? Or do I need the full Symfony package to do this sort of thing? That would seem kind of overkill if I just needed to write a somewhat complex terminal application.

Just in case it is any use, these are the relevant packages in my composer.json :

"symfony/console": "v3.3.*",
"symfony/yaml": "v3.3.*",
"doctrine/orm": "~2.5",
"doctrine/doctrine-bundle": "~1.6",
"doctrine/doctrine-cache-bundle": "~1.2",

If you create a console command which extends the ContainerAwareCommand as described here:

https://symfony.com/doc/current/console.html#getting-services-from-the-service-container

Then you can call:

$em = $this->container->get('doctrine.orm.entity_manager');

Which gives you the EntityManager allowing you to use Doctrine in your command line application. There is no need to edit your AppKernel or composer file to get Doctrine working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM