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这本书上有。

laravel route路由,视图和response和filter的更多相关文章

  1. [PHP] - Laravel - Route路由

    前言 这里使用的是Laravel 5 PHP Laravel的路由比较强悍,但也正因如此,不统一而容易凌乱.比如在路由中可以直接写方法操作(破坏封装啊) 以下是个人学习的例子,不供参考 路由中的直接方 ...

  2. laravel route路由

    基本路由 您的应用程序的绝大多数路由将在 app/routes.php 文件中定义.Laravel 中最简单的路由由一个 URI 和一个闭包调用组成. 基本 GET 路由 代码如下: Route::g ...

  3. Laravel教程 二:路由,视图,控制器工作流程

    Laravel教程 二:路由,视图,控制器工作流程 此文章为原创文章,未经同意,禁止转载. View Controller 上一篇教程我们走了那么长的路,终于把Laravel安装好了,这一篇教程我们就 ...

  4. [转]laravel 4之视图及Responses

    http://dingjiannan.com/2013/laravel-responses/   laravel 4之视图及Responses 16 Aug 2013 Laravel的Response ...

  5. laravel基础课程---8、laravel响应和视图(响应是什么)

    laravel基础课程---8.laravel响应和视图(响应是什么) 一.总结 一句话总结: 就是向请求返回的响应数据(一般为html(视图),当然也可以是变量值):所有的路由及控制器必须返回某个类 ...

  6. laravel之路由

    laravel之路由设置 代码如下: 访问就是: 代码附上: <?php /*|--------------------------------------------------------- ...

  7. MVC3/4/5/6 布局页及Razor语法及Route路由配置

    一.目录结构 二.Razor语法 代码块:@{},如:@{Html.Raw(“”);} @if(){} @switch(){} @for(){} @foreach(){} @while(){} @do ...

  8. laravel的路由分组,中间件,命名空间,子域名,路由前缀

    laravel的路由分组,就是把一些具有相同特征的路由进行分组,比如一些路由需要进行验证,一些路由有共同的前缀,一些路由有相同的控制器命名空间等. 这样把路由组合在一起,方便管理,维护性更好. Rou ...

  9. Laravel中路由怎么写(二)

    1.路由命名——给路由起个名字 1.1 基本使用 我们使用as关键字来为路由命名: Route::get('/hello/Laravel',['as'=>'academy',function() ...

随机推荐

  1. c#调用c++ dll(二)

    当对c++几种调用方式有了解以后我们可以试着写个c++动态连接库了,我们现在来写个简单的c++求和函数并把它封装成dll,供以后的c#调用 我们写dll的时候,个人认为,要写就要把dll写好,写标准, ...

  2. 学习C++ Primer 的个人理解(六)

    第四章和第五章没什么特别的.基本上就是书本上的字面意思,也没什么需要注意的细节.直接记录第六章. 本章介绍了函数,其实也没什么特别的.但有几个重点 1.形参的类型决定了形参和实参的交互方式.形参是引用 ...

  3. 九度OJ 1385 重建二叉树

    题目地址:http://ac.jobdu.com/problem.php?pid=1385 题目描述: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都 ...

  4. 程序员面试题精选100题(33)-在O(1)时间删除链表结点[数据结构]

    作者:何海涛 出处:http://zhedahht.blog.163.com/ 题目:给定链表的头指针和一个结点指针,在O(1)时间删除该结点.链表结点的定义如下: struct ListNode { ...

  5. 4.MySQL连接并选择数据库(SQL & C)

    在连接了MySQL数据库之后,可以通过SQL命令或者C.PHP.JAVA等程序来指定需要操作的数据库.这里主要介绍SQL命令和相应的C程序. 首先创建用户rick(赋予所有权限) mysql> ...

  6. 数独的C++解法

    grid.h #ifndef _GRID_H_ #define _GRID_H_ #include <set> #include <cstddef> class Grid { ...

  7. ajax提交数据Demo

    $.ajax({ url: "url", type: "post", data: JSON.stringify(yourData), contentType: ...

  8. sql server 2008数据复制方法

    发布订阅份为两个步骤:1.发布.2.订阅.首先在数据源数据库服务器上对需要同步的数据进行发布,然后在目标数据库服务器上对上述发布进行订阅.发布可以发布一张表的部分数据,也可以对整张表进行发布.下面分别 ...

  9. 转 修改oracle用户密码永不过期

      1.查看用户的proifle是哪个,一般是default: sql>SELECT username,PROFILE FROM dba_users; 2.查看指定概要文件(如default)的 ...

  10. Class.forName、Class.class(属性)、getClass()的区别

    1.出现的时期不同:Class.forName()在运行时加载:Class.class和getClass()是在编译器加载2.Class.class只是在编译时用来存放类的相关信息,并没有实例化对象: ...