您的位置:首页 > 编程语言 > PHP开发

Laravel的路由管理

2014-04-23 16:51 281 查看


基础

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');
});


你可以按照你自己的需求定制这部分代码!

延伸阅读:

事件(Events)


过滤器(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: