LBA February 2016

Identify whether a managed entity needs to be refreshed based on getReference

Let's assume I have an entity 'Application' and one of 'Application's' attributes is Category (it doesn't really matter of which association type).

So when I know the Category by ID I can call something like:

$category = $entityManager->getReference('Category', 1);
$application->setCategory($category);
$entityManager->flush();

getReference will create a Proxy which can be set as an attribute with my application. And this works without any additional SQL query sent to the DB for getting/setting my Category.

Great!

But wait, when I try to e.g. get the name for my category afterwards, what would I do? I thought I'd:

 $category = $entity->getRepository('Category')->find(1);
 $name = $category->getName();

What's happening is that I don't get the name but an error that the entity cannot be found.

I can fight this issue by explicitly calling:

 $entityManager->refresh($category);

Now this will reload my Category from the database and now I can get the name.

My Question is:

Is there any chance to identify whether I have just a reference to Category or an initialized / real proxy one?

Because in my case, sometimes I have a need to access Category after retrieving a Reference to it and sometimes not.

If I do it by 'refresh' anytime I will have unnecessary SQL statements executed which I really have to avoid performancewise and

$entityManager->getUnitOfWork()->getEntityState($category)

delivers MANAGED in any case.

Answers


Dymen1 February 2016

according to this: http://stackoverflow.com/a/26257234/3784145 you can check if the reference is an instance of the proxy class (Doctrine\ORM\Proxy\Proxy) and take action accordingly

Post Status

Asked in February 2016
Viewed 3,392 times
Voted 4
Answered 1 times

Search




Leave an answer