php - Include Class in Parent Based on Child Class -
i have child controller class extends base controller class. in child have defined static namespace string points model class want use when calling functions in base class. right now, have use call_user_func
call function on correct model class. code looks 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 think design pattern incorrect. there better way accomplish trying without having rely on call_user_func
? can not find similar question struggling find words describe problem. if point me in right direction appreciated.
long answer
what makes cumbersome static methods on model classes. cleaner approach this:
class rolescontroller extends controller { const resource_name = 'roles'; const model = app\models\role::class; } class controller extends basecontroller { private $model; public function __construct() { $modelclass = static::model; $this->model = new $modelclass; } public function getall(request $request) { $objects = $this->model->getall([ model::get_option_format => true ]); return response::success([ static::resource_name => $objects ]); } }
i kept "model class constant" approach, made explicit reference class.
but using actual objects, recommend go 1 step further , instantiate without indirection of class constant:
class rolescontroller extends controller { const resource_name = 'roles'; public function __construct() { parent::__construct(); $this->model = new app\models\role(); } } class controller extends basecontroller { protected $model; public function __construct() { } public function getall(request $request) { $objects = $this->model->getall([ model::get_option_format => true ]); return response::success([ static::resource_name => $objects ]); } }
note don't need change static method getall
non-static method. calling static methods $object->method
works fine in strict mode (just not other way around).
short answer
you can use variable class name (not property, tried, parser can't understand this):
$class = $this->model; $objects = $class::getall([ model::get_option_format => true ]);
but solves immediate coding problem not structural problem.
Comments
Post a Comment