在slim3 php框架中,response-> getBody()为空

时间:2016-02-11 09:48:12

标签: php middleware slim-3

我在使用这个slim3 php代码时遇到了麻烦。在函数createErrorReponse函数上,$ response-> getBody()为null或为空。 Php抱怨以下错误。正如您所看到的,getBody()大小为空,因此write不会对其起作用。但是,同一行在其他功能中起作用。 HTTP / 1.1 200 OK内容类型:text / html; charset = UTF-8 0 致命错误:在第16行的/home/ubuntu/webapp/middleware/authmodule.php中的非对象上调用成员函数withHeader()

<?php
class AuthenticationMiddleware
{
        public function isAuthenticated($userid, $authorization)
        {
                //do data validation here
                return false;
        }

        public function createErrorResponse($code, $msg, $response)
        {
                echo $response;
                echo $response->getBody()->getSize();
                $response = $response->getBody()->write(json_encode('holla'));
                $response = $response->withHeader('Content-Type', 'application/json; charset=utf-8');
                return $response;
        }

        public function __invoke($request, $response, $next)
        {
                $userid = $request->getHeaderLine('userid');
                $authorization = $request->getHeaderLine('Authorization');
                if($this->isAuthenticated($userid, $authorization))
                {
                        $response = $next($request, $response);
                }
                else
                {
                        $msg = 'You are unauthenticated. Please login again';
                        $code = 400;
                        $response = $this->createErrorResponse($code, $msg, $response);
                }
                return $response;
        }
}

1 个答案:

答案 0 :(得分:3)

感谢有关错误报告和修复的提醒。 我觉得有必要回答这个问题,以防万一你没有放弃PHP和Slim框架。 希望它对其他人有帮助。

我的方法是:

<?php

use Slim\Http\Request;
use Slim\Http\Response;

class AuthenticationMiddleware {

    public function isAuthenticated($userid, $authorization) {
        //do data validation here
        return false;
    }

    public function createErrorResponse($code, $msg, Response $response) {
        return $response->withStatus($code)
            ->withHeader('Content-Type', 'application/json;charset=utf-8')
            ->withJson($msg);
    }

    public function __invoke(Request $request, Response $response, $next) {
        $userid = $request->getHeaderLine('userid');
        $authorization = $request->getHeaderLine('Authorization');
        if(!$this->isAuthenticated($userid, $authorization)) {
            $msg = 'You are unauthenticated. Please login again';
            $code = 400;
            $this->createErrorResponse($code, $msg, $response);
        } else {
            $response = $next($request, $response);
        }
        return $response;
    }
}

我来说吧。我会在这段代码中抽象一些东西,所以我最终不会重复自己。我看到你重复:

public function createErrorResponse($code, $msg, Response $response) {
    return $response->withStatus($code)
        ->withHeader('Content-Type', 'application/json;charset=utf-8')
        ->withJson($msg);
}

在所有中间件中,也许在您的路由中。 希望这能让某人走上正轨。