You can install this plugin into your CakePHP application using composer.
The recommended way to install composer packages is:
composer require passchn/cakephp-simple-di
Load the plugin:
bin/cake plugin load SimpleDI
In your Application.php
:
public function services(ContainerInterface $container): void
{
Configure::load('app_di');
$di = new DIManager([
ServiceFactoryManager::class => Configure::readOrFail('DI.services'),
]);
$di->addDependencies($container);
}
Then, define Factories in your app_di.php
:
return [
'DI' => [
'services' => [
NewsletterService::class => NewsletterServiceFactory::class,
CheckoutService::class => CheckoutServiceFactory::class,
PaymentService::class => fn () => new PaymentService(),
],
],
];
Factories should be Invokables or class-strings of Invokables. It is best to
implement \SimpleDI\Module\DI\InvokableFactoryInterface
.
You can then use the Service e.g. in Controller Actions:
class ExamplesController {
public function someAction(NewsletterService $service): Response
{
$service->doSomething();
}
}
If real DI is not possible, e.g. in ViewCells, you can use the ServiceLocator
to receive the container or Services.
\SimpleDI\Module\ServiceLocator\ServiceLocator::getContainer(); // the container instance
\SimpleDI\Module\ServiceLocator\ServiceLocator::get(NewsletterService::class); // the service
This only works if you loaded the plugin or registered the container yourself, e.g.:
// in your Application::services()
ServiceLocator::setContainer($container);