Slim Framework PHP - 在某些情况下阻止用户访问路由

Slim Framework PHP - block routes access to users in some conditions

我正在为 PHP 使用 Slim Framework v3,这是我在 class 中用来创建我的 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 对用户的访问权限,因此在上述情况下,我需要 return 一个 response 当他们尝试访问应用程序时出现错误路线。 因此,用户在尝试访问 getElementsgetElements2 和所有其他路由时将收到错误消息。

我一直在考虑在 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() 函数中。