0

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

guidsen
  • 2,333
  • 6
  • 34
  • 55
  • 2
    BaseController with the methods, and model/repository injected to the controllers extending it - off the top of my head. – Jarek Tkaczyk Sep 30 '14 at 14:30
  • Would it be an abstract class or what do u mean, could u provide a simple example? Would appreciate it :)! @JarekTkaczyk – guidsen Sep 30 '14 at 15:39

1 Answers1

2

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;
  }
}
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
  • How will I use the Request class in Laravel 5? Cause in every method I have to inject another Request object. For example from the `Eventcontroller` I will need a `UpdateEventRequest` on my update method in my `Basecontroller`. – guidsen Sep 30 '14 at 23:09
  • Then just adjust it, the way I showed is for basic L4 controllers. In Laravel5 you have much more power thanks to method injection and other cool features. – Jarek Tkaczyk Sep 30 '14 at 23:14
  • Any suggestion or tip for how I can inject the specific Request class to my BaseController method? – guidsen Sep 30 '14 at 23:16