palmtree / container
Service Container component for Palmtree PHP
Installs: 4 209
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=7.1
- psr/container: ~1.0
- symfony/yaml: ~4.2
Requires (Dev)
- palmtree/php-cs-fixer-config: ^1.0
- phpunit/phpunit: ~7.5
Provides
- psr/container-implementation: 1.0.0
This package is auto-updated.
Last update: 2024-11-23 04:19:49 UTC
README
A PSR-11 compatible service container
Supports environment variable parameters, factories and private services.
Requirements
- PHP >= 7.1
For PHP >= 5.6 support use v1.0
Installation
Use composer to add the package to your dependencies:
composer require palmtree/container
Usage
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');
Advanced Usage
Factories
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]
Private Services
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) { } }
Prior Art
Inspired by Symfony's DependencyInjection component.
License
Released under the MIT license