我正在使用Slim Framework
v3 for PHP,这是我在一个类中用于创建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
在决定是否应阻止用户之前,我需要访问该对象。
谢谢
我只是这样做解决了:
if ( !$check ) {
return $response->withStatus(403);
}
在我的$this->slim->add()
职能上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句