Getting the properties' original values of a Doctrine entity after an update

Published on 2022-01-25 • Modified on 2022-01-25

This snippet shows how to get the properties' original values of a Doctrine entity after an update. One learns every day, I have used Doctrine for many years, but I discovered this function quite recently (we can also detect modifications with Doctrine events and changesets). This function doesn't return an entity but an associative array field name/value.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * 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.
 */
trait Snippet186Trait
{
    public function snippet186(): void
    {
        $snippet = $this->articleData->getSnippetById(186);
        $originalAuthor = $snippet->getAuthor();
        $snippet->setAuthor('Les Tilleuls');
        $originalEntityData = $this->entityManager->getUnitOfWork()->getOriginalEntityData($snippet);

        echo 'Original author: '.$originalAuthor.PHP_EOL;
        echo 'New author: '.$snippet->getAuthor().PHP_EOL;
        echo 'Original author using the getOriginalEntityData() function: '.$originalEntityData['author'].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  More on the web

  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 Snippet186Trait
 */
final class Snippet186Test extends KernelTestCase
{
    private EntityManagerInterface $doctrine;
    private ArticleData $articleData;

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

    /**
     * @see Snippet186Trait::snippet186
     */
    public function testSnippet186(): void
    {
        $snippet = $this->articleData->getSnippetById(186);
        $originalAuthor = $snippet->getAuthor();
        $snippet->setAuthor('Les Tilleuls');
        $originalEntityData = $this->doctrine->getUnitOfWork()->getOriginalEntityData($snippet);

        self::assertNotSame($originalAuthor, $snippet->getAuthor());
        self::assertSame($originalAuthor, $originalEntityData['author']);
    }
}