Should I reuse controllers in laravel between admin & api? or is my admin using my API?

New to laravel and trying to develop a better way to structure my application.

It has both an admin interface and an API (JSON, front-end corner).

Now my routes are as follows:

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')));

});

There is a lot of duplicate logic, for example, OrdersController and APIOrdersController. Should I ever use one controller, possibly with content? or is it better to modify the OrdersController to request API routes instead of using the eloquent one?

or is there another, better way?

+4
source share
1 answer

, ( ). , , . :

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
    }

}

.

API :

class APIOrderController extends APIController {

    protected $repository;

    public function __construct(OrderRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function create()
    {
        // Let 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);
    }

}

:

class AdminOrderController extends AdminController {

    protected $repository;

    public function __construct(OrderRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function create()
    {
        // Now, let 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');
    }

}

, . , , .

+4

All Articles