Skip to content

Latest commit

 

History

History
31 lines (22 loc) · 1011 Bytes

psr11_di.md

File metadata and controls

31 lines (22 loc) · 1011 Bytes

Dependency Injection

Before continue, refer to the Psr11 documentation and the Dependency Injection documentation.

The main advantage of the Dependency Injection is to decouple the code from the implementation. For example, if you want to cache objects for prod environment, but don't for dev environment, you can do it easily by creating different implementations of the same interface.

e.g. config-dev.php:

return [
    BaseCacheEngine::class => DI::bind(NoCacheEngine::class)
        ->toSingleton(),
]

and config-prod.php:

return [
    BaseCacheEngine::class => DI::bind(FileSystemCacheEngine::class)
        ->toSingleton(),
]

To use in your code, you just need to set the environment variable APP_ENV to the environment name (dev or prod) and call:

Psr11::container()->get(BaseCacheEngine::class);

The application will return the correct implementation based on the environment.