0

I'm new to this and still trying to wrap my head around DI while creating a small project using Slim Framework.

Is it a bad practice to set an $app on the container like this?

$container = $containerBuilder->build();

AppFactory::setContainer($container);
$app = AppFactory::create();

$container->set('app', $app);

The reason I want to do this is to have abstract class with $container and $app instances available without having to pass it as constructor parameters. For getting the container instance, I used this piece of code from Slim' documentation.

<?php
declare(strict_types=1);

namespace Testing;

use Psr\Container\ContainerInterface;
use Slim\App;

abstract class Service
{
    protected ContainerInterface $container;
    protected App $app;


    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->app = $this->container->get('app');
    }

}

I would then want to instantiate the classes extending Service abstract class like this:

$serviceExample = $container->get(ServiceExample::class);

It IS working, but I feel like I'm doing something really wrong and there must be a better solution. If so, can you please help and point me in the right direction?

vrerabek
  • 183
  • 1
  • 14

1 Answers1

1

If you are using a DI container (and dependency injection), you should not use the container- or the Slim App instance within your application classes because this is an anti-pattern.

Instead you just need to declare all dependencies directly the the class constructor and let the DI container do the rest of the work.

<?php

final class MyService
{
    private MyRepository $repository;

    public function __construct(MyRepository $repository)
    {
        $this->repository= $repository;
    }

}
odan
  • 4,757
  • 5
  • 20
  • 49
  • Thanks for the answer! I will read more into DI. It just really felt weird to me accesing the container, that's why I made this thread. – vrerabek Oct 04 '21 at 14:22