divsmith/airlock

本包的最新版本(1.0.1)没有提供许可证信息。

用于非接口符合依赖项的IoC。

1.0.1 2014-07-31 15:09 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:28:34 UTC


README

Airlock是一个简单的抽象适配器类,为未指定自身接口的依赖项提供解耦。

安装

通过在您的composer.json文件中添加以下内容来安装Airlock

{
    "require": {
        "divsmith/airlock": "1.*"
    }
}

使用方法

  1. 创建一个接口,指定将要依赖的实体依赖项的方法。

    interface ExampleInterface {
        public function method1($args);
        public function method2($args);
        etc...
    }
  2. 创建一个扩展Airlock并实现该接口的适配器类。

    class ExampleInterfaceAdapter extends \Airlock\Airlock implements ExampleInterface {
    
        public function method1($args)
        {
            return $this->delegate(__FUNCTION__, func_get_args());
        }
    
        public function method2($args)
        {
            return $this->delegate(__FUNCTION__, func_get_args());
        }
    
    }

    每个方法都需要包含

    return $this->delegate(__FUNCTION__, func_get_args());

    否则它将不会按预期工作。

  3. 通过适配器构造函数注入实体依赖项。这可以通过使用预定义的Airlock构造函数

    $adapter = new ExampleInterfaceAdapter(new ConcreteDependency());

    或通过IoC容器类型提示和注入来完成

    class ExampleInterfaceAdapter extends\Airlock\Airlock implements ExampleInterface {
    
        public function __construct(\Namespace\ConcreteDependency $dependency)
        {
            $this->locker = $dependency;
        }
    
        ...
    }
  4. 享受吧!现在您可以通过接口类型提示和注入适配器来代替实体依赖项(假设适当的IoC绑定)。就像使用实体依赖项一样使用适配器,并在夜晚安心地知道您的代码已经从它解耦。

其他使用方法

您可以使用Airlock与空接口,这些接口只是为您的IoC容器提供锁。只需将您的实体依赖项注入到适配器中,让Airlock完成剩下的工作。虽然不如定义良好的接口在架构上稳健,但它让您在不需要定义适配器中的每个方法的情况下,也能从实体依赖项中解脱出来。

interface ExampleInterface {};

class ExampleAdapter extends \Airlock\Airlock implements ExampleInterface{
    
    public function __construct(\Namespace\ConcreteDependency $dependency)
    {
        $this->locker = $dependency;
    }
}