Laravel(3)你的第一个应用2

写你的第一个routes(路由)

在我们的app/routes.php添加两个路由

1 Route::get('/', function()
2 {
3     return "All cats";
4 });
5 
6 Route::get('cats/{id}',function($id){
7     return "Cat #$id";
8 });

 

get方法的第一个参数是url模式,当模式被匹配到,就会执行一个带参数的(在匹配到的模式中提取)闭包函数(get的第二个参数)。

 

限制路由参数

在我们的第二个路由中,{id}匹配任何的字符和数字。我们要限制它只能匹配数字,我们可以链一个where方法在我们的路由中

1 Route::get('cats/{id}',function($id){
2     return "Cat #$id";
3 })->where('id','[0-9]+');

where方法带两个参数,第一个是参数的名字,第二个是一个正则表达式

访问看看

设置错误页面,我们可以通过catch一个“NOT FOUND”异常来显示我们自定义的错误页面。在app/start/global.php定义missing方法:

1 App::missing(function($exception){
2     return Response::make("Page Not Found!by jy pong",404);
3 });

我们这里不仅仅返回一个字符串,而是一个Response对象带一个字符串信息作为第一个参数,HTTP状态码作为第二个参数。

 

重定向

我们可以通过Redirect对象来重定向。

1 Route::get('/', function()
2 {
3     return Redirect::to('cats');
4 });
5 Route::get('cats',function(){
6     return "All cats!!";
7 });

 

返回一个视图

我们最经常返回的对象是View对象。Views从路由(route)当中(或者控制器controller)得到数据,然后注入到模板中。在app/views中建立一个about.php

<h2>About this site</h2>
There are over <?php echo $number_of_cats; ?> cats on this site!

通过View::make方法带一个变量$number_of_cats 返回一个view视图

1 Route::get('about', function(){
2     return View::make('about')->with('number_of_cats',400);
3 });

 

posted @ 2014-10-28 22:33  pwn_pjy  阅读(220)  评论(0)    收藏  举报