A PSR-11 compatible service container
Supports environment variable parameters, factories and private services.
- PHP >= 7.1
For PHP >= 5.6 support use v1.0
Use composer to add the package to your dependencies:
composer require palmtree/container
Define parameters and services:
# config.yml
parameters:
database_name: 'mydb'
database_user: 'mydb_user'
database_password: '%env(DB_PASSWORD)%'
env(DB_PASSWORD): 123456 # Default env parameter used if environment variable is not set
imports:
- { resource: services.yml }
- { resource: secrets.yml }
# services.yml
services:
my_service:
class: MyNamespace\MyService
arguments: [arg1, '%database_name%']
my_other_service:
class: MyNamespace\MyOtherService
arguments: ['@my_service']
calls:
-
method: doThing
arguments: [arg1, arg2]
# secrets.yml
parameters:
secret: 'TopsyCrett'
Create container:
<?php
use Palmtree\Container\ContainerFactory;
$container = ContainerFactory::create('config.yml');
$container->get('my_service')->myMethod();
$container->getParameter('db_username');
Services can be created by calling static factory methods. Arguments are passed to the factory method.
# services.yml
services:
my_service:
factory: 'MyNamespace\MyFactory:createService'
arguments: [argForCreateService]
Services can be defined as private, meaning they can only be used via dependency injection and cannot be retrieved from the container directly:
# services.yml
services:
my_service:
class: MyNamespace\MyService
public: false
my_consumer:
class: MyNamespace\MyConsumer
arguments:
- "@my_service"
The following will throw a ServiceNotPublicException:
<?php
$container->get('my_service');
Whilst the following will work:
<?php
namespace MyNamespace;
class MyConsumer {
public function __construct(MyService $myService) {
}
}
Inspired by Symfony's DependencyInjection component.
Released under the MIT license