zfcampus / zf-console

Create console applications in PHP
BSD 3-Clause "New" or "Revised" License
64 stars 25 forks source link

Running with service manager #44

Open wiryonolau opened 6 years ago

wiryonolau commented 6 years ago

Could you gave example how to do dependency injection from service manager ( container interop ) that define in the configuration to the handler ?

jguittard commented 6 years ago

From your console PHP script, chdir to the root, bootstrap composer autoload, and call the container script. Like below:

<?php
use Psr\Container\ContainerInterface;

chdir(__DIR__ . '/../');
require_once 'vendor/autoload.php';

/** @var ContainerInterface $container */
$container = require 'config/container.php';

Later on in the script you can use it in the handler definition:

<?php
use Zend\Console\Console;
// ...

$routes = [
    [
        'name' => 'my-route',
        'route' => '[--foo=]',
        'description' => 'Some really cool feature',
        'short_description' => 'Cool feature',
        'options_descriptions' => [
            'foo'   => 'Lorem Ipsum',
        ],
        'defaults' => [
            'foo'   => 'bar',
        ],
        'handler' => function($route, $console) use ($container) {
            $handler = $container->get(My\Fully\Qualified\Class\Name::class);
            return $handler($route, $console);
        }
    ],
// ...
]
wiryonolau commented 6 years ago

can dispatcher handler the container (servicemanager) stuff ? this look's dirty. loading container in other file, then on route.config.php reuse the container variable.

weierophinney commented 6 years ago

Using closures is valid PHP and an acceptable way to provide lazy-loading.

It's also possible to extend the zf-console dispatcher to do this sort of thing, and that would be an interesting patch for us to consider.

wiryonolau commented 6 years ago

adding handlermanager similar to controllermanager would be nice ( not sure if it is possible to add eventmanager ). handlermanager will use it's own config array instead of putting every handler inside service_manager config.