PHP - generate functions from an array of strings

In my application, I need a lot of getter and setter, and my idea was to generate them from an array, for example:

protected $methods = ['name', 'city'];

With these two parameters, I will need to generate the following methods:

public function getNameAttribute() {
  return $this->getName();
}

public function getName($lang = null) {
  return $this->getEntityValue('name', $lang);
}

And for the city, the method will be:

public function getCityAttribute() {
  return $this->getCity();
}

public function getCity($lang = null) {
  return $this->getEntityValue('city', $lang);
}

Of course, I also need to generate a setter (with the same logic).

As you can see, I will need a method with get<variable_name>Attributeand inside this call get<variable_name>, and another (getName) will even return the same method (for each recipient) and simply change the parameter 'name'.

Each method has the same logic, and I would like to generate them "dynamically". I do not know if this is possible.

+4
source share
3 answers

__call() . , - :

public function __call($name, $args) {
    // Match the name from the format "get<name>Attribute" and extract <name>.
    // Assert that <name> is in the $methods array.
    // Use <name> to call a function like $this->{'get' . $name}().

    // 2nd Alternative:

    // Match the name from the format "get<name>" and extract <name>.
    // Assert that <name> is in the $methods array.
    // Use <name> to call a function like $this->getEntityValue($name, $args[0]);
}
+2

, .

$methods = ['name', 'city'];
$func = 'get'.$methods[1].'Attribute';
echo $func($methods[1]);

function getNameAttribute($func_name){
    $another_func = 'get'.$func_name;
    echo 'Name: '.$another_func();
}

function getCityAttribute($func_name){
    $another_func = 'get'.$func_name;
    echo 'City: '.$another_func();
}

function getCity(){
    return 'Dhaka';
}

function getName(){
    return 'Frayne';
}
0

Send these parameters (name, city or other) as a parameter to the universal method (if you do not know what parameters you can get)

public function getAttribute($value) {
  return $this->get($value);
}

public function get($value, $lang = null) {
  return $this->getEntityValue($value, $lang);
}

If you know your options, you can use this:

public function getNameAttribute() {
    return $this->getName();
}
$value = 'Name'; //for example
$methodName = 'get' . $value . 'Attribute';
$this->$methodName; //call "getNameAttribute"
0
source

Source: https://habr.com/ru/post/1655431/


All Articles