fowlerwill/attribute-injection

基于属性的PHP依赖注入

dev-master 2022-10-12 03:10 UTC

This package is auto-updated.

Last update: 2024-09-12 07:27:49 UTC


README

听起来很吸引人,不是吗?!好吧,这个项目旨在成为一个简单的容器,可以帮助你防止依赖地狱。

快速开始。

// Map interfaces to concrete classes.
$dependencyMap = [
    MyDependencyInterface::class => MyDependencyPort::class
];

// Pass them to the container.
$container = new Container($dependencyMap);

// Annotate your classes with #[Injected] on properties or constructor params.
class Main 
{
    #[Injected]
    protected MyDependencyInterface $dependency;

    protected MyOtherDependencyInterface $otherDependency;

    public function __construct(MyOtherDependencyInterface $otherDependency)
    {
        $this->otherDependency = $otherDependency;
    }
}

$main = $container->make(Main::class);

// Now the dependency will be fulfilled, and you can call methods that rely
// on them.
$main->whateverMethod();

开始。

假设你有一个想要从第三方引入的依赖,你真正应该做的是编写一个接口,用于你需要的方法,以及一个与依赖交互的端口。这样,第三方依赖就被隔离到一个单独的端口,不会污染你的代码。

该项目预期使用方式是,首先在你的项目中引入它

$ composer require fowlerwill/attribute-injection

然后,你可以实例化容器,并向它提供依赖到端口的映射接口。

// Somewhere like index.php or during bootstrap of your application.
$dependencyMap = [
    MyDependencyInterface::class => MyDependencyPort::class
];

$container = new Container($dependencyMap);

其中 MyDependencyInterface.php 可能看起来像这样

interface MyDependencyInterface
{
    public function party(): string;
}

MyDependencyPort.php 可能看起来像这样

use FowlerWill\AttributeInjection\Injected;
use Thirdparty\Dependency\SomeDependency;

class MyDependencyPort implements MyDependencyInterface
{

    #[Injected]
    protected SomeDependency $dependency;


    public function party(): string
    {
        return "party, " . $this->dependency->partyHard();
    }
}

注意,我们在这里使用了PHP属性 #[Injected] 来将依赖一起带入,当我们使用接口的类来整合一切时...

use FowlerWill\AttributeInjection\Injected;

class Main
{

    #[Injected]
    protected MyDependencyInterface $dependency;

    public function itsTimeToParty(): string
    {
        return "I believe it's time to ".$this->dependency->party();
    }
}

然后在我们的应用程序中,通过容器实例化类,并可以使用提供到类属性的依赖。

$main = $container->make(Main::class);

echo $main->itsTimeToParty();

贡献。

首先,我很荣幸你愿意为项目做出贡献,所以感谢你考虑。我对这个项目有很多想法,但在这个阶段非常欢迎PR,以帮助它成长到你需要的用例。

开始。

$ composer install

测试。

要本地运行测试

$ composer run test

在docker上运行测试,并生成覆盖率报告

$ composer run test-docker