2

我正在学习 Phalcon(在多模块应用程序模板中尝试 REST API),并且我对每个请求进行了简单的检查,例如“此请求是否包含特定的标头” x-api-key(类似于 ASP.NET MVC 中的 ActionFilters)。

  1. 我尝试使用annotations, plugins,beforeExecuteRoutebeforeException. 但是当我写其中一个时,throw new \Exception("Some exception", 500);Phalcon 返回一个空白页,没有异常消息和代码。AFAIK 这是一个已知的错误。

  2. 我试图用dispatcherin做到这一点beforeException

     public function beforeException($event, $dispatcher, $exception)
     {
        if ($exception instanceof \Phalcon\Http\Request\Exception)
        {
            $dispatcher->forward(
                    array(
                        'controller' => 'error',
                        'action' => 'showInternalServerError'
                    )
            );
            return false;
        }
        //...
      }

看来这很有效,但这不是一个优雅的解决方案,我对此太懒了:)

问题:你有什么更好的想法如何在 PhalconPHP 中做 ActionFilters 吗?

4

2 回答 2

1

看一下cmoore4/phalcon-rest/HTTPException上的解决方案

当应用程序抛出 HTTPError 时,它会修改响应对象以反映错误详细信息和标头并将其发送到输出。

我喜欢在 REST 实现上做很多事情的 cmoore4 方式。

于 2015-05-18T18:17:28.393 回答
0

您可以使用 Match Callbacks 来检查您的 api 密钥:

假设您有以下路线:

$router->add('/api/v1', array(
    'module'     => 'api',
    'controller' => 'index'
))

您可以像这样预先检查它:

$router->add('/api/v1', array(
    'module'     => 'api',
    'controller' => 'index'
))
->beforeMatch(array(new AuthenticationFilter(), 'check'));

在您自定义创建的 AuthenticationFilter 中,您可以检查有效的 api 密钥:

<?php

class AuthenticationFilter
{

    public function check($uri, $route)
    {
        $response = new \Phalcon\Http\Response();

        if ($response->getHeaders()->get('X-Api-Key') != 'XYZ')
        {

            throw new CustomAuthenticationErrorExteption('Api Key Invalid');

            // you can also just return false here and redirect to a default non-authenticated 404 response

        }

        else return true;

    }

}

参考

https://docs.phalconphp.com/en/latest/reference/routing.html#match-callbacks

于 2015-10-20T09:56:09.470 回答