你应该利用魔术方法 __call
每当你在类中调用任何函数时,都会调用该魔术方法。
这样你就可以做到以下操作:
class HomeController extends BaseController {
public function __call($method, $arguments)
{
if (method_exists($this, $method))
{
if (in_array($method, ['create', 'update', 'delete']) && !$this->checkPermissions())
{
return null;
}
return call_user_func_array([$this, $method], $arguments);
}
}
protected function index() {}
protected function create() {}
protected function update() {}
protected function delete() {}
}
请注意,这仅适用于私有或受保护的方法,而不是公共方法。
如果您想在公共方法上使用此功能,则应像以下示例一样应用装饰器模式:
class HomeController extends BaseController {
public function index() {}
public function create() {}
public function update() {}
public function delete() {}
}
class ControllerDecorator {
private $controller;
public function __construct($controller)
{
$this->controller = $controller;
}
public function __call($method, $arguments)
{
if (method_exists($this->controller, $method))
{
if (in_array($method, ['create', 'update', 'delete']) && !$this->checkPermissions())
{
return null;
}
return call_user_func_array([$this->controller, $method], $arguments);
}
}
private function checkPermissions() {}
}
$homeController = new HomeController();
$decoratedHomeController = new ControllerDecorator($homeController);
$decoratedHomeController->update();
我希望这有所帮助 :)