mardi 29 septembre 2015

Include Class in Parent Based on Child Class

I have a child controller class that extends a base controller class. In the child I have defined a static namespace string that points to the model class I want to use when calling functions in the base class. Right now, I have to use call_user_func to call the function on the correct model class. The code looks something like this:

Child Class

class RolesController extends Controller
{
    const RESOURCE_NAME = 'roles';
    const MODEL = 'Role';
}

Parent Class

class Controller extends BaseController
{

    private $model;

    public function __construct()
    {
        $this->model = 'App\\Models\\' . static::MODEL;
    }

    public function getAll(Request $request)
    {
        $objects = call_user_func([$this->model, 'getAll'], [
            Model::GET_OPTION_FORMAT => true
        ]);

        return Response::success([
            static::RESOURCE_NAME => $objects
        ]);
    }
}

I can't help but think that this design pattern is incorrect. Is there a better way to accomplish what I am trying to do without having to rely on call_user_func? I can not find a similar question as I am struggling to find the words to describe this problem. If anyone could point me in the right direction it would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire