guidsen
guidsen

Reputation: 2393

Design pattern to reuse code with different instances

I'm developing an API and in the controller the index, store, show, update and destroy methods are all the same except for the Model that is being used.

How would you implement this?

I was thinking about a ActionRepository where I create those methods and will resolve the model somehow. I am not sure how I can reach the model though..

Really would appreciate some feedback on this ;)!

Upvotes: 0

Views: 138

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81157

You can do this:

abstract class BaseController extends LaravelController {
  protected $repository; // or $model or whatever you need

  public function index() { // your logic }
  public function show($id) {
    // your logic here, for example
    return $this->repository->find($id);
    // or
    return $this->model->find($id);
  }
  public function create() { // your logic }
  public function store() { // your logic }
  public function edit($id) { // your logic }
  public function update($id) { // your logic }
  public function destroy($id) { // your logic }
}

class SomeSolidController extends BaseController {
  public function __construct(SomeRepositoryInterface $repository)
  {
    $this->repository = $repository;
  }
}

Upvotes: 2

Related Questions