cairns/shields

该软件包已被废弃,不再维护。未建议替代软件包。
该软件包最新版本(0.1.1)没有可用的许可信息。

0.1.1 2014-08-28 16:22 UTC

This package is not auto-updated.

Last update: 2017-08-02 14:41:29 UTC


README

Shields 帮助在请求和您的 API 之间创建一个屏障。Shields 提供了一种方法,根据一组简单的规则在请求到达应用程序的其余部分之前过滤请求。这有助于尽早且一致地针对格式错误的请求失败,因此您不需要在控制器中持续处理这些问题。

为什么使用 Shields?

  • 允许将简单的请求检查抽象为独立的类。
  • 通过删除“输入检查”if语句的数量来减少控制器膨胀。
  • 高度可配置、可扩展且与框架无关。

Shields 可以检查什么?

  • 发送了所需的参数。
  • 确保两个字段匹配,例如密码确认。
  • 通过自定义守卫检查您想要的任何内容。

要求

以下版本的 PHP 受此版本支持。

  • PHP 5.4
  • PHP 5.5
  • PHP 5.6
  • HHVM

安装

安装 Shields 的主要方式是通过 Composer

{
    "require": {
        "cairns/shields": "~0.1"
    }
}

入门

设置 Shields 时,您可以提供可以使用的守卫数组。此列表可以通过您自己的守卫进行自定义,但是已经提供了一些用于常见检查的守卫。

例如,要仅对输入运行一些简单的检查,您的配置可能如下所示

use Cairns\Shields\ShieldManager;
use Cairns\Shields\Guards\ArrayGuard;

$shields = new ShieldManager([
    'post' => new ArrayGuard($_POST)
]);

示例用法

继简单设置之后,我们可以看看对登录尝试的简单用例。

此操作的示例 shield 可能如下所示

use Cairns\Shields\ShieldFilterAbstract;

class LoginControllerShield extends ShieldFilterAbstract
{
    public function post()
    {
        $this->post->required('username');
        $this->post->required('password');
    }
}

... 然后,您的控制器可能如下所示

use Cairns\Shields\ShieldManager;

class LoginController
{
    private $shield;

    public function __construct(ShieldManager $shield)
    {
        $this->shield = new LoginControllerShield($shield);
    }

    public function post()
    {
        $this->shield->post();

        // shields are down, you may proceed.
    }
}

管理器

ShieldManager 控制护盾。它包含可用的守卫列表以及确定在需要升起护盾时会发生什么。

创建管理器时,您可以设置一些数据


$shields = new Cairns\Shields\ShieldManager([
    // Guards go here!
]);

// Set the error handler
$shields->setErrorHandler(function ($exception) {
    // What happens when something goes wrong.
    // Default: throw $exception;
});

守卫

将守卫视为传感器 - 确定哪些请求可以通过护盾的工具。

守卫是非常简单的检查,可以在请求到达控制器之前快速运行。失败的守卫将调用 $this->raiseShields(...) 并传递一个扩展 \Cairns\Shields\Exceptions\ShieldsUpException 的异常。

让我们快速看一下守卫的结构;

use Cairns\Shields\Guars\BaseGuard;
use Cairns\Shields\Guars\GuardInterface;
use Cairns\Shields\Exceptions\ShieldsUpException;

class ExampleGuard extends BaseGuard implements GuardInterface
{
    public function checkSomething()
    {
        // If a check fails, the shields are raised.
        if (false) {
            $this->raiseShields(new ShieldsUpException);
        }

        return true;
    }
}

在将守卫添加到 ShieldManager 时,确保其索引适当,以便在过滤器中可访问。

use Cairns\Shields\ShieldManager;

$shields = new ShieldManager([
    'example' => new ExampleGuard
]);

然后,您可以使用以下代码运行检查

$this->example->checkSomething();

待办事项

  • 设置 TravisCI
  • 设置 Scrutinizer
  • 提高测试覆盖率
  • 将 badges 更新到 README.md

思考

  • 考虑抛出异常而不是 $this->fail(...)

致谢

授权

MIT许可证(MIT)。请参阅LICENSE文件以获取更多信息。