I have a great number of PHP classes which perform the business logic of my application, e.g.
class FileMaker{
public function makeFile(){
//some code here to make a file
}
}
Now I need to add permissions checks to them. I want to avoid having to copy/paste $this->checkPermissions() or similar into every method in every class. What's the best way of achieving this?
I was thinking some kind of decorator pattern which could add permissions checks, e.g:
//decorator that can be used to check permissions
class PermissionsDecorator{
private $ob;
public function __construct($ob){
$this->ob = $ob;
}
//magic method which is called when any function is called
public function __call($name,$arguments){
if($this->hasPermission(get_class($this->ob), $name)){
call_user_func_array(array($this->ob,$name),$arguments);
}else{
throw new Exception('You do not have permission to perform this action.');
}
}
public function hasPermission($class,$method){
echo 'does the user have permission on '.$class.'->'.$method.'?<br/>';
//do some logic here to work out whether the user has permission
return true;
}
}
The decorator above could apply to all classes because it uses the __call magic method, rather than specifying the exact methods to call. Then I could use code such as:
$fm = new PermissionsDecorator(new FileMaker());
This feels a bit 'hacky' to me though. Is there a standard way of doing this? Or will I just have to copy/paste permissions checks everywhere?
Aucun commentaire:
Enregistrer un commentaire