sergonie/container

PSR-11 兼容的依赖注入容器

v1.0.0-alpha 2021-03-05 00:39 UTC

This package is auto-updated.

Last update: 2024-09-26 20:17:47 UTC


README

是一个符合 psr-container 的轻量级服务定位模式实现。

此包基于 Igni Container

特性列表

  • 简单用法 如果你熟悉 psr-container,则基本用法无需学习曲线
  • 上下文感知 你可以为特定的用例定义自定义服务实例。
  • 自动绑定 所需的依赖关系将自动注入到你的服务中

安装

composer install sergonie/container

基本用法

<?php
$serviceLocator = new Sergonie\Container\ServiceLocator();
$serviceLocator->set('my_awesome_service', new stdClass());

$myService = $serviceLocator->get('my_awesome_service');

var_dump($myService === $serviceLocator->get('my_awesome_service')); // returns true

注册共享服务

共享服务是只实例化一次并保留在注册表中的服务。每次从容器请求服务时,都会返回相同的实例。

<?php
use Sergonie\Container\ServiceLocator;

class Service 
{
    public $a;
    
    public function __construct(int $a = 1) 
    {
        $this->a = $a;    
    }
}

$serviceLocator = new ServiceLocator();
$serviceLocator->share(Service::class, function() { return new Service(2); });

var_dump($serviceLocator->get(Service::class)->a === 2); //true
var_dump($serviceLocator->get(Service::class) === $serviceLocator->get(Service::class)); // true

因式分解服务

因式分解服务每次容器被请求服务时都会实例化。

<?php
use Sergonie\Container\ServiceLocator;

class Service 
{
    public $a;
    
    public function __construct(int $a = 1) 
    {
        $this->a = $a;    
    }
}

$serviceLocator = new ServiceLocator();
$serviceLocator->factory(Service::class, function() { return new Service(2); });

var_dump($serviceLocator->get(Service::class)->a === 2); //true
var_dump($serviceLocator->get(Service::class) === $serviceLocator->get(Service::class)); // false

自动绑定

自动绑定允许你简单地传递完全限定的类名和该类的所有类型提示参数,容器将自动解析这些参数。

<?php
use Sergonie\Container\ServiceLocator;

class A
{
    
}

class Service 
{
    public $a;
    public $number;
    
    public function __construct(int $number = 7, A $a) 
    {
        $this->number = $number;
        $this->a = $a;    
    }
}

$serviceLocator = new ServiceLocator();
$serviceLocator->share(A::class);
$serviceLocator->share(Service::class);

var_dump($serviceLocator->get(Service::class)->a instanceof A);// true