我正在学习Phalcon (在多模块应用程序模板中尝试REST ),并且对每个请求做了简单的检查,例如x-api-key (类似于ASP.NET MVC中的ActionFilters )。
annotations,plugins,beforeExecuteRoute,和beforeException.一起做但是当我编写其中一个throw new \Exception("Some exception", 500);时,Phalcon返回一个没有异常消息和代码的空白页面。AFAIK这是一个已知的错误。beforeException:中的dispatcher做这件事 public function beforeException($event, $dispatcher, $exception)
{
if ($exception instanceof \Phalcon\Http\Request\Exception)
{
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'showInternalServerError'
)
);
return false;
}
//...
}这似乎很有效,但这不是一个优雅的解决方案,我懒得这么做:)
问题:您有什么更好的方法在PhalconPHP中做ActionFilters吗?
发布于 2015-05-18 18:17:28
看看cmoore4 4/phalcon-rest/HTTPException上的解决方案
当应用程序抛出一个HTTPError时,这个应用程序将修改响应对象,以反映错误细节和标题,并将其发送到输出。
我喜欢在REST实现上执行许多事情的cmoore4方式。
发布于 2015-10-20 09:56:09
您可以使用匹配回调来检查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
https://stackoverflow.com/questions/26357135
复制相似问题