Laravel的路由管理

基礎

Laravel充分利用PHP 5.3的特性,使路由變得簡單並富於表達性。這使得從構建API到完整的web應用都變得儘可能容易。路由的實現代碼在 application/routes.php 文件。

和其它框架不同,應用邏輯在Laravel中可以通過兩種方式集成。雖然在控制器(controllers)中實現業務邏輯是普遍的做法,但是在Laravel中也可以直接在路由中嵌入應用邏輯。這種方式尤其適用於只有幾個頁面的小型網站,這樣就免去了創建一大堆控制器(controllers),還要爲每個控制器創建一些不相干的方法(methods),而最後只是一部分方法(methods)通過手動設置路由的方式被暴露出來。

在下面的代碼示例中,第一個參數(parameter)是你“註冊”的路由(route),第二個參數是這個路由將要觸發的函數(function),函數中包含了應用邏輯。定義路由時不需要開頭的斜線(front-slash),唯一的例外是默認路由(default route)只包含一個斜線(front-slash)。

注意: 路由的權重在於其被註冊的先後順序。 因此,任何通配(catch-all)的路由應該在 routes.php 文件的底部註冊

註冊一個響應 "GET /" 的路由:

Route::get('/', function() { return "Hello World!"; });


註冊一個能同時響應(GET、POST、PUT、DELETE)HTTP請求方法(HTTP verbs)的路由:

Route::any('/', function() { return "Hello World!"; });


註冊響應其它HTTP請求方法(HTTP verbs)的路由:

Route::post('user', function() { 
    // 
}); 
Route::put('user/(:num)', function($id) { 
    // 
}); 
Route::delete('user/(:num)', function($id) { 
    // 
});


註冊一個能響應多個HTTP請求方法(HTTP verbs)的路徑(URI):

Router::register(array('GET', 'POST'), $uri, $callback);


通配符(Wildcards)

強制路徑(URI)中的某部分爲數字:

Route::get('user/(:num)', function($id) { 
    // 
});


允許路徑(URI)中的某部分是字母、數字串:

Route::get('post/(:any)', function($title) { 
    //
});


允許路徑(URI)中的某部分是可選的:

Route::get('page/(:any?)', function($page = 'index') { 
    // 
});


404事件(The 404 Event)

如果一個請求(request)不能匹配任何一個路由,404事件將被觸發。在 application/routes.php 文件中可以找到默認的事件處理代碼。

默認的404事件處理代碼

Event::listen('404', function() { 
    return Response::error('404'); 
});


你可以按照你自己的需求定製這部分代碼!

延伸閱讀:

過濾器(Filters)

過濾器(filters)可以在路由之前或之後觸發。如果在路由之前觸發的過濾器(filters)有返回值,那麼這個返回值將被認爲是對此次請求(request)的迴應(response),路由將停止執行。這一特性便於實現身份驗證之類的功能。在application/routes.php 文件中定義了所有過濾器(filters)。

註冊一個過濾器(filter):

Route::filter('filter', function() { 
    return Redirect::to('home'); 
});


綁定一個過濾器(filter)到路由:

Route::get('blocked', array('before' => 'filter', function() { 
    return View::make('blocked'); 
}));


給路由綁定一個之後(after)執行的過濾器(filter):

Route::get('download', array('after' => 'log', function() { 
    // 
}));


綁定多個過濾器(filters)到路由:

Route::get('create', array('before' => 'auth|csrf', function() { 
    // 
}));


給過濾器(filters)傳遞參數:

Route::get('panel', array('before' => 'role:admin', function() { 
    // 
}));

模式過濾器(Pattern Filters)

有時你可能需要針對所有包含部分路徑(URI)的請求(request)綁定一個過濾器(filter),例如,你想對以“admin”開頭的路徑(URI)綁定一個叫”auth“的過濾器(filter),以下代碼就是具體實現:w

D定義一個基於路徑模式(URI pattern)的過濾器(filter):

Route::filter('pattern: admin/*', 'auth');

你也可以在爲某個給定的路徑(URI)綁定過濾器(filters)時直接提供一個帶有名稱(name)和回調函數(callback)的數組,這樣,過濾器(filters)也就完成了註冊。

Defining a filter and URI pattern based filter in one:

Route::filter('pattern: admin/*', array('name' => 'auth', function() { 
    // 
}));

全局過濾器(Global Filters)

Laravel默認有兩個過濾器(filters),他們分別在每次請求(request)之前(before)和之後(after)執行。你可以在application/routes.php 文件中找到這兩個過濾器(filters)。這兩個過濾器可以方便你啓動通用擴展包(bundles)或者添加全局資源(assets)。

注意: 之後(after) 過濾器接收到的參數是對應當前請求(request)的 迴應(Response) 對象。

路由組(Route Groups)

路由組方便你爲一組路由綁定一些屬性(attributes),從而保持代碼的整潔。

Route::group(array('before' => 'auth'), function() { 
    Route::get('panel', function() { 
        
    }); 
    Route::get('dashboard', function() { 
        
    }); 
});

