spiffy/spiffy-dispatch

该软件包已被废弃且不再维护。未建议替代软件包。

Spiffy\Dispatch 是一个轻量级、HHVM 兼容且无依赖的调度库。

1.0.0-alpha 2014-07-15 22:03 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:37:09 UTC


README

Build Status Code Coverage Scrutinizer Code Quality

安装

Spiffy\Dispatch 可以使用 composer 安装,这将为您设置自动加载。

composer require spiffy/spiffy-dispatch

此外,您还可以下载或克隆仓库并设置自己的自动加载。

调度

调度可以通过 Dispatchable 接口、Closurecallableinvokable 来完成。

Dispatchable

Dispatchable 接口有一个接受参数数组的 dispatch 方法。这种方式调用调度不涉及反射,因此性能最佳。

use Spiffy\Dispatch\Dispatcher;

class TestDispatchable implements Dispatchable
{
    public function dispatch(array $params) { return 'foo'; }
}

$d = new Dispatcher();
$d->add('foo', new TestDispatchable());

// outputs 'foo'
echo $d->ispatch('foo');

// the second argument will be passed to the $params array of the dispatch() method
echo $d->ispatch('foo', ['name' => 'bar']);

Closure

通过闭包进行调度对于微框架或快速搭建原型非常有用。

use Spiffy\Dispatch\Dispatcher();

$d = new Dispatcher();
$d->add('foo', function() { return 'foo'; });

// outputs 'foo'
echo $d->ispatch('foo');

// this closure has a default value of 'baz' for the $slug parameter
$d->add('bar', function($id, $slug = 'baz') {
    return $id . ': ' . $slug;
)};

// this uses the default value for $slug
// outputs '1: baz'
echo $d->ispatch('bar', ['id' => 1]);

// this overwrites the default value
// outputs '1: booze'
echo $d->ispatch('bar', ['id' => 1, 'slug' => 'booze']);

Invokable

use Spiffy\Dispatch\Dispatcher;

class TestInvokable implements Dispatchable
{
    public function __invoke($id, $slug = 'baz')
    {
        return $id . ': ' . $slug;
    }
}

$d = new Dispatcher();
$d->add('foo', new TestInvokable());

// this uses the default value for $slug
// outputs '1: baz'
echo $d->ispatch('bar', ['id' => 1]);

// this overwrites the default value
// outputs '1: booze'
echo $d->ispatch('bar', ['id' => 1, 'slug' => 'booze']);

Callable

use Spiffy\Dispatch\Dispatcher;

class TestCallable implements Dispatchable
{
    public function outputId($id)
    {
        return $id;
    }

    public static function outputStaticId($id)
    {
        return $id;
    }
}

$test = new TestCallable();

$d = new Dispatcher();
$d->add('foo', [$test, 'outputId']);

// output is '1'
$d->ispatch('foo', ['id' => 1]);

$d->add('bar', 'TestCallable::outputStaticId');

// output is '2'
$d->ispatch('bar', ['id' => 2]);

懒加载和递归

只要返回一个调度器,调度器就会继续调度。这允许您通过闭包(也是调度器)来懒加载对象。

<?php
use Spiffy\Dispatch\Dispatcher;

$d = new Dispatcher();

// assume the TestDispatchable class from above
// instead of this
$d->add('foo', new TestDispatchable());

// you would do this
$d->add('foo', function() {
    return new TestDispatchable();
});

// the output is identical to the output from Dispatchable above
// the only difference is that it's lazy loaded on dispatch() instead.

为什么使用 ispatch() 而不是 dispatch()

因为它很可爱,就是这样!如果您愿意的话,也可以使用 dispatch(),因为 ispatch() 只是 dispatch() 的简单代理调用。