Constructor injection in Doctrine 2 entity
- echo
- Member | 134
Hello,
I was wondering how to properly use constructor injection in doctrine entities.
Let's say I have entity Photo that has property $location. I want to
implement method getURL(). For me to be able to do that, I need to pass a
service UrlProvider into entity. Has anyone an elegant solution.
Solution 1:
Use different model. Something like $urlProvider->getURL($photo) thus no
method getURL() in photo entity.
Solution 2:
Use $container->callMethod(…) hooked as event postLoad().
Solution 3 (elegant):
?
Thanks for reviewing.
- mkoubik
- Member | 728
Entity itself doesn't depend on $urlProvider
, it uses it only in
one method for external formating. Thus the only reasonable approches for
me are
$entity->formatSomeProperty($helper);
and
$service->formatSomeProperty($entity);
both of them are unusable in templates. Personally, I would remap
the entities to some single-purpose data bags, but I don't dare to
seriously recommend this pattern to anybody yet.
Maybe someone
who considers leaking persistence-layer objects into templates ok will help
you with this :-)
Edit: maybe you could create template helper for this:
{$photo->location|location2url}
.
Last edited by mkoubik (2014-01-30 15:32)
- Filip Procházka
- Moderator | 4668
I don't understand where is the problem
{foreach $photos as $photo}
<a n:href="Photo:detail, $photo->id"><img n:src="$photo">
Method getUrl()
should not be on the photo entity. You could
have some “seoName” propety or “filename” property that contains
relative path to storage and everything else should be solved in storage.
Have a look at https://github.com/brabijan/images
And lastly constructor injection with entities doesn't make sense. Entity lifecycle is that you create it, it get's persisted and whenever you load it from databaze it's unserialized, therefore you cannot use constructor for anything else than parameters and relations of the entity. The only thing you can use is method injection using entity listeners. But I would strongly advise not to do that (at least not at this case), because you're trying to hack it with wrong design. Use proper storage.
Last edited by Filip Procházka (2014-01-30 17:08)