I am stuck with a problem please help me with it. Here is the scenarario:
I have an entity \"User\" and corresponding repository \"UserRepository\", inside my entit
Everything is possible however you should not access the entity's repository from the entity itself because of the separation of concerns.
See this Stackoverflow answer for more details.
Basically, the whole idea is that you want to have your application organized the following way.
In short:
It should not go in the other direction otherwise it creates a mess.
If you want to go a bit further into the separation of concerns you could do the following.
Alternative solutions:
There are probably others but you would know better how your application is organized.
You need to declare the UserRepository
as an EntityRepository
for your user entity. In your User
entity add this annotation:
/**
* @ORM\Entity(repositoryClass="Acme\StoreBundle\Entity\UserRepository")
*/
See the docs for a more detailed description.
You can use the postLoad event from doctrine and inject everything you want into the entity. The event listener looks like:
<?php
namespace AppBundle\EventListener;
use AppBundle\Entity\MyEntity;
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* Class MyEntityListener
*/
class MyEntityListener
{
public function postLoad(LifecycleEventArgs $eventArgs)
{
/** @var MyEntity $document */
$document = $eventArgs->getEntity();
if(!($document instanceof MyEntity)){
return;
}
$document->setEntityManager($eventArgs->getEntityManager());
}
}
and service.yml:
services:
app.myentity.listener:
class: AppBundle\EventListener\MyEntityListener
tags:
- { name: doctrine.event_listener, event: postLoad }
Of cource your Entity needs the method setEntityManager and your're ready.
If the bundle is Acme/DemoBundle, then one would expect at a minimum
namespace Acme/DemoBundle/Entity
use Doctrine\ORM\Mapping as ORM;
/**
*
* @ORM\Table(name="user")
* @ORM\Entity(repositoryClass="Acme/DemoBundle/Entity/UserRepository")
*/
class User
{
...
}
namespace Acme/DemoBundle/Entity
use Doctrine\ORM\Mapping as ORM;
class UserRepository extends EntityRepository
{
...
}
It is also true that with an array of ids, one can also do the following in a controller:
...
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository("AcmeDemoBundle:User")->findAllById($idArray);
...
To iterate thru users in a controller, one can then use a foreach loop as in:
foreach ($users as $user) {
//each user is an array
...
$id = $user['id'];
...
}
or in a template:
{% for user in users %}
...
{{ user.firstName }}
...
{% endfor %}