【发布时间】:2016-08-20 22:55:22
【问题描述】:
我正在为 PHP 使用 Slim Framework v3,这是我在类中用于创建我的 API 的代码:
public function __construct( ) {
$this->slim = new \Slim\App;
$this->init();
$this->slim->run();
}
private function init () {
$this->slim->add(function ($request, $response, $next) {
// my code ...
return $response;
});
$this->slim->get('/getElements', array($this, 'getElements'));
$this->slim->get('/getElements2', array($this, 'getElements2'));
// and more...
}
public function getElements ( $request, $response, $args ) {
// my code ...
}
public function getElements2 ( $request, $response, $args ) {
// my code ...
}
在某些情况下,我需要限制用户访问 API,因此在上述情况下,当他们尝试访问应用程序路由时,我需要返回带有错误的 response。
因此,用户在尝试访问getElements、getElements2 和所有其他路由时会收到错误消息。
我一直在考虑在init() 函数中添加一些代码并在那里阻止用户,但是我可以使用什么代码来做到这一点?
另外,另一种方法是为每个路由回调添加一些代码并执行以下操作:
public function getElements ( $request, $response, $args ) {
echo json_encode(array(
'error' => array(
'msg' => "MESSAGE...",
),
));
return $response;
// my code ...
}
但我有很多路线,我宁愿避开。
有什么想法吗?
编辑:我忘了提到在决定是否应该阻止用户之前我需要访问$request 对象。
谢谢
【问题讨论】:
-
这是中间件的众多用途之一...slimframework.com/docs/concepts/middleware.html