首页 > 解决方案 > PHP Slim 3 API 中间件类不能来自 __invoke 的方法?

问题描述

我正在尝试为我的 API 做一些非常基本的密钥验证,只需根据存储在数据库中的密钥检查提供的密钥属性。

我有一个中间件类,我正在使用它添加到 slim 对象中

$app->add(new auth());

其中 auth.php 是我的班级。

我让它工作了,我想将代码拆分为函数,但是我似乎无法从 __invoke 中调用函数而不会出现 Slim 应用程序错误。

现在我有

public function __invoke($request, $response, $next){
        try {
            $user_key = $request->getAttribute('route')->getArguments()['key'];

            ...
            //fetch key from database code
            ...

            if($user_key==$api_key){
                $response = $next($request, $response);
            }
            else{
               $response->getBody()->write("Invalid API Key");
            }
        } 
        catch (PDOException $e) {
               $response->getBody()->write("An error has occurred");
        }        
        return $response;
    }

哪个有效,但我想将获取代码移动到它自己的函数中,例如

public function fetchKey(){
            ...
            //return key
            ...
    }

并调用$api_key = fetchKey();但是这会导致 Slim 错误。

这可能真的很简单,但有人知道是什么原因造成的吗?

标签: phpapislim

解决方案


推荐阅读