I use symfony and doctrine.
The server receives an HTTP PATCH request for the URL / company / {id} containing the model property and its value, similar {"name": "My new name"}. The new value must be saved in the database.
$request = Request::createFromGlobals();
$requestContentJSON = $request->getContent();
$requestContentObj = json_decode($requestContentJSON);
$repository = $this->getDoctrine()->getRepository('MyBundle:Company');
$company = $repository->find($id);
Now I can just enter $company->setName($requestContentObj[0]);, but the resulting property will be different. Right now I am using the following code to be able to handle each property:
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;
}
}
But this does not look very smart, especially because I know that I will have other objects, such as news, products, users, etc. that will update their properties in the same way. I would like to do something like this:
$company->set("property", "value");
, switch , , . ? , symfony/doctrine , , .
.
.