Backend Database Discussion PHP

persist() and flush() – Symfony

Call $entityManager->persist() and pass the object to save. And then $entityManager->flush().

use Doctrine\ORM\EntityManagerInterface;
class QuestionController extends AbstractController
{
public function new(EntityManagerInterface $entityManager)
{
$entityManager->persist($question);
$entityManager->flush();
}
}

Yes, you need both lines. The persist() call simply says:

Hey Doctrine! Please be “aware” of this Question object.

The persist line does not make any queries. The INSERT query happens when we call flush(). The flush() method says:

Yo Doctrine! Please look at all of the objects that you are “aware” of and make all the queries you need to save those.

So this is how saving looks: a persist() and flush() right next to each other. If you ever needed to, you could call persist() on 5 different objects and then call flush() once at the end to make all of those queries at the same time.

Anyways, now that we have a Question object, let’s make the Response more interesting. I’ll say sprintf with:

Well hallo! The shiny new question is id #%d, slug: %s

Passing $question->getId() for the first placeholder and $question->getSlug() for the second.

use Doctrine\ORM\EntityManagerInterface;
class QuestionController extends AbstractController
{
public function new(EntityManagerInterface $entityManager)
{
$entityManager->persist($question);
$entityManager->flush();
return new Response(sprintf(
‘Well hallo! The shiny new question is id #%d, slug: %s’,
$question->getId(),
$question->getSlug()
));
}
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *