Reinitializing a Doctrine entity after a modification

Published on 2022-01-06 • Modified on 2022-01-06

In this snippet, we see how to reinitialize a Doctrine entity after a modification. The trick is to use the refresh() function of the entity manager (it's, in fact, a shortcut calling the function on the UnitOfWork object). If you want to know which fields of your entity are modified, check out this snippet.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use App\Data\ArticleData;
use Doctrine\ORM\EntityManagerInterface;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property ArticleData            $articleData
 * @property EntityManagerInterface $entityManager
 */
trait Snippet183Trait
{
    public function snippet183(): void
    {
        // get the current snippet
        $snippet = $this->articleData->getSnippetById(183);
        echo 'Author before update: '.$snippet->getAuthor().PHP_EOL;

        // modify the author
        $snippet->setAuthor('https://les-tilleuls.coop');
        echo 'Author after update: '.$snippet->getAuthor().PHP_EOL;

        // restore initial state of entity
        $this->entityManager->refresh($snippet);
        // $this->entityManager->getUnitOfWork()->refresh($snippet); // long version

        // we should see the orginial author now!
        echo 'Author after refresh: '.$snippet->getAuthor().PHP_EOL;

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Random snippet

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use App\Data\ArticleData;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet183Trait
 */
final class Snippet183Test extends KernelTestCase
{
    private EntityManagerInterface $entityManager;
    private ArticleData $articleData;

    protected function setUp(): void
    {
        $this->entityManager = self::getContainer()->get(EntityManagerInterface::class);
        $this->articleData = self::getContainer()->get(ArticleData::class);
    }

    /**
     * @see Snippet183Trait::snippet183
     */
    public function testSnippet183(): void
    {
        $originalAuthor = 'COil';
        $snippet = $this->articleData->getSnippetById(183);
        self::assertSame($originalAuthor, $snippet->getAuthor());

        $snippet->setAuthor('https://les-tilleuls.coop');
        self::assertSame('https://les-tilleuls.coop', $snippet->getAuthor());

        $this->entityManager->refresh($snippet);
        self::assertSame($originalAuthor, $snippet->getAuthor());
    }
}