Using ConsoleServiceProvider with Silex

I recently needed a few scripts that run as cronjobs. Symfony has something like the Console Component which gives the possibility to create command line interfaces for your code.

The people from KNPLabs created a ConsoleServiceProvider which Provides a Symfony\Component\Console based console for Silex. Registering this service provider is easy as registering any other service provider. First step is adding the knplabs/console-service-provider to the composer.json file and running composer update.

   "require": {
      "knplabs/console-service-provider": "dev-master"
   "autoload": {
      "psr-0": {"": "src/"}

Next we’ll register the service and set some options:

use Knp\Provider\ConsoleServiceProvider;

* Console Service Provider
$app->register(new ConsoleServiceProvider(), array(
	'' => 'ConsoleApp',
	'console.version' => '1.0.0',
	'console.project_directory' => __DIR__ . '/..'

Next up we’ll have to create a command script which extends the Knp\Command\Command. You’ll have to implement two methods to configure and execute a command. The configure method just defines what kind of commands are available and what kind of options you can use.

protected function configure() {
      ->setDescription('Import all data.')
         'Import for a specific user'
         'If set, the task will run in debug mode'
   ; // nice, new line

If you need the Silex\Application $app you can retrieve it using the getSilexApplication() function (available in the Knp\Command\Command namespace).

Next we need a console script which will use the Command created earlier. This will look something like this:
import console

Tip: If the executing fails, try php -d display_errors script.php to check syntax mistakes.

The execute commands looks like this:

protected function execute(InputInterface $input, OutputInterface $output) {
// use $input->getArgument('userId'); and $input->getOption('debug')

This is actually all you need to do. The configuration in your ImportCommand file will basically tell your console how to use it. Running [path to console file] without arguments will give you output about how to use your options and commands. (ex. app/console/imports).

Output when running the console file without arguments
Output when running the console file without arguments

Wow! Now you can while(true) or for(;;) the shit out of your application!

5 thoughts on “Using ConsoleServiceProvider with Silex

Leave a Reply to Thiago Paes Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s