I have some classes that do have a lot of properties!
Instead of creating a lot of getters and setters foreach class I decided to create an abstract class as templeate where I have a magic function __call
to set and get properties values using Php Reflection API
like below:
public function __call($name, $args)
{
//Check to see if we are getting a property value.
if (preg_match("/get/i", $name)) {
//Normalize method name, in case of camel case.
$name = strtolower($name);
//Find the start of get/set in the method.
$pos = strpos($name, "get") + strlen("get");
//Strip get / set from method. Get only property name.
$name = substr($name, $pos, strlen($name) - $pos);
//Refelct child class object.
$reflection = new \ReflectionClass($this);
//Get child class properties.
$props = $reflection->getProperties();
//Loop through the init. class properties.
foreach ($props as $prop) {
//Check if the property its array so we can search the keys in an array.
if (is_array($this->{$prop->getName()})) {
//So it's an array, check if array property has the key that we are looking for.
if (array_key_exists($name, $this->{$prop->getName()})) {
return $this->{$prop->getName()}[$name];
}
}
//If its not array then check for the property name that we are looking for.
else if ($prop->getName() == $name) {
return $this->$name;
}
}
return null;
}
//Same thing here same like in get method, but instead of getting the method
//here we will be setting a property value.
else if (preg_match("/set/i", $name)) {
$name = strtolower($name);
$pos = strpos($name, "set") + strlen("set");
$name = substr($name, $pos, strlen($name) - $pos);
$value = "";
//Make sure that we have an argument in there.
if (count($args) >= 1) {
$value = $args[0];
}
$reflection = new \ReflectionClass($this);
$props = $reflection->getProperties();
foreach ($props as $prop) {
if (is_array($this->{$prop->getName()})) {
if (array_key_exists($name, $this->{$prop->getName()})) {
$this->{$prop->getName()}[$name] = $value;
}
} else if ($prop->getName() == $name) {
$this->$name = $value;
}
}
}
}
My questions is:
Is this a good approach to make dynamic getters and setters or what are the downsides of this compare to child classes getters and setters! And what is the best way of handling not found properties throwing an exception or return null ?
Aucun commentaire:
Enregistrer un commentaire