2014-02-06 62 views
0

如何將應用程序從我的自定義類重定向到特定的url?Laravel - 自定義類的重定向

比方說,我有我的Laravel應用定製類API:

class API { 

    private function generic_request($uri) 
    { 
     $response = $this->getResponse($uri); 
     if($response == 'bad_token') 
     { 
      //redirect to login screen with message 
     } 
    } 

在我的控制器功能:

public function add_employee() { 
    $data['employee_positions'] = API::generic_request('/employees/position_list'); 
    $this->layout->content = View::make('employees.add_employee')->with($data); 
} 

我試過Events,但你不能從Event監聽器重定向。現在我正在使用Exceptions,但我覺得這是錯誤的方法。例如:

App::abort(401); 

,然後在global.php

App::error(function(Exception $exception, $code) 
{ 
    /*CORE API Exceptions*/ 

    if($code == 401) 
    { 
     Session::put('message','System Action: Expired Token'); 
     return Redirect::to('login'); 
    } 
} 

回答

0

你只需要創建一個響應並返回它所有的方式回到Laravel:

<?php 

class API { 

    public function doWhatever($uri) 
    { 
     return $this->generic_request($uri); 
    } 

    private function generic_request($uri) 
    { 
     $response = $this->getResponse($uri); 

     if($response == 'bad_token') 
     { 
      return Redirect::to('login')->with('message', 'your message'); 
     } 

    } 

} 

Route::get('test', function() 
{ 
    return with(new API)->doWhatever('yourURI'); 
}); 
+0

如果讓API調用在我的'控制器'功能是這樣的:'$ data ['employee_positions'] = API :: generic_request('/ employees/position_list'); $ this-> layout-> content = View :: make('employees.add_employee') - > with($ data);'?用你的例子,我只會看到JSON響應。我想知道是否有一個通用的方法,而不是用'if'語句包裝每個請求 – castt

+0

在私有和非靜態方法上? –

+0

API不應該重定向,只返回請求的響應!消費者應根據收到的迴應做出決定。我只是返回狀態代碼在響應標題與一些JSON正文解釋情況。 – Andreyco