Restful laravel应用程序中用于控制器和方法的最佳实践是什么 [英] What is best practice in a Restful laravel app for Controllers and methods

查看:85
本文介绍了Restful laravel应用程序中用于控制器和方法的最佳实践是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个宁静的laravel应用程序,我需要知道什么是在Laravel中实现路由,控制器和方法以同时支持restful requestsHTTP web requests的最佳实践,我们可以轻松地创建资源控制器并然后将以下行添加到Laravel中的路由文件中:

I am developing a restful laravel application and I need to know what is the best practice to implement the routes, controllers and methods in the Laravel to both support the restful requests and HTTP web requests we can easily create a resource controller and then add the following line to the routes file in Laravel:

Route::resource('Photo', 'PhotoController');

,然后在PhotoController中,我们只需要添加以下代码行即可从所有照片返回json响应:

and then in the PhotoController we just need to add the following lines of codes which returns a json response from all the photos:

class PhotoController {

  public function index()
  {
     $photos = Photo::all();        

     return response()->
                        json(['result' => $photos]);       
     }
}

我们还需要一个Controllermethod来响应Web HTTP请求并返回一个网页,而不是一个json响应,该响应将所有照片显示给网络用户

we also need a Controller and a method which responds to web HTTP request and returns a web page instead of a json response which displays all the photos to the web users

问题: 将该方法和Controller放在哪里最好的地方是一个好习惯,将它放在同一个Controller中并返回视图?就像下面的例子

Question: where is the best place to put this method and Controller is it a good practice to put it inside the same Controller and returns a view? like following example

class PhotoController{

 public function getAll(){
            $photos = Photo::getAll();

            return view('views',['photos'=>$photos]);
  }
}

还是创建另一个Controller并在那里处理Web请求,并在routes文件中添加新的rout,例如:mysite.com\photos\all到路由文件?

or creating another Controller and handling the web requests there and adding a new rout in the routes file for example : mysite.com\photos\all to the routes file?

还是我必须将其保存在另一个Controller中,还是必须确定请求是否来自网络,使用下面的示例所示的相同方法:

or do I have to keep this in another Controller or do I have to decide whether or not the request is from the web inside the same method like the below example:

 public function index()
{
   $photos = Photo::all();        
   if ( from web ){
      return view('views',['photos'=>$photos]);
   } else {
      return response()->
                    json(['result' => $photos]);   
   }

}

我还必须提到我之前曾问过以下问题: 实现路线的最佳设计实践和RESTFul Laravel应用的控制器 但没有得到任何答案.

I also have to mention that I previously asked the below question: Best design practice to implement routes and controllers for a RESTFul Laravel app but didn't get any answer.

推荐答案

可能是有一个原因导致您上次询问该问题时没有得到答案.这确实取决于您的项目.我将分享我自己的偏好:

There's probably a reason why you didn't get an answer the last time you asked that question. It really depends on your project. I will share my own preference:

我有两组路由,中间件,控制器和通用服务.

I have two sets of routes, middleware, controllers and common services.

路线:

//For web
Route::resource('photo', 'PhotoController');

/For API, with versioning 
Route::resource('api/v1/photo', 'API\PhotoController');

中间件

//For web
public function handle($request, Closure $next, $role="view")
{
 if(Gate::denies($role.'-photo', $photo)){

        if($role == "view"){
            abort(404);
        }

        return $this->redirect($photo)->withErrors(['You are not authorized to see this photo']);;

    }
}
return $next($request);

/For API, with versioning 
 public function handle($request, Closure $next, $role="view")
{
   if(Gate::forUser(Auth::guard('api')->user())->denies($role.'-photo', $photo)){

        if($role == "view"){
            return Response::json([], 404);
        }

        return Response::json([], 403);

    }
}

return $next($request);

控制器

//PhotoController
class PhotoController{

     //RESTful name here   
     public function index(){

         $photoService = new PhotoService();
         $photos = $photoService->getAll();

         return view('views',['photos'=>$photos]);
     }
}

//API\PhotoController
class PhotoController{

     //RESTful name here   
     public function index(){
         $photoService = new PhotoService();
         $photos = $photoService->getAll();

         return Response::json($photos, 200);
     }
}

服务

class PhotoService(){

    //You could add a _construct() that would accept Request $request or User $user

    public function getAll(){
        return Photo::all(); 
    }
}

奖金:异常处理程序

您应该看一下似乎很多重复,但是对我来说,这比在任何地方添加$request->wantsJson()更具可读性和清晰度.您可能会认为这是一个过大的杀伤力,在某些情况下,这可能是一个过大的杀伤力.

It may seems like a lot of duplication but to me this is much more readable and clear than adding $request->wantsJson() everywhere. You might think that this is an overkill and, in some cases, it is probably an overkill.

但是,我之所以这样,是因为api和网络中的请求和响应逻辑是分开的.因此,我可以处理不同的请求(例如:访问用户信息)和不同的响应(例如:JSON或视图).它还为每种类型的请求创建专用空间,使您可以根据需要对应用的每个部分执行额外的逻辑.

However, I like this because the request and response logic from my api and my web are separated. Therefore I can deal with the different requests (ex: accessing the user information) and the different responses (ex: JSON or view). It also creates dedicated space for each type of request which allow you to execute extra logic if needed for each part of your app.

同样,这是一个偏好和项目问题,但我希望它能回答您的问题.

Again, it's a question of preference and project but I hope it answers your question.

这篇关于Restful laravel应用程序中用于控制器和方法的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