phico/container

Phico 的轻量级依赖注入容器

dev-main 2024-09-04 10:39 UTC

This package is auto-updated.

Last update: 2024-09-19 16:31:41 UTC


README

专为 Phico 框架设计的轻量级和专注的依赖注入容器。

安装

使用 composer

composer require phico/container

参考

设置一个描述如何创建类的定义 set(string $classname, callable|string $defintion, array $args =[])

在定义上设置快捷别名 alias(string $name)

在定义上设置共享标志 share(bool $toggle)

返回一个实例化的类 get(string $classname or $alias)

使用

// pass an optional array of parameters through the constructor
$c = new Phico\Container([
    'autowiring' => false, // default is true
    'sharing' => false, // default is true
]);

// use get() to fetch an instantiated class
$foo = $c->get(Foo::class);
// foo is now an instance of Foo

自动装配

启用自动装配后,容器将尽力在没有明确指令的情况下查找和构建类。

当自动装配被禁用时,容器将需要使用 set() 创建定义

// set() accepts a string for simple cases
$c->set(Foo::class, Foo::class);

// or callables for more complex requirements
$c->set(Foo::class, function() {
    return new Foo::class
});

// shorter function syntax is fine too
$c->set(Foo::class, fn() => new Foo());

别名

有时您只是想避免输入,您可以在调用 set() 后使用 alias() 添加别名;

// set an alias to Foo named Bar, now foo can be accessed by get(Bar)
$c->set(Foo::class, Foo::class)
    ->alias('Bar');
$bar = $c->get('Bar');
// bar is now an instance of Foo

共享

有些类在共享时表现更好,默认情况下总是共享实例,但有时您可能需要在每次调用 get() 时获得一个唯一的实例,使用 share() 方法切换此行为,它接受布尔值 true 或 false,并且只会影响当前定义。

$c->set(Foo::class, Foo::class)
    ->share(false);
$a = $c->get(Foo::class);
$b = $c->get(Foo::class);

// $a is not equal to $b, they are different instances

贡献

容器被认为功能完整,但如果您发现它在行为或性能方面有任何错误或问题,请创建一个问题,如果可能,提交一个带有修复的 pull request。

请确保适当地更新测试。

对于重大更改,请首先打开一个问题来讨论您想要更改的内容。

许可

BSD-3-Clause