jtreminio/zimple

为Pimple容器提供包装,添加了几个实用的功能,使代码管理更加容易!

v1.1 2013-08-07 21:44 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:45:11 UTC


README

这是简单Pimple容器的包装。它提供了一些功能,使得处理对象和编写测试更加容易。

如果你的代码库无法进行测试,且无法进行深度重构以使其可测试,那么拥有这样的容器是掌握代码库的好一步。

安装

将其添加到你的 composer.json 文件

"jtreminio/zimple": "1.0.*@dev"

然后运行 ./composer.phar update。这也会安装 Pimple容器

现在只需将其放入你的代码中

Zimple::setPimple(new Pimple);

用法

Zimple接受一个完全限定的名称

$date = Zimple::get('\DateTime');

您还可以传递一个可选的参数数组给对象构造函数

$date = Zimple::get('\DateTime', array('now', Zimple::get('\DateTimeZone')));

默认情况下,每次调用 Zimple::get() 时,Zimple都会返回一个对象的新实例。您可以通过调用 Zimple::set() 并将第三个参数设置为 true 来覆盖此行为

$today = Zimple::get('\DateTime');
$tomorrow = Zimple::get('\DateTime', array('tomorrow'));

// $today !== $tomorrow

Zimple::set('\DateTime', $tomorrow, true);

$tomorrowDup = Zimple::get('\DateTime');

// $tomorrowDup == $tomorrow

$twoDaysAgo = Zimple::get('\DateTime', array('2 days ago'));

// $twoDaysAgo == $tomorrow

您可以在将对象传递给Zimple之前或之后像为Pimple那样定义对象

// From Pimple's homepage
$pimple = new Pimple;

// define some objects
$pimple['session_storage'] = function ($c) {
    return new $c['session_storage_class']($c['cookie_name']);
};

$pimple['session'] = function ($c) {
    return new Session($c['session_storage']);
};

Zimple::setPimple($pimple);

然后像平常一样访问它们: $session = Zimple::get('session_storage');

Zimple的名字很奇怪

Zimple是Pimple的包装,Pimple的名字很糟糕。 SandyZoop 建议我将它命名为Cyst或Zit,这些名字同样糟糕。这个容器的目标是使依赖管理简单易用,并使之前无法测试的代码可测试。

Pimple + Simple = Zimple。

您可以使用以下方式别名

use jtreminio\Zimple\Zimple as Container;
Container::setPimple(new Pimple);
$date = Container::get('\DateTime');

测试

Zimple使在测试中插入模拟变得极其容易。它使用 ::set() 来防止代码覆盖PHPUnit模拟。查看测试以获取几个简单示例。