tonis/dispatcher

此包已被废弃,不再维护。未建议替代包。

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

dev-master / 1.0.x-dev 2015-06-17 14:32 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:48:05 UTC


README

Build Status Code Coverage Scrutinizer Code Quality

安装

Tonis\Dispatcher可以使用composer安装,它将为您设置自动加载。

composer require tonis/dispatcher

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

调度

调度可以通过Dispatchable接口、Closurecallableinvokable来实现。

Dispatchable

Dispatchable接口有一个接受参数数组的dispatch方法。这种方式在调度时没有反射,因此是性能最高的。

use Tonis\Dispatcher\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 Tonis\Dispatcher\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 Tonis\Dispatcher\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 Tonis\Dispatcher\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 Tonis\Dispatcher\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()的简单代理调用。