本包最新版本(0.1)没有可用的许可证信息。

0.1 2016-04-01 09:38 UTC

This package is not auto-updated.

Last update: 2024-09-24 21:29:25 UTC


README

Build Status

Burlap

Burlap 是一个简单的 PHP 依赖注入容器,灵感来自 Fabien Potencier 的 Fabien PotencierTwittee依赖注入系列

为了与其他组件良好协作,Burlap 实现了来自 容器互操作性标准 的 ContainerInterface 和 Delegate Container 策略。

贡献

注意:此项目不是为生产环境准备的,但欢迎提出建议和提交 Pull Request! :)

安装

在终端中运行 composer require codeeverything/burlap

测试

从项目的根目录运行 vendor/bin/phpunit

示例用法

借鉴 Fabien Potencier 在其依赖注入系列中的示例,让我们想象设置一个邮件服务。

向 Burlap 容器中添加项目遵循与在 AngularJS 中定义服务相同的模式,其中传递一个数组作为唯一参数,数组的最后一个元素是要运行的函数,而所有前面的元素定义了这个函数的依赖项。这些依赖项应该是已注册到 Burlap 中的服务,并作为参数传递给定义的服务。

创建用户名和密码的参数

$sack = new Burlap();
$sack->mailer_user([function () {
    return 'username';
}]);

$sack->mailer_pass([function () {
    return 'password';
}]);

创建一个 mailer_settings 服务来获取这些信息

// when defined, a service receives the container as it's first argument and it's dependencies thereafter
$sack->mailer_settings(['mailer_user', 'mailer_pass', function ($c, $user, $pass) {
    $o = new stdclass();
    $o->user = $user . rand();
    $o->pass = $pass . rand();
    
    // return a single instance of the service by using Burlap's "share" function
    return $c->share('mailer_settings', $o);
}]);

最后,创建 mailer 服务,使用先前定义的服务/参数作为依赖项

$sack->mailer(['mailer_settings', function ($c, $settings) {
    $o = new stdclass();
    $o->one = $settings->user;
    $o->two = $settings->pass;
    $o->three = rand() * 10;
    // return a single instance of the service by using Burlap's "share" function
    return $c->share('mailer', $o);
}]);

服务定义后,我们可以使用它

// setup two mailers, since the service is shared these will be identical
$mailer1 = $sack->mailer();
$mailer2 = $sack->mailer();

// dump the list of defined services
var_dump($sack->container);

容器互操作性

Burlap 尝试与其他组件良好协作,并实现了 容器互操作性标准

这意味着我们也可以以更标准化的方式访问我们的服务,如下所示

$mailer = $sack->get('mailer');

我们还可以检查容器是否有一个给定名称的服务

$hasMailer = $sack->has('mailer');

代理容器

容器互操作性标准还定义了一种两个容器协作的方式,其中一个容器位于另一个容器中,并仅用于向另一个容器中定义的服务提供任何必要的依赖项。

Burlap 通过允许您将代理容器作为构造函数参数传递来实现这一点

// must implement the ContainerInterface
$delegate = new SomeOtherContainer();

$sack = new Burlap($delegate);

处理依赖关系的示例

// must implement the ContainerInterface
$delegate = new Burlap();

// add a service
$delegate->user([function ($c) {
    return '1234';
}]);

// create our Burlap sack, and pass the delegate container
$sack = new Burlap($delegate);

// define a service in Burlap which depends on the service defined in the delegate 
// container and pull in the result of that service as $who
$sack->whoAmI(['user', function ($c, $who) {
    return "$who: I am not a number, I am a free man";
}]);

待办事项

  • 更新文档以显示获取服务的互操作性方式
  • 移除魔法函数 __call() 并将其拆分为 add()get(),以提高性能
    • 保留用于设置和向后兼容获取。但首选使用 ->get(serviceID)
  • 更新测试以检查预期的异常并测试 get() 和 has() 方法
  • 允许“参数”使用 ArrayAccess 设置?仅允许非可调用项... $sack['param1'] = 'this is a param';
  • 允许从容器中使用 ArrayAccess 访问“参数”? $sack['param1']