gpt4 book ai didi

php - 动态使用 setter 和 getter 的 symfony Doctrine

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:55:45 24 4
gpt4 key购买 nike

我正在使用 symfony 和 doctrine。

服务器获取 URL/company/{id} 的 HTTP PATCH 请求,其中包含模型的属性及其值,如 {"name": "My new name"} 新值需要持久化到数据库中。

$request = Request::createFromGlobals();
$requestContentJSON = $request->getContent();
$requestContentObj = json_decode($requestContentJSON);

$repository = $this->getDoctrine()->getRepository('MyBundle:Company');
$company = $repository->find($id);

现在我可以输入 $company->setName($requestContentObj[0]); 但收到的属性会有所不同。现在我正在使用以下代码来处理每个属性:

foreach($requestContentObj as $key => $value){
switch($key){
case 'name':
$company->setName($value);
break;
case 'department':
$company->setDepartment($value);
break;
case 'origin':
$company->setOrigin($value);
break;
case 'headquarters':
$company->setHeadquarters($value);
break;
case 'email':
$company->setEmail($value);
break;
case 'twitterid':
$company->setTwitterId($value);
break;
case 'description':
$company->setDescription($value);
break;
}
}

但这看起来不太聪明,尤其是因为我知道我会有其他实体,如新闻、产品、用户等,它们的属性将以相同的方式更新。我想做这样的事情:

$company->set("property", "value");

我首先想到的是将此 switch 语句放在此 set 函数内的公司类中以及我拥有的所有其他实体类中。但是有更好的方法吗?也许 symfony/doctrine 已经内置了解决方案,但我没有找到适合我的东西。

我仍然希望将 setter 和 getter 作为一项长期投资。

谢谢。

最佳答案

假设您将拥有类似于方法名称的属性名称。

你可以这样做。设置多个属性。

Class customer {

protected $_email;

public function __construct(array $config = array()){
$this->setOptions($config);
}

public function getEmail(){
return $this->_email;
}

public function setEmail($email){
$this->_email = $email;
}

public function setOptions(array $options)
{
$_classMethods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $_classMethods)) {
$this->$method($value);
} else {
throw new Exception('Invalid method name');
}
}
return $this;
}

public function setOption($key, $value){
return $this->setOptions(array($key, $value));
}

}

现在你可以简单地这样做:

$array = array('email' => 'abc.@gmail.com');
$customer = new Customer($array);
echo $customer->getEmail();

关于php - 动态使用 setter 和 getter 的 symfony Doctrine ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23078604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com