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?