Bra*_*rad 3 php model-view-controller
就像学习练习一样,我正在尝试用PHP构建自己的迷你MVC.
我想要实现的是一个可以在cetain其他方法之前调用的方法(类似于rails上的ruby中的before_filter方法)
例如; 给出以下控制器类用户必须有权限做一些活动,所以说我想叫checkPermissions()从BaseController之前的create(),update()和delete().
class HomeController extends BaseController {
beforeFilter(checkPermissions,['create','update','delete']);
function index(){}
function create(){}
function update(){}
function delete(){}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以给我任何指导如何实现这一目标?或者启发我做PHP这种任务的方式.我对PHP比较陌生,所以请保持温和.
你应该使用魔术方法__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; // Permission is wrong, do something
}
return call_user_func_array([$this, $method], $arguments);
}
}
protected function index() {}
protected function create() {}
protected function update() {}
protected function delete() {}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这仅适用于私有或受保护的方法,而不适用于公共方法.
如果要在公共方法上使用它,则应该应用以下示例中的装饰器模式:
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; // Permission is wrong, do something
}
return call_user_func_array([$this->controller, $method], $arguments);
}
}
private function checkPermissions() {}
}
$homeController = new HomeController();
$decoratedHomeController = new ControllerDecorator($homeController);
$decoratedHomeController->update(); // Will check for permissions
Run Code Online (Sandbox Code Playgroud)
我希望它有帮助:)