I think the title asks it all. Very simple, I have an entity:
class User {
private $id;
private $name;
private $username;
}
with all the appropriate setters and getter. I have an array:
array( 'name' => 'joe', 'username' => 'shmoe' );
and I want to be able to do something like this:
Some\Unknown\Doctrine\Object::hydrateFromArray($array);
Obviously creating a function to hydrate it an 开发者_高级运维object would be easy enough, but surely doctrine must have something build in to accomplish this?
Figured it out. Given a repository:
//for odm
$repo->getDocumentManager()->getHydratorFactory()->hydrate($entity, $array);
I don't know if the same can be done for ORM, but I'm currently using ODM.
You could use the Serializer Component:
$user = $serializer->deserialize($data, 'Namespace\User', 'json');
http://symfony.com/doc/current/components/serializer.html#deserializing-an-object
As with Entities it's up to you to create the setters and getters.
class User
{
private $id;
private $name;
private $username;
public function fromArray($array)
{
// Code to fill the object here.
}
}
Also there's nothing that says you can't implement it in the constructor either. Remember, Doctrine 2 entities don't inherit anything from a main class unless you do it yourself. It just acts on it.
Thanks to answer of HKandulla, i using symfony component ObjectNormalizer
:
$myHydratedObject = (new ObjectNormalizer())->denormalize($array, MyAnyEntity::class);
精彩评论