Pass any model extension to controller method

48 Views Asked by At

I have something like this:

class ModelA extends Model {}
class ModelB extends Model {}
class DefaultController extends Controller {
    protected function getData(Model $model) {
        return $model::where(...)->first();
    }
}
class MyControllerA extends DefaultController {
    private function show() {
        $this->getData(new ModelA);
        // Error: Must be Model, but ModelA given.
    }
}
class MyControllerB extends DefaultController {
    private function show() {
        $this->getData(new ModelB);
        // Error: Must be Model, but ModelB given.
    }
}

I want to pass any instance of Model to function getData, since in that method I will use only Model instances. When I pass an instance of ModelA PHP throws an error that Model is expected as parameter. I cannot define getData(ModelA $model), since I need any model subclass (e.g. ModelB) to be passed to that method.

As I know, I could do that if Model was abstract, but it isn't.

0

There are 0 best solutions below