davidecesarano/embryo-container

一个简单且兼容PSR-11的容器。

2.0.1 2020-12-12 15:18 UTC

This package is auto-updated.

Last update: 2024-09-12 23:36:29 UTC


README

Embryo Container是一个小巧且兼容PSR-11的PHP依赖注入容器。

要求

  • PHP >= 7.1

安装

使用Composer

$ composer require davidecesarano/embryo-container

用法

创建服务

服务通过匿名函数定义,该函数返回对象的实例

$container = new \Embryo\Container\ContainerBuilder;
$container->set('connection', function(){
    return [
        'host' => 'localhost',
        'db'   => 'database',
        'user' => 'user',
        'pass' => 'pass'
    ];
});

$container->set('pdo', function($container){
    $connection = $container->get('connection');
    $mysql = 'mysql:host='.$connection['host'].';dbname='.$connection['db'], $connection['user'], $connection['pass']);
    return new \PDO($mysql);
});

注意,匿名函数可以访问当前容器实例。

使用服务

使用定义的服务

$pdo = $container->get('pdo');

自动注入

容器可以通过自动装配自动创建和注入依赖项。自动装配默认启用。您可以使用容器构建器禁用它。

$container->useAutowiring(false);

自动装配是容器自动创建和注入依赖项的能力。Embryo Container使用PHP的反射来检测构造函数需要哪些参数。

class Person
{
    public function getName()
    {
        return 'David';
    }
}

class Hello
{
    public $name;
    
    public function __construct(Person $person)
    {
        $this->name = $person->getName();
    }
    
    public function getHello()
    {
        return 'Hello '.$this->name;
    }
}

$container = new \Embryo\Container\ContainerBuilder;
$hello = $container->get('Hello');
echo $hello->getHello(); // Hello David

在这个例子中,Embryo Container创建一个Person实例(如果尚未创建)并将其作为构造函数参数传递。

服务提供者

Embryo Container可以在扩展ServiceProvider实例的提供者中定义服务

use Embryo\Container\ContainerBuilder;
use Embryo\Container\ServiceProvider;

class TestServiceProvider extends ServiceProvider 
{
    public function register()
    {
        $this->container->set('testService', function($container){
            $other = $container->get('otherService');
            return 'This is a Test Service! '.$other;
        });
    }
}

$container = new ContainerBuilder;
$test_service_provider = new TestServiceProvider($container);
$test_service_provider->register();
echo $container['testService']; // This is a Test Service!

示例

您可以使用内置的PHP服务器快速测试此功能

$ cd example
$ php -S localhost:8000

访问 https://:8000