wamania/container

简单的PHP容器

v0.1 2018-10-08 14:57 UTC

This package is auto-updated.

Last update: 2024-09-09 13:53:32 UTC


README

具有懒加载和自动注入的简单PHP容器

安装

composer require wamania/container

获取服务

您的项目的每个类都可以是一个服务。

<?php

use Wamania\Container;

class OneService
{
}

$container = new Container();
$oneService = $container->get(OneService::class);

如果服务尚未构建且类不存在,则抛出 NotFoundException。

有服务吗?

<?php

use Wamania\Container;

$container = new Container();
$oneService = $container->has(OneService::class);

如果服务已构建或类存在,则返回 true,否则返回 false

自动注入

如果您有服务之间的依赖关系,容器会尝试构建它们(如果可能)。

class OneService
{
}
class AnotherService
{
    private $oneService;
    
    public function __construct(OneService $oneService)
    {
        $this->oneService = $oneService;
    }
    
    public function getOneService()
    {
        return $this->oneService;
    }
}
<?php

use Wamania\Container;

$container = new Container();
$anotherService = $container->get(AnotherService::class);

$oneService = $anotherService->getOneService();

小心循环引用

  • 如果 OneService 需要 AnotherService
  • 并且如果 AnotherService 需要 OneService

容器将抛出 ContainerException。

如果您尝试注入既不是类/服务也不是参数的参数,并且默认情况下不能为 null,它将抛出 ContainerException。

参数

您可以将参数传递给容器并在服务中注入它们。

<?php

class Db
{
    private $host;
    
    private $user;
    
    private $password;

    // we have defined Container::PARAMETER_PATTERN = '_parameter_%s'
    // if the container find the pattern in an argument, it inject the corresponding parameter value
    public function __construct($_parameter_host, $_parameter_user, $_parameter_password)
    {
        $this->host = $_parameter_host;
        $this->user = $_parameter_user;
        $this->password = $_parameter_password;
    }
}
<?php

use Wamania\Container;

$parameters = [
    'host' => 'localhost',
    'user' => 'user',
    'password' => 'secret'
];

$container = new Container($parameters);
$db = $container->get(Db::class);