Just as a learning exercise I'm trying to build my own mini MVC in PHP.
What I want to achieve is a method that can be called before cetain other methods (similar to the before_filter method in ruby on rails)
For example; given the below controller class a user must have permission to do certain activities, so say I wanted to call checkPermissions() from BaseController before the create(), update() and delete().
class HomeController extends BaseController {
beforeFilter(checkPermissions,['create','update','delete']);
function index(){}
function create(){}
function update(){}
function delete(){}
}
Can anyone give me any guidance on how to achieve this? or enlighten me on the PHP way of doing this sort of task. I'm relatively new to PHP so please be gentle.
You should make use of the magic method __call
That magic method is called every time you call any function within your class.
That way you should be able to do the following:
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() {}
}
Please note that this only works for private or protected methods, not public ones.
If you want to use this on public methods, you should apply a decorator pattern like the following example:
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
I hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With