https://github.com/passchn/cakephp-simple-di
Dependency Injection plugin for CakePHP
https://github.com/passchn/cakephp-simple-di
cakephp cakephp4 cakephp5 dependency-injection php php82
Last synced: about 2 months ago
JSON representation
Dependency Injection plugin for CakePHP
- Host: GitHub
- URL: https://github.com/passchn/cakephp-simple-di
- Owner: passchn
- Created: 2024-02-24T16:38:56.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-08-18T18:14:23.000Z (over 1 year ago)
- Last Synced: 2025-10-10T17:29:43.512Z (5 months ago)
- Topics: cakephp, cakephp4, cakephp5, dependency-injection, php, php82
- Language: PHP
- Homepage:
- Size: 23.4 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# SimpleDI plugin for CakePHP
## Installation
You can install this plugin into your CakePHP application using [composer](https://getcomposer.org).
The recommended way to install composer packages is:
```sh
composer require passchn/cakephp-simple-di
```
Load the plugin:
```sh
bin/cake plugin load Passchn/SimpleDI
```
## Usage
In your `Application.php`:
```php
public function services(ContainerInterface $container): void
{
Configure::load('app_di');
DIManager::create($container)
// to add individual services:
->addServices(Configure::readOrFail('DI.services'))
/**
* to collect multiple services, define a module:
* @see \Passchn\SimpleDI\Module\Module\ModuleInterface
*/
->addModules(Configure::readOrFail('DI.modules'))
/**
* a plugin can define multiple modules:
* @see \Passchn\SimpleDI\Module\Plugin\PluginInterface
*/
->addPlugin(SomePlugin::class);
}
```
Then, define Factories/Modules in your `app_di.php`:
```php
return [
'DI' => [
'services' => [
NewsletterService::class => NewsletterServiceFactory::class,
CheckoutService::class => CheckoutServiceFactory::class,
PaymentService::class => fn () => new PaymentService(),
],
'modules' => [
MyModule::class,
],
],
];
```
Factories should be Invokables or class-strings of Invokables.
You can then use the Service e.g. in Controller Actions:
```php
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.
```php
Passchn\SimpleDI\Module\ServiceLocator\ServiceLocator::get(NewsletterService::class); // the service
```
This only works if you loaded the plugin or registered the container yourself, e.g.:
```php
// in your Application::services()
ServiceLocator::setContainer($container);
```