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 文件的底部注冊
3 // app/routes.php
4
5 Route::get();
6 Route::post();
7 Route::put();
8 Route::delete();
9 Route::any();
注冊一個能同時響應(GET、POST、PUT、DELETE)HTTP請求方法(HTTP verbs)的路由
ROUTE::any('/', function() { return "Hello World!"; });
(
下面是老版本的,4.0后不支持了。
通配符(Wildcards)
強制路徑(URI)中的某部分為數字:
Route::get('user/(:num)', function($id) { // });
允許路徑(URI)中的某部分是字母、數字串:
Route::get('post/(:any)', function($title) { // });
允許路徑(URI)中的某部分是可選的:
Route::get('page/(:any?)', function($page = 'index') { // });
路由參數:
Route::get('/books/{genre}', function($genre)
Route::get('user/{id}', function($id) { return 'User '.$id; });
可選路由參數
Route::get('user/{name?}', function($name = null) { return $name; });
帶有默認值的可選路由參數
Route::get('user/{name?}', function($name = 'John') { return $name; });
用正則表達式限定的路由參數
Route::get('user/{name}', function($name) { // }) ->where('name', '[A-Za-z]+'); 輸入:http://localhost/laravelFirst/public/post/you1 由於1不是,會匹配不到,去掉1就可以匹配到了。 Route::get('user/{id}', function($id) { // }) ->where('id', '[0-9]+');
傳遞參數限定的數組
當然,必要的時候你還可以傳遞一個包含參數限定的數組作為參數:
Route::get('user/{id}/{name}', function($id, $name) { // }) ->where(array('id' => '[0-9]+', 'name' => '[a-z]+'))
定義全局模式
如果希望在全局范圍用指定正則表達式限定路由參數,可以使用 pattern
方法:
Route::pattern('id', '[0-9]+'); Route::get('user/{id}', function($id) { // Only called if {id} is numeric. });
訪問路由參數
如果想在路由范圍外訪問路由參數,可以使用 Route::input
方法:
Route::filter('foo', function() { if (Route::input('id') == 1) { // } });
Route::get('post/{postTitle}',function($postTitle){
$data['title']=$postTitle;
return View::make('simple',$data);
});
$data數組傳給視圖會自動extract。
response;
創建自定義Response
Response
類繼承自Symfony\Component\HttpFoundation\Response
類,提供了多種方法用於構建HTTP Response。
Route::get("custom/response",function(){
$response=Response::make("<h1>hello world</h1>");
$response->headers->set('Content-type','text/plain');
return $response;
});
如果需要訪問 Response
類的方法,但又要返回一個視圖作為響應的內容,通過使用 Response::view
方法可以很容易實現:
return Response::view('hello')->header('Content-Type', $type);
在Response中添加Cookie
$cookie = Cookie::make('name', 'value'); return Response::make($content)->withCookie($cookie);
json response:
Route::get('markdown/response', function()
6 {
7 $data = array('iron', 'man', 'rocks');
8 return Response::json($data);
9 });
By handing an array to the Response::json() method it has been converted to a JSON string and
set as the body of our new Response object. Appropriate headers have been set to explain that the
provided data is infact a JSON string.
上面的會被解析為數組。
$data = array('a'=>'iron','b'=> 'man', 'rocks');
被解析成:
{"a":"iron","b":"man","0":"rocks"}
download response
Serving files directly requires certain headers to be set. Fortunately, Laravel takes care of this for
you using the Response::download() shortcut. Let’s see this in action.
Route::get('file/download', function()
6 {
7 $file = 'path_to_my_file.pdf';
8 return Response::download($file);
9 });
Now if we navigate to the /file/download URI the browser will intiate a download instead of
displaying a response. The Response::download() method received a path to a file which will be
served when the response is returned.
You can also provide optional second and third parameters to configure a custom HTTP status code
and an array of headers. For example:
Route::get('file/download', function()
6 {
7 $file = 'path_to_my_file.pdf';
8 return Response::download($file, 418, array('iron', 'man'));
9 });
Here we will serve our file with the HTTP status code of 418 (I’m a Teapot) and a header value of
iron=man.
Well this chapter was a lot longer than I originally anticipated, but I’m sure you will see that
returning appropriate response objects can be a lot more valuable than returning simple strings.
In the next chapter we will take a look at route filters, which will allow us to protect our routes or
perform actions before/after they are executed.
Filter過濾器
Filters are certain sets of rules or actions that can be applied to a route. They can be performed
before or after a route’s logic is executed, however, you will find before filters to be more useful.
Using before filters we can alter the flow of the application
路由過濾器提供了非常方便的方法來限制對應用程序中某些功能訪問,例如對於需要驗證才能訪問的功能就非常有用。Laravel框架自身已經提供了一些過濾器,包括 auth
過濾器、auth.basic
過濾器、guest
過濾器以及csrf
過濾器。這些過濾器都定義在app/filter.php
文件中。
使用1:
Route::controller('users', 'UsersController'); Route::get('admin-only',array('before'=>'checkAdmin','after'=>'logAdmin',function(){ return "hello there, amdin!"; })); Route::get("set-admin",function(){ Session::put("user_type",'admin'); return Redirect::to("admin-only"); });
filter.php
Route::filter("checkAdmin",function(){ if('admin' !== Session::get("user_type")) return " you are not an admin .go away"; }); Route::filter('logAdmin',function(){ Log::info("Admin logged in on ".date("Y-m-d H:i:s")); });
Create a route where we can set the admin session:
Route::get('set-admin', function()
{
Session::put('user_type', 'admin');
return Redirect::to('admin-only');
});
4. Test the route by going to http://your-server/admin-only (where yourserver
is the URL for your server) and notice the results. (顯示:
you are not an admin .go away )
Then, go to set-admin
and see those results.
5. Go to the app/storage/logs directory and view the logfiles.
After the route is accessed, we create a log of the visit along with the date the route
was accessed.
使用route group
When creating a web app, we may find a few routes that need the same URL prefix or filter.
Using Laravel's route groups, we can easily apply these to multiple routes.
To complete this recipe, follow these steps:
1. In our app/filters.php file, create a filter to check for a user:
Route::filter('checkUser', function()
{
if ('user' !== Session::get('profile'))
{
return 'You are not Logged In. Go Away!';
}
});
2. In the app/routes.php file, create a route that can set our profile session:
Route::get('set-profile', function()
{
Session::set('profile', 'user');
return Redirect::to('profile/user');
});\
3. In routes.php, create our route group:
Route::group(array('before' => 'checkUser', 'prefix' =>
'profile'), function()
{
Route::get('user', function()
{
return 'I am logged in! This is my user
profile.';
});
Route::get('friends', function()
{
return 'This would be a list of my friends';
});
});
4. In our browser, we then go to http://path/to/our/server/profile/user,
where we will get an error. If we then go to http://path/to/our/server/setprofile,
it will redirect us and show the correct page.
Now, any route we create inside this group must pass the filter and will be accessible
using the profile prefix.
controller routing 控制器路由
Route::get('index', 'ArticleController@showIndex');
Here’s a neat thing to know. You can namespace your controller and Laravel won’t bat an eyelid.
Just make sure to include the namespace within your route declaration and everything will be just
dandy! Let’s see this in action.
1 <?php
2
3 // app/controllers/Article.php
4
5 namespace Blog\Controller;
6
7 class Article
8 {
9 public function showIndex()
10 {
11 return View::make('index');
12 }
13 }
So here we have a similar Controller to that used in the other example. This time however, it is
contained within the Blog\Controller namespace. Since it’s located within the Controller section
of the namespace, I have omitted the Controller suffix from the class name. This is my own personal
preference, I leave it up to you to decide whether you keep it or not.
Let’s see how this namespaced controller can be routed to. You’ve probably already guessed it!
Route::post('index', 'Blog\Controller\Article@showIndex');
Restful controller;
code bright這本書上有。