此包已被废弃,不再维护。作者建议使用 league/container 包。

由反射驱动的最小PSR-11 PHP DI容器

v0.2.0 2018-01-31 12:20 UTC

This package is auto-updated.

Last update: 2019-08-18 18:30:08 UTC


README

PHP的最小反射驱动的DI容器。

我使用这个容器用于我的个人项目。它还没有准备好稳定发布。我想添加一些测试并尝试找出一些错误。如果你想帮助我,那就太棒了!

安装

composer require mnavarrocarter/bolido

功能

  • 服务自动注入:使用反射,递归地检查构造函数中声明的服务。

  • 参数自动注入:当服务的依赖不是一个类时,尝试猜测你的 snake_case 变量名的 camelCase 值,并在参数包中查找它进行注入。

  • 闭包服务注册:你也可以使用闭包或匿名函数注册服务。这些函数将容器实例作为第一个参数接收。

  • 接口支持:使用注解,你可以在服务的构造函数中指定接口的具体实现。

  • 无需配置文件:无需配置文件。只需创建一个服务类,在构造函数中定义其依赖关系,然后调用它。Bolido将处理一切。

使用

要实例化一个新的容器,只需这样做

<?php

use Bolido\Container;

$container = new Container();

注册服务很容易!

<?php

use Bolido\Container;
    
$container = new Container();

// Using closures
$container->set(SomeService::class, function($con) {
    return new SomeService($con->getParameter('something'));
});

要获取容器的任何类的实例,只需使用类的常量,Bolido会找到它。(别忘了使用声明!)。如果没有在容器中找到,它将返回一个新实例。

<?php

$service = $container->get(SomeService::class);  

你还可以存储参数,并获取它们

<?php

use Bolido\Container;
        
$container = new Container();

$parameter = 'some-value';
$container->setParameter('parameter_name', $parameter);

$container->getParameter('parameter_name'); // 'some-value'

对于注册具有复杂配置的第三方服务,只需创建一个适配器

<?php

use Bolido\Container;
            
$container = new Container();
$container->setParameter('views_dir', '/resources/views');

class Twig extends \Twig_Environment 
{    
    // Note that camelCase non type-hinted params are converted to snake_case,
    // searched in the container and fetched it found.
    public function __construct($viewsDir) {
        $loader = new \Twig_Loader_Filesystem([$viewsDir]);
        parent::__construct($loader);
    }    
}

$twig = $container->get(Twig::class);

$twig->render('some-html', ['data]);

反射容器的一个常见问题是当在构造函数中声明一个接口时。你可以使用 @Resolve 注解来指定接口的具体实现,指定接口的 短名 和具体实现的 FQCN

<?php

use Bolido\Annotation\Resolve;
use App\Service\SomeServiceInterface;

class SomeService
{
    $private service;
    
    /**
     * @Resolve("SomeServiceInterface", concrete="App\Service\SomeConcreteService")
     */
    public function __construct(SomeServiceInterfce $serviceName)
    {
        $this->service = $serviceName;
    }
}

容器注入

不建议这样做,但如果你想将整个容器注入到服务或其他类中,只需让这个类使用 ContainerAwareTrait。在实例化过程中,Bolido会检测到这个特质并将自身的一个实例注入到该类中。