Laravel 4 - Route::resource 与 Route::controller.使用哪个?

2022-01-02 00:00:00 routing php laravel laravel-4

我知道资源控制器可以有以下方法

I understand that a Resource controller can have the following methods

index
show
create
edit
store
update
destroy

现在假设除了资源操作之外,我还需要执行以下操作:

Now suppose I have the following actions which need to be performed in addition to the resource actions:

  • 用户尝试登录.
  • 管理员希望通过电子邮件/名字查找用户
  • 用户请求发帖

资源控制器对上述功能无用吗?如果对 API 进行编程,我显然想要索引、显示、编辑、创建、销毁……以及登录、查找、搜索等……

Are resource controllers useless for the above functionality? If programming an API, I obviously want the index, show, edit,create,destroy... but also the login, find, search etc...

是否可以路由到两种类型的控制器?例如

Is it possible to route to both types of controller? e.g.

Route::group(['prefix' => 'api'], function() {
    Route::group(['prefix' => 'v1'], function() {
        // Resource Controller
        Route::resource('posts', 'ApiV1PostsResourceController');

        // Restful Controller
        Route::controller('posts', 'ApiV1PostsController');
    });
});

或者我应该忘记资源控制器并使用宁静的控制器来代替?

Or should I just forget about the resource controller and use a restful controller instead?

推荐答案

只需使用资源控制器,将这些其他方法添加到同一个控制器,并直接向这些方法添加路由:

Just use a resource controller, add those other methods to that same controller, and add routes to those methods directly:

Route::group(['prefix' => 'api'], function()
{
    Route::group(['prefix' => 'v1', 'namespace' => 'ApiV1'], function()
    {
        // Add as many routes as you need...
        Route::post('login', 'PostsResourceController@login');
        Route::get('find',   'PostsResourceController@find');
        Route::get('search', 'PostsResourceController@search');

        Route::resource('posts', 'PostsResourceController');
    });
});

P.S. 我通常回避使用 Route::controller().太含糊了.

P.S. I generally shy away from using Route::controller(). It's too ambiguous.

相关文章