symfony doctrine动态地使用setter和getter

Yur*_*ges 4 php oop doctrine symfony

我正在使用symfony和doctrine.

服务器获取URL/company/{id}的HTTP PATCH请求,其中包含模型的属性及其值,例如{"name": "My new name"}需要将新值保存到DB中.

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

$repository = $this->getDoctrine()->getRepository('MyBundle:Company');
$company = $repository->find($id);
Run Code Online (Sandbox Code Playgroud)

现在我可以进入,$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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但这看起来并不聪明,特别是因为我知道我将拥有其他实体,如新闻,产品,用户等,这些实体将以相同的方式更新其属性.我想做这样的事情:

$company->set("property", "value");
Run Code Online (Sandbox Code Playgroud)

我首先想到的是将这个switch语句放在这个set函数中的公司类中,也放在我拥有的所有其他实体类中.但有更好的方法吗?也许symfony/doctrine已经内置了解决方案,但我找不到任何适合我的方法.

我仍然希望使用setter和getter作为长期投资.

谢谢.

Jay*_*att 9

假设您将拥有与方法名称类似的属性名称.

你可以做这样的事情.设置多个属性.

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));
    }

}
Run Code Online (Sandbox Code Playgroud)

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

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