PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 11, 2022

[FIXED] how do I use Symfony console with dependency injection, without the Symfony framework bundle?

 May 11, 2022     dependency-injection, php, symfony, symfony-console     No comments   

Issue

I have a command-line application, which so far uses the Symfony dependency injection component. I now find that I want to add command-line options and improve the formatting of the output, and the Symfony console component seems like a good choice for that.

However, I can't fathom how to get my Symfony console command classes to receive the container object.

The documentation I have found uses the ContainerAwareCommand class, but that is from the FrameworkBundle -- which seems a huge amount of overhead to add to a pure CLI app, as it requires further bundles such as routing, http, config, cache, etc, none of which are of any relevance to me whatsoever here.

(Existing SO question How can i inject dependencies to Symfony Console commands? also assumes the FrameworkBundle, BTW.)

I've made a test repository here with a basic command that illustrates the problem: https://github.com/joachim-n/console-with-di


Solution

Yes, the whole framework isn't required. In your case, first you need to create a kind of entry script. Something like that:

<?php

require 'just/set/your/own/path/to/vendor/autoload.php';

use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\ContainerBuilder;

$container = new ContainerBuilder();
$container
    ->register('your_console_command', 'Acme\Command\YourConsoleCommand')
    ->addMethodCall('setContainer', [new Reference('service_container')]);
$container->compile();

$application = new Application();
$application->add($container->get('your_console_command'));
$application->run();

In this example, we create the container, then register the command as a service, add to the command a dependency (the whole container in our case -- but obviously you can create another dependency and inject it) and compile the container. Then we just create app, add the command instance to the app and run it.

Sure, you can keep all configurations for container in yaml or xml or even using PHP format.



Answered By - E.K.
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing