控制器

通常Laravel控制器文件放在app/controllers/目录下。该目录已被Composer自动加载。控制器名称可以任意取,但一般以Controller为后缀,然后继承BaseControllerController类,BaseController通常包括一些公用的控制器逻辑。

  1. <?php
  2. // app/controllers/ArticleController.php
  3. classArticleControllerextendsBaseController
  4. {
  5. publicfunction showIndex()
  6. {
  7. returnView::make('index');
  8. }
  9. publicfunction showSingle($articleId)
  10. {
  11. returnView::make('single');
  12. }
  13. }

在路由中调用控制器

  1. // app/routes.php
  2. Route::get('index','ArticleController@showIndex');

控制器中使用命名空间

  1. // app/routes.php
  2. Route::get('index','Namespace/ArticleController@showIndex');

在控制器路由中指定名称

  1. Route::get('foo', array('uses'=>'FooController@method',
  2. 'as'=>'name'));

使用URL::action方法获取一个控制器操作的链接

  1. $url = URL::action('FooController@method');

使用currentRouteAction方法获取当前控制器操作的名称

  1. $action =Route::currentRouteAction();

控制器过滤器

  1. Route::get('profile', array('before'=>'auth',
  2. 'uses'=>'UserController@showProfile'));

在控制器内部定义过滤器

  1. classUserControllerextendsBaseController{
  2. publicfunction __construct()
  3. {
  4. $this->beforeFilter('auth');
  5. $this->beforeFilter('csrf', array('on'=>'post'));
  6. $this->afterFilter('log', array('only'=>
  7. array('fooAction','barAction')));
  8. }
  9. }

RESTful 控制器

使用简单的REST命名规范,轻松定义单个路由去处理控制器的每个操作。避免为每个控制器动作绑定路由。定义一个 RESTful 控制器

  1. Route::controller('article','ArticleController');

ArticleController类中的方法以HTTP动作为前缀,如

  1. <?php
  2. // app/controllers/Article.php
  3. classArticleextendsBaseController
  4. {
  5. publicfunction getCreate()
  6. {
  7. returnView::make('create');
  8. }
  9. publicfunction postCreate()
  10. {
  11. // Handle the creation form.
  12. }
  13. }

如果你的控制器操作名称包含多个单词,你可以使用 "破折号" 语法来获得URI。例如,下面UserController控制器中的这个操作会用来应答users/admin-profileURI:

  1. publicfunction getAdminProfile(){}

结束