此包已被弃用且不再维护。没有建议的替代包。

Popeye 是一个受 Slim 微型框架启发的通用中间件堆栈

1.1 2018-10-10 07:10 UTC

This package is auto-updated.

Last update: 2022-11-29 02:31:03 UTC


README

Build Status Coverage Status

Popeye 是一个通用中间件堆栈 - 因为 HTTP 不是唯一需要中间件的。

使用方法

这是一个小巧的库,非常易于使用。它与 Slim 的中间件实现类似,但它不特定于 HTTP - 可以在任何上下文中使用。以下是一个添加一些类型安全的示例。

<?php

use Popeye\HasMiddleware;
use Popeye\Lockable;

class SpecificMiddleware
{
    use HasMiddleware;

    public function __invoke(CertainType $input)
    {
        return $this->runStack($input);
    }

    public function add(CertainHandler $handler)
    {
        return $this->addHandler([$handler, 'handle']);
    }
}

interface CertainType
{
    public function getFoo();
    public function getBar();
}

interface CertainHandler
{
    public function handle(CertainType $input);
}

上面的代码确保只有特定实现类型的中间件可以被添加,以及只有特定的值可以传递给它们,从而确保尽可能多的类型安全。它还实现了魔法 __invoke() 方法,因此中间件的一个实例可以直接被当作可调用对象处理,这可能或可能不适合您的应用程序。
然而,这个例子有点复杂,并且效率不高,因为即使堆栈最终没有调用它,也必须实例化每个处理器对象。

考虑将其与提供依赖注入的框架结合使用,例如 Laravel。这样,您就能利用其能力在可调用或为您构造和调用对象上自动注入依赖。
这可以通过以下方式实现。当然,可以使用任何其他 DI - 在这个方面,这个库没有特定的观点。

<?php

use Popeye\HasMiddleware;
use Popeye\Lockable;

class ContainerAwareMiddleware
{
    // use Lockable; // add this if you want to restrict middleware modifications once its being resolved.
    use HasMiddleware;

    public function add(string $handler)
    {
        return $this->addHandler($handler);
    }

    public function resolve()
    {
        return $this->runStack($input);
    }

    /**
     * Override the trait method to use the Laravel DI container to call the handler.
     */
    protected function callHandler($handler)
    {
        // have laravel construct and call the handler
        app()->call($handler);
    }
}

当然,使用这种方法我们失去了类型安全,因此您必须小心添加处理器,以便它们与中间件最终解决的方式兼容,尽管 Laravel 会尽力解决未指定的事情。我们可能无法拥有一切 ...

许可

Popeye 使用 MIT 许可证。