2016-02-11 28 views
0

我遇到了這個slim3 php代碼的問題。在函數createErrorReponse函數中,$ response-> getBody()爲空或空。 Php抱怨下面的錯誤。正如你所看到的那樣,getBody()的大小是空的,因此編寫不起作用。儘管如此,其他功能也適用同一條線。 HTTP/1.1 200 OK Content-Type:text/html;字符集= UTF-8 0 致命錯誤:調用一個成員函數withHeader()一個非對象在/home/ubuntu/webapp/middleware/authmodule.php第16個響應 - > getBody()在slim3 php框架中爲空

<?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; 
     } 
} 
+0

大家都知道。我似乎已經暴露了框架中的一個錯誤,他們正在討論它。當你看到這一點時,它將被修復。由於這個錯誤將被修復的時間框架,我將會完全放棄php和這個糟糕的框架。 –

回答

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); 
} 

在所有的中間件,也許在你的路線。 希望這會讓某人走上正軌。