命名路由(Named Routes)

總是會有修改路由的時候,這就會讓寫死的路徑(URI)產生錯誤。給路由賦予一個名稱(name)可以方便通過這個名稱(name)動態生成路徑(URI),即便以後路由變化了,路徑(URI)仍然和你新的路由保持一致。

定義一個命名路由:

Route::get('/', array('as' => 'home', function() { return "Hello World"; }));

通過命名路由生成URL:

$url = URL::to_route('home');

重定向到命名路由:

return Redirect::to_route('home');

對於一個命名路由,可以方便反查當前請求(request)是否是由這個命名路由在處理。

反查處理當前請求(request)的路由是否具有給定的名稱(name):

if (Request::route()->is('home')) { 
    // 名稱爲”home“的路由正在處理當前請求(request)!
}

HTTPS路由(HTTPS Routes)

定義路由時,可以通過使用”https“參數指定所生成的URL(或重定向時)採用HTTPS協議。

定義一個HTTPS路由:

Route::get('login', array('https' => true, function() { 
        return View::make('login'); 
    })
);

使用”secure“函數完成同樣的事情:

Route::secure('GET', 'login', function() { 
    return View::make('login'); 
});

擴展包路由(Bundle Routes)

擴展包(bundle)是Laravel的模塊化擴展系統。可以通過配置擴展包,方便的處理請求(request)。這裏是擴展包的詳細介紹,此處略過。 通過此段介紹,你會認識到擴展包不僅可以通過路由(route)暴露功能,還可以在擴展包中註冊路由。

打開 application/bundles.php 文件,添加以下代碼:

註冊擴展包,處理相應的路由:

return array( 'admin' => array('handles' => 'admin') );

注意到代碼中的 handles 參數了嗎? 這告訴Laravel加載Admin擴展包並處理任何以“admin”開頭的路徑(URI)。

現在準備爲你的擴展包註冊幾個路由吧,在你的擴展包的根目錄創建 routes.php 文件,並添加以下代碼:

給擴展包添加一個根路由(root route):

Route::get('(:bundle)', function() { 
    return 'Welcome to the Admin bundle!'; 
});

我們來解析一下這段代碼。 注意到 (:bundle) 了嗎? 它將被替換爲前面註冊擴展包時的 handles 參數的值。這使你的代碼保持D.R.Y. - 不重複,還能讓使用你的代碼的開發者隨意修改擴展包的根(root)URI而不破快擴展包中定義的路由!

當然,你可以在擴展包中的所有路由上使用 (:bundle) 佔位符,而不僅僅是跟路由(root route)。

註冊擴展包路由:

Route::get('(:bundle)/panel', function() { 
    return "I handle requests to admin/panel!"; 
});

控制器路由(Controller Routing)

Controllers provide another way to manage your application logic. If you're unfamiliar with controllers you may want toread about controllers and return to this section.

It is important to be aware that all routes in Laravel must be explicitly defined, including routes to controllers. This means that controller methods that have not been exposed through route registration cannot be accessed. It's possible to automatically expose all methods within a controller using controller route registration. Controller route registrations are typically defined in application/routes.php.

Most likely, you just want to register all of the controllers in your application's "controllers" directory. You can do it in one simple statement. Here's how:

Register all controllers for the application:

Route::controller(Controller::detect());

The Controller::detect method simply returns an array of all of the controllers defined for the application.

If you wish to automatically detect the controllers in a bundle, just pass the bundle name to the method. If no bundle is specified, the application folder's controller directory will be searched.

Register all controllers for the "admin" bundle:

Route::controller(Controller::detect('admin'));

Registering the "home" controller with the Router:

Route::controller('home');

Registering several controllers with the router:

Route::controller(array('dashboard.panel', 'admin'));

Once a controller is registered, you may access its methods using a simple URI convention:

http://localhost/controller/method/arguments

This convention is similar to that employed by CodeIgniter and other popular frameworks, where the first segment is the controller name, the second is the method, and the remaining segments are passed to the method as arguments. If no method segment is present, the "index" method will be used.

This routing convention may not be desirable for every situation, so you may also explicitly route URIs to controller actions using a simple, intuitive syntax.

Registering a route that points to a controller action:

Route::get('welcome', 'home@index');

Registering a filtered route that points to a controller action:

Route::get('welcome', array('after' => 'log', 'uses' => 'home@index'));

Registering a named route that points to a controller action:

Route::get('welcome', array('as' => 'home.welcome', 'uses' => 'home@index'));

命令行路由測試(CLI Route Testing)

可以用Laravel自帶的“Artisan”命令行工具測試你的路由,只需指定請求方法(request method)和需要測試的URI,所有返回的響應(response)都會通過var_dump函數輸出到命令行上。

通過Artisan命令行工具調用路由:

php artisan route:call get api/user/1
發佈了41 篇原創文章 · 獲贊 11 · 訪問量 51萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章