在我的应用程序中,我需要很多getter和setter,我的想法是从数组中生成它们,例如:
protected $methods = ['name', 'city'];
使用这两个参数,我需要生成以下方法:
public function getNameAttribute() {
return $this->getName();
}
public function getName($lang = null) {
return $this->getEntityValue('name', $lang);
}
对于城市,方法将是:
public function getCityAttribute() {
return $this->getCity();
}
public function getCity($lang = null) {
return $this->getEntityValue('city', $lang);
}
当然,我也需要生成setter(使用相同的逻辑)。
正如您所看到的,我将需要一个get<variable_name>Attribute
的方法,在此调用get<variable_name>
内,另一个(getName)返回相同的方法(对于每个getter),只需更改{{ 1}}参数。
每个方法都有相同的逻辑,我想“动态”生成它们。我不知道这是否可能..
答案 0 :(得分:2)
您可以利用__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]);
}
答案 1 :(得分:0)
看看这个,让我知道这是你的要求。
<ul class="nav navbar-nav pull-right">
<li class="">
<a href="#"><img src="https://upload.wikimedia.org/wikipedia/commons/f/f5/Loxoceles_reclusa_iconized_thread.png" class="swingimage" width="200" height="200" > </a>
</li>
</ul>
答案 2 :(得分:0)
将此参数(名称,城市或其他)作为参数发送到通用方法(如果您不知道可以获得什么参数)
public function getAttribute($value) {
return $this->get($value);
}
public function get($value, $lang = null) {
return $this->getEntityValue($value, $lang);
}
如果您了解自己的参数,可以使用:
public function getNameAttribute() {
return $this->getName();
}
$value = 'Name'; //for example
$methodName = 'get' . $value . 'Attribute';
$this->$methodName; //call "getNameAttribute"