在RESTful API,Laravel应用程序中区分Web和移动请求

时间:2017-01-24 08:06:16

标签: rest laravel-5.3 restful-architecture

我正在Laravel 5.3开发一个应用程序,我正在为它实现RESTful API,我试图尽可能避免服务器端的冗余代码,例如我需要两个移动应用程序和Web应用程序将请求发送到相同的URL

例如用于更新类别

public function update($categoryId)
{
    //some code here   

}

移动应用程序和Web应用程序都会在CategoryController

中向上述函数发送更新类别的请求

问题:我需要找到不同类型请求的标准方式,例如,应将Web请求重定向到新页面,但如果移动请求只有JSON response应该发送回移动应用程序。在Controller中区分这些请求以了解从哪个设备发送哪个请求的标准和正确方法是什么?

2 个答案:

答案 0 :(得分:1)

为了获得更好的编码体验并避免重复,您可以使用Categories Repository和2个不同的控制器来处理桌面/移动路由。

CategoriesRepository.php

class CategoriesRepository{

  public function update($category_id, $data = []){

     $category = Category::findOrFail($category_id);

     return $category->update($data);

  }

  //another category related methods
}

路由/ web.php

Route::group(function(){
    Route::patch("category/{id}", 'CategoriesController@update');
});

//this can also be in the routes/api.php and will get the api prefix automatically
Route::group(["prefix" => "mobile"], function(){
    Route::patch("category/{id}", 'ApiCategoriesController@update');
});

CategoriesController.php

public function update(Request $request){
  (new CategoriesRepository)->update($request->category_id, $request->only("name", "type"));

  return view("categories.main");
}

ApiCategoriesController.php

public function update(Request $request){
  (new CategoriesRepository)->update($request->category_id, $request->only("name", "type"));

  return response([
    "success" => true,
    "message" => "The category has been updated successfully"
  ], 200);
}

答案 1 :(得分:0)

如果您以不同于网络/移动应用程序的方式呼叫update功能,只需传递另一个参数,然后进行切换或在控制器中使用该参数。