korim/null-object

空对象生成器

1.0.4 2023-09-29 06:40 UTC

This package is auto-updated.

Last update: 2024-09-03 03:05:58 UTC


README

codecov Type Coverage Continuous Integration

从接口生成一个空对象。它是为了测试和AOP而创建的。

安装

composer require --dev koriym/null-object

入门

从接口实例化空对象。

interface FooInterface
{
   public function do(): void;
}
$nullObject = $this->nullObject->newInstance(FooInterface::class);
assert($nullObject instanceof FooInterface);
$nullObject->do(); // nothing's going to happen

newInstance() 定义了一个具有 eval 的类,但使用 save() 将生成的代码保存到文件中。

$class = $this->nullObject->save(FooInterface::class, '/path/to/saveDirectory');
assert(new $class instanceof FooInterface);

即时生成

如果这样听起来不太疯狂,也可以通过简单地在接口名称后添加 Null 后缀来创建空对象,通过注册自动加载器来实现。

$loader = require __DIR__ . '/vendor/koriym/null-object/autoload.php';
spl_autoload_register($loader);

或者在 composer.json 中添加到 autoload-dev

    "autoload-dev": {
        "files": ["./vendor/koriym/null-object/autoload.php"]
    }

您可以通过以下方式创建空对象。

$nullClass = FooInterface::class . 'Null'; // add Null suffix to the interface
$foo = new $nullClass;  // instantiate a NullObject
assert($foo instanceof FooInterface);

注意

尚不支持继承的接口。