Symfony ContainerAwareCommand executed from a custom Application

It is clear that, if you want to use with profit all the services configured/developed on you Symfony application, you have to use a ContainerAwareCommand.

Since the web is plenty of examples, I wont spend time here in writing how to do this and that. What is, instead, quite difficult to find is a way to integrate your brand new command into a Symfony Console application.

If you ended up with something like the following error:

PHP Catchable fatal error:  Argument 1 passed to SymfonyBundleFrameworkBundleConsoleApplication::__construct() must be an instance of SymfonyComponentHttpKernelKernelInterface, none given, called in...


PHP Notice:  Undefined variable: kernel in...  

You just have to instantiate a new Kernel, which is a new Symfony environment. If you spend some more time in understanding why, you’ll notice that it is quite natural. Since you need all the stuff contained into your Symfony Web Application (like the database connection and so on), you’ll have to specify which environment you are going to use (dev or prod or else).

Here there is a raw example:

#!/usr/bin/env php
<?php // application.php use MyBundleConsoleCommandAddCustomerCommand; use SymfonyBundleFrameworkBundleConsoleApplication; use SymfonyComponentDebugDebug; $loader = require_once __DIR__.'/app/bootstrap.php.cache'; Debug::enable(); require_once __DIR__.'/app/AppKernel.php'; $kernel = new AppKernel('dev', true); $kernel-&gt;loadClassCache();

$application = new Application($kernel);
$application->add(new AddCustomerCommand);