Slim v2未定义变量

时间:2017-04-21 08:27:07

标签: php slim

我在slim framework v2中编写了一个用于身份验证的中间件。

以下是教程:http://docs.slimframework.com/routing/middleware/#what-arguments-are-passed-into-each-route-middleware-callable

$app->get('/cases/shared/group/:group_id', 'authenticate', $authenticate2($app->router()->getCurrentRoute(), 'member', 'group'), function ($group_id) use ($app) {
    $limit = $app->request()->params('limit');
    $offset = $app->request()->params('offset');
    $search = $app->request()->params('search');
    $order = $app->request()->params('order');

    $objCases = new Cases();
    $result = $objCases->getSharedWithGroupCases($group_id, $limit, $offset, $search, $order);

    if ($result === null) {
        $response["error"] = true;
        $response["message"] = _("İlgili grup ile paylaşılan olgu bulunmamaktadır.");
    } else {
        $response["error"] = false;
        $response["data"] = $result;
        $response["total_data"] = $objCases->getNumOfSharedWithGroupCasesData($group_id, $search, $order);
    }

    echoResponse(200, $response);
});

认证。 :

function authenticate(\Slim\Route $route) {
    $headers = getallheaders();
    $response = array();
    $app = \Slim\Slim::getInstance();

    if (isset($headers['Authorization'])) {
        if(strpos($headers['Authorization'], '.') !== false) {
            $authorization = explode('.', $headers['Authorization']);
            $api_key = $authorization[0];
            $user_id = $authorization[1];

            $objUsers = new Users();
            if ($objUsers->isValidUser($user_id, $api_key) <= 0) {
                $response["error"] = true;
                $response["message"] = "Access Denied. Invalid Api key";
                echoResponse(401, $response);
                $app->stop();
            }
        } else {
            $response["error"] = true;
            $response["message"] = "Access Denied. Invalid Api key";
            echoResponse(401, $response);
            $app->stop();
        }
    } else {
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoResponse(400, $response);
        $app->stop();
    }
}

$authenticate2 = function (\Slim\Route $route, $role, $where) {
    $response["group_id"] = $route->getParam('group_id');
    $response["role"] = $role;
    $response["where"] = $where;

    echoResponse(200, $response);
};

第一种认证方法效果很好。但第二种身份验证方法会返回两个错误:

  

未定义的变量:authenticate2

     

函数名称必须是字符串

错误行: $app->get('/cases/shared/group/:group_id', 'authenticate', $authenticate2($app->router()->getCurrentRoute(), 'member', 'group'), function ($group_id) use ($app) {

如何将路由和参数一起发送到中间件?

1 个答案:

答案 0 :(得分:0)

确保$authenticate2 = function();代码在$app->get('/cases/shared/group/:group_id', …调用之前执行。