I have implemented the following PHP magic method behavior to save my time of creating accessor and mutators for properties of any class that extends this base class.
I am looking for suggesiongs on improving it for my application that assumes the following:
Properties of the form:
- $_first_name
- $_user_id
Methods of the form:
getUserId()
setFirstName("Mohammad")
I have some points that I think need more research:
Is it a secure way? What are the insecurities here?
Is my way of handling errors by using
throw new Exception('my message');
a good practice? What are the alternatives?Is there a best practice or a design pattern that addresses such a solution for reusability?
Am I exaggerating the steps? Are there any steps can be combine into one step with the same results?
The __call function of my Base class:
class Base
{
private $_first_name; // just an example
public function __call($name, $args)
{
// The begining of a method must be in all lower case characters.
// E.g. set, get
$result = preg_match('/^[a-z]*/', $name, $matches);
if($result !== 1)
{
throw new Exception('Action not recognized.');
}
// Hold the found action.
$action = $matches[0];
// Find the rest of the method name.
$result = preg_match_all('/[A-Z][a-z]*/', $name, $matches);
// $matches will hold a multi-dimensional array
// we need the first 1D array only.
$matches = $matches[0];
if($result < 1 || $result === FALSE)
{
throw new Exception('Malformed method name.');
}
// Construct the property name.
$property = '_' . strtolower(implode('_', $matches));
if(! property_exists($this, $property))
{
throw new Exception("Property: '{$property}' not found.");
}
switch($action)
{
// Mutator
case 'set':
{
if(count($args) === 1)
{
$this->$property = $args[0];
return;
}
else
{
throw new Exception('You must provide 1 argument only.');
}
}
// Accessor
case 'get':
{
return $this->$property;
}
}
}
}