Symfony update managed Entity elsewhere

93 views Asked by At

The usual way to update an entity is like this:

$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')->find($id);
$product->setName("New product name!");
$em->flush();

Calling persist() is not necessary: since you fetched the $product object from Doctrine, it's already managed.

But: what if fetch an entity and then pass it onto a update function, like so:

// Somewhere in the application I get the Product entity, call a setter, and want to save the Entity:
$product->setName("A new name!");
$productService->update($product);

// Inside productService:
function update(Product $product) {
    // what to do here to update the entity? Is it still managed?

    $em = $this->getEntityManager();
    $em->persist($product);
    $em->flush();
} 

Calling persist() would not be necessary if it's still managed, but is it? The code in update(..) does seem to work, but is it the right way to do it?

0

There are 0 answers