[英]Laravel - using controllers instead of routes for actions
我今天從字面上下載了Laravel,並且很喜歡事物的外觀,但是我在2件事情上苦苦掙扎。
1)我喜歡控制器的url分析而不是使用路由的action方法,它似乎可以使所有內容更加整潔,但是可以說我想轉到
/account/account-year/
如何為此編寫動作函數? 即
function action_account-year()...
顯然是無效的語法。
2)如果我有
function action_account_year( $year, $month ) { ...
並參觀了
/account/account_year/
將顯示有關缺少參數的錯誤,如何使此用戶友好/加載差異頁面/顯示錯誤?
您將必須手動路由連字符的版本,例如
Route::get('account/account-year', 'account@account_year');
關於參數,取決於您的路由方式。 您必須接受路徑中的參數。 如果您使用完整的控制器路由(例如Route::controller('account')
),則該方法將自動傳遞參數。
如果您是手動路由,則必須捕獲參數,
Route::get('account/account-year/(:num)/(:num)', 'account@account_year');
因此,訪問/account/account-year/1/2
可以->account_year(1, 2)
希望這可以幫助。
您也可以考慮以下可能性
class AccountController extends BaseController {
public function getIndex()
{
//
}
public function getAccountYear()
{
//
}
}
現在,只需按照以下方式在您的路由文件中定義一個RESTful控制器
Route::controller('account', 'AccountController');
訪問'account/account-year'
將自動轉到操作getAccountYear
我以為我會將此添加為答案,以防其他人在尋找它:
1)
public function action_account_year($name = false, $place = false ) {
if( ... ) {
return View::make('page.error' );
}
}
2)
還不是一個可靠的解決方案:
laravel / routing / controller.php,方法“響應”
public function response($method, $parameters = array())
{
// The developer may mark the controller as being "RESTful" which
// indicates that the controller actions are prefixed with the
// HTTP verb they respond to rather than the word "action".
$method = preg_replace( "#\-+#", "_", $method );
if ($this->restful)
{
$action = strtolower(Request::method()).'_'.$method;
}
else
{
$action = "action_{$method}";
}
$response = call_user_func_array(array($this, $action), $parameters);
// If the controller has specified a layout view the response
// returned by the controller method will be bound to that
// view and the layout will be considered the response.
if (is_null($response) and ! is_null($this->layout))
{
$response = $this->layout;
}
return $response;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.