mercredi 1 novembre 2017

Laravel use extended controller or Traits or something else?

To maintain my Laravel application and save myself from a lot of duplicate code I have made the following solution:

BaseController

class BaseController extends Controller
{ 
    public function get($id){
        return $this->baseService->get($id);
    }

    public function getAll(){
        return $this->baseService->getAll();
    }
}

BaseService

class BaseService
{
    protected $model;

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

    public function get($id){
        return response()->json($this->model->where('id', $id)->first());
    }

    public function getAll()
    {
        return $this->model->get();
    } 
}

MyController

class MyController extends BaseController
{
    protected $model;
    protected $baseService;

    public function __construct(){
        $this->model= new Model();
        $this->baseService = new BaseService($this->model);
    }

    /**
     * This controller has all the functionality from BaseController now
     */
}

What I'm wondering if this is a good method. Should I stick with this or should I use a different approach? I've heard about Traits but not sure if they are doing the same thing. It's Laravel 5.5 I'm using.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2gTvUx7
via IFTTT

Aucun commentaire:

Enregistrer un commentaire