dimanche 12 septembre 2021

Parent Controller class to call child overridden methods (Laravel)

I know this might seem anti pattern, and a lot will throw stones at me, but please hear me out.

I want to create a generic Controller to support many reference tables (mostly id, label). So I did something like this:

class GenericController extends Controller
{
    public function index($modelName)
    {
        $x = '\\App\\Models\\'.$modelName;
        $data = $model->all();
        return view('generic.list', ['model'=>$model, 'data'=>$data]);
    }
}

And this way my routes in web.php will be reduced to the minimum like this:

//List
Route::get('/{model}', function ($model) {
    return App::call('\App\Http\Controllers\GenericController@index', ['modelName' => $model]);
});

It's working very well with simple CRUD actions like store, update, etc.. However I know I am over simplifying the design because sometimes I need to return a field from a joined table in the index list for example. That's where I am heading into a dead end, sort of.

My first thought was to create a controller for each model that inherits from the GenericController like this:

class CategoryController extends GenericController
{
}

And whenever I need to override the GenericController method, I would simply add it to the child class. However how can I do this from inside the GenericController (call a method in a sub class from parent class)? Because otherwise I will have to create routes for every single model which is against my wish.

So basically I am looking for something like this:

class GenericController extends Controller
{
    public function index($modelName)
    {
        $x = '\\App\\Models\\'.$modelName;            
        //this thing I'm looking for is something like this:
        //Check if we have CategoryController and it has a definition for index
        //if yes do something like $data = CategoryController->index();
        //otherwise just call $data = $model->all();
        return view('generic.list', ['model'=>$model, 'data'=>$data]);
    }
}

So I know this seems weird and any patter, but other wise how can I create my generic routes and controller actions?

Aucun commentaire:

Enregistrer un commentaire