akrabat / slim3-skeleton

Simple Slim Framework 3 skeleton with Twig & Monolog
BSD 3-Clause "New" or "Revised" License
344 stars 99 forks source link

Full DI container to HomeAction __construct? #8

Closed prostoroman closed 9 years ago

prostoroman commented 9 years ago

Hello, Dear Rob.

Thank you for great code!

Is it possible to put full DI container to HomeAction construct method?

slim3-skeleton/app/src/Action/HomeAction.php:

    public function __construct(Twig $view, LoggerInterface $logger)
    {
        $this->view = $view;
        $this->logger = $logger;
    }

change to something like this:

    public function __construct(ContainerInterface $container)
    {
        $this->view = $container['view'];
        $this->logger = $container['logger'];
        $this->db = $container['db'];
        $this->flash = $container['flash'];
    }

In order to have access to full list of dependencies from class? Or it's a bad idea?

If I need a logger, view, flash, database mapper etc in one place.

akrabat commented 9 years ago

Yes, you can do that. It's known as Service Location and is considered by some to be an anti-pattern. See https://adamcod.es/2013/11/25/service-locator-vs-dependency-injection-container.html for a good explanation of the differences.

It does however work!

The main risks are related to the fact that you can now access anything that's in your container within the controller which can lead to scope creep and hidden dependencies in your controller. Testing is also harder as you now have to mock the container too.

prostoroman commented 9 years ago

Ok, I understand, thank you!