2017-01-30 59 views
1

有道我有一個控制器之外的常規PHP類,所以它不會從容器的自動注射受益。我需要訪問該類的響應對象,我想我應該從容器中獲取它。 訪問它的正確方法是什麼?只是將它作爲參數傳遞給外部類可以使用它?有沒有更好的辦法 ?從類訪問容器不纖薄控制器

+0

爲什麼你需要響應對象 – jmattheis

+0

做一個重定向 –

回答

0

如果您需要發送子請求,Slim provides such functionality。不過,使用它carefully,因爲在某些情況下其結果並不明顯。

<?php 
class MySortOfOutsideClass 
{ 
    /** 
    * If you need to send a subrequest, you have to access application instance, 
    * so let's inject it here. 
    */ 
    public function __construct(\Slim\App $app) 
    { 
     $this->$app = $app; 
    } 

    /** 
    * Method that makes a subrequest, and returns the result of it. 
    */ 
    public function myMethod() 
    { 
     if ($subRequestIsRequired) { 
      return $this->app->subRequest('GET', '/hello'); 
     } 
    } 
} 
0

您需要使用中間件,因爲響應對象是不可變的,因此「更改」它不會更新將被slim使用的響應。

$app->add(function($request, $response, $next) { 
    if($shouldRedirect === true) { 
     return $response->withRedirect('myurl'); // do not execute next middleware/route and redirect 
    } 
    return $next($request, $response); // execute next middleware/ the route 
}); 

有關中間件have a look at this的更多信息。

+0

謝謝,將調查這一點。請快速提問:是否可以從「外部」文件(不在控制器內部)觸發細長路由進程(會觸發中間件)? –

+0

@RobertBrax我不明白,你觸發與'$ APP-> run()的執行;' – jmattheis

+0

是,應用程序運行良好,但我想觸發從一個類文件,是不是在控制器中的請求過程。想象一下,我有一個文件「authRequired.php」文件,它不在控制器中,但仍然必須能夠從內部進行重定向。 –