ixmanuel/nexus

该库管理内部构建者协作者的依赖。

1.0.0 2016-08-13 05:29 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:58:40 UTC


README

Build Status

在构建时映射依赖

这将在构造函数中注册协作者(依赖),以便解耦方法中的对象创建。

关键词

反转控制,依赖注入,构建器

目标

通过避免方法中的硬编码引用,实现可测试、可重用和可维护的代码。

优点

  • 仅在构造函数中创建协作者(即依赖)。
  • 避免全局依赖注入容器。
  • 切换默认实现和测试对象。

语言的优势

  • 使用其命名空间引用类和接口。

替代方案

  • 使用映射。
  • 匿名类。
  • 传递空对象以创建完全可识别的对象。
  • 为每个协作定义和实现一个接口。

以下是一个从数据存储中重新构建实体的示例。

您只需要传递接口及其实现。
    // It reconstitutes a person from a data store: PersonID is a kind 
    // of Identity as much as an AboutMe is a kind of About and both
    // of them are collaborators. Take note that the creation is
    // delayed until need it, but it is not a Singleton.

    // Testing purposes.
    $person = new PersonFromStore(
        new FetchedPerson($id), TestPersonID::class, AboutMe::class
    );   

    // Application.
    $person = new PersonFromStore(
        new FetchedPerson($id), PersonID::class, AboutMe::class
    );  

    // Description
    final class PersonFromStore implements Party
    {
        private $record;
        private $identity;
        private $about;

        public function __construct(IdentityRecord $record, string $identity, string $about)
        {
            $this->record = $record;        

            $this->identity = new Assignment(Identity::class, $identity);

            $this->about = new Assignment(About::class, $about);
        }

        // Please, your ID?
        public function identity() : Identity
        {
            // It calls the main constructor or the operator "new" in the ID class.
            // Same as: new PersonID(...)
            return $this->identity->new($this->record->key());
        }

        // Tell me something about you.
        public function about() : About
        {
            // It calls a convenience constructor in the AboutMe class.
            // Same as: AboutMe::withID(...)
            return $this->about->withID($this->identity());
        }
    }  

对PHP社区的一个建议。

    // Definition
    final class PersonFromStore implements Party 
    {
        // It can use another word, such as join, to avoid conflicts with traits.
        use (Identity, About);

        public function identity() : Identity
        {
            return new Identity($record->key());
        }

        ...               
    }

    // Client
    $person = new PersonFromStore($fetchedPerson) use (PersonID, AboutMe);
    // Test
    $person = new PersonFromStore($fetchedPerson) use (TestPersonID, AboutMe);

现在,我们可以从它们的接口创建对象,因此方法中不再有硬编码的依赖。