danmurf/dependencyinjection

一个轻量级、可配置的自动绑定依赖注入容器。

dev-master 2020-08-02 10:41 UTC

This package is auto-updated.

Last update: 2024-09-10 07:31:40 UTC


README

Build Status Scrutinizer Code Quality Code Coverage

依赖注入容器

这是一个轻量级的依赖注入容器,具有多种服务位置策略,包括自动绑定。

要安装,请运行

composer require danmurf/dependencyinjection

已注册服务

<?php

use danmurf\DependencyInjection\ContainerFactory;

class MyClass
{
    public function myAction()
    {
        // Create a container somewhere in your kernel or bootstrap process
        $container = ContainerFactory::createRegistrationOnlyContainer();

        // Create your services and register them with the container
        $myService = new MyService();
        $container->register($myService, 'my.service.id');

        // Access your services elsewhere in your application by their registered id...
        $container->has('my.service.id'); // true
        $myService = $container->get('my.service.id');

        // ... or FQCN
        $myService = $container->get(MyService::class);
    }
}

可配置服务

根据服务定义让容器定位服务。

$config = [
    'my.service.id' => [
        'class' => MyService::class,
        'arguments' => [
            [
                'type' => 'scalar',
                'value' => 123,
            ],
            [
                'type' => 'service',
                'value' => 'another.service.id',
            ],
        ],
    ],
];

$container = ContainerFactory::createConfigurableContainer($config);

// The service will be located and instantiated using the defined config.
$myService = $container->get('my.service.id');

绑定服务到接口

定义您想用于特定接口的服务。

$config = [
    MyInterface::class => [
        'service' => 'my.service.id'
    ],
    'my.service.id' => [
        'class' => MyService::class,
        'arguments' => [
            [
                'type' => 'scalar',
                'value' => 123,
            ],
            [
                'type' => 'service',
                'value' => 'another.service.id',
            ],
        ],
    ],
];

$container = ContainerFactory::createConfigurableContainer($config);

// The service bound to the interface will be returned
$myService = $container->get(MyInterface::class);

自动注入服务

通过允许容器推断配置,快速创建并使用服务。

// This service location strategy still requires config for services with scalar constructor arguments
$container = ContainerFactory::createAutoWireContainer([]);

// Use the FQCN to get your autowired service from the container
$myService = $container->get(MyService::class); // No config required!

许可证

此作品根据MIT许可证提供。有关详细信息,请参阅LICENSE.md。