Jac*_*man 5 php api rest laravel
Laravel 新手并试图找出构建我的应用程序的最佳方式。
它同时具有管理界面和 API(JSON、angularjs 前端)。
我的路线目前看起来像:
Route::group(array('prefix' => 'admin', 'before' => 'auth.admin'), function()
{
Route::any('/', array('as' => 'admin.index', function() {
return View::make('admin.index');
}));
Route::resource('countries.products', 'ProductsController');
Route::resource('countries', 'CountriesController');
Route::resource('orders', 'OrdersController');
});
// Route group for API versioning
Route::group(array('prefix' => 'api/v1'), function()
{
Route::resource('products', 'APIProductsController', array('only' => array('index', 'show')));
Route::resource('orders', 'APIOrdersController', array('only' => array('store', 'update')));
});
Run Code Online (Sandbox Code Playgroud)
例如,OrdersController 和 APIOrdersController 中有很多重复的逻辑。我应该以某种方式重新使用单个控制器,也许是内容协商?还是修改 OrdersController 来查询 API 路由而不是使用 eloquent 更好?
还是有另一种更好的方法?
正如我所看到的,我会将所有对象创建逻辑提取到适当的类中(听起来像是存储库的一个很好的例子)。这个类应该只知道它必须接收的参数,并做出相应的响应。例如:
class EloquentOrder implements OrderRepositoryInterface {
// Instance of OrderValidator,
// assuming we have one
protected $validator;
public function create($params)
{
// Pseudo-code
$this->validator = new Ordervalidator($params);
if ($this->validator->passes())
create and return new Order
else
return validator errors
}
}
Run Code Online (Sandbox Code Playgroud)
然后,每个模块都可以在其控制器内使用此功能。
在你的 API 中,你可以这样:
class APIOrderController extends APIController {
protected $repository;
public function __construct(OrderRepositoryInterface $repository)
{
$this->repository = $repository;
}
public function create()
{
// Let's imagine you have an APIAuth class which
// authenticates via auth tokens:
if (APIAuth::check()) {
$params = Input::all();
return $this->repository->new($params);
}
return Response::json(['error' => 'You are not authorized to create orders'], 401);
}
}
Run Code Online (Sandbox Code Playgroud)
在管理模块中,您可以:
class AdminOrderController extends AdminController {
protected $repository;
public function __construct(OrderRepositoryInterface $repository)
{
$this->repository = $repository;
}
public function create()
{
// Now, let's imagine Auth uses a different authentication
// method, and can check for specific permissions
if (Auth::check() && Auth::hasPermission('create.orders')) {
$params = Input::all();
return $this->repository->new($params);
}
return Redirect::home()->with('message', 'You are not authorized to create orders');
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这允许您在不同的上下文中重用对象创建逻辑。在示例中,我使用了不同的身份验证方法和响应,只是为了显示灵活性,但这实际上取决于您的项目要求。