Using Symfony Console with Slim Framework

Symfony console is a very flexible component from Symfony Framework, it allows developers to create CLI apps. Like any good framework component, it’s not tied to it’s original framework, and it can be easily pulled into other apps.

Start by installing the component:

composer require symfony/console

With the module installed, we need to create a file to initialise the console part of your application. This will be the file called by users interacting with your console commands. I would personally organise this into a bin/ folder off the project root directory. The Symfony documentation covers this well:
#!/usr/bin/env php
<?php
// application.php

require __DIR__.'/vendor/autoload.php';

use Symfony\Component\Console\Application;

$application = new Application();

// ... register commands

$application->run();

And you can register commands with:

$application->add(new GenerateAdminCommand());

The only thing missing here is the integration with our Slim app. As it stands, we can’t pass dependencies from our container into any commands. All we need to do for this is to include our Slim dependencies.php file:
require __DIR__ . '/../src/dependencies.php';

We’re then free to access our container, which we can then use to pass dependencies directly into commands.
$service = $container->get(MyService::class);
$application->add(new GenerateAdminCommand($service));

Here’s my full bin/console file:
#!/usr/bin/env php
<?php
// application.php

require __DIR__.'/vendor/autoload.php';
require __DIR__ . '/../src/dependencies.php';

use Symfony\Component\Console\Application;

$application = new Application();

$service = $container->get(MyService::class);
$application->add(new GenerateAdminCommand($service));

$application->run();

See full documentation on Symfony Console here: https://symfony.com/doc/current/components/console.html

2 thoughts on “Using Symfony Console with Slim Framework

  1. Hello. I have an issue where require ‘dependencies.php’ return error “Call to a member function getContainer() on null”. I-m not quite sure how to resolve this issue. Can you maybe show depencencies file?

    • Try adding the following before you include dependencies.php:
      // Instantiate the app
      $settings = require __DIR__ . ‘/src/settings.php’;
      $app = new \Slim\App($settings);

      Let me know you get on!

Leave a Reply

Your email address will not be published. Required fields are marked *