How to access repository methods for an entity in symfony2?

允我心安 提交于 2019-11-29 12:31:42

问题


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 entity there are only getter and setter methods. All custom queries I have written to UserRepository. Now inside my UserController I am trying to access repository methods which I am not able to do so. e.g. User entity:

class User
{
    ...

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        return $this->id=$id;
    }
    public function setProperty($property)
    {
        $this->property = $property;
    }


    public function getProperty()
    {
        return $this->property;
    }

    ....

    }
  ?>

UserRepository:

class UserRepository extends EntityRepository
{


    public function findUsersListingById($id)
    {
        $queryBuilder = $this->getEntityManager()->createQueryBuilder();

       $query = $em->createQuery(
                    "SELECT U
                    FROM  UserEntityPathGoesHere
                    WHERE U.id IN (".implode(",", $id).")"
                );

        $users = $query->getResult();

        return $users;
    }

    public function sayHelloWorld(){

        echo ' Hello World';
    }

}
?>

UserController

class UserController
{
 ...


$users=$this->getDoctrine()
        ->getRepository('MyUserEntityPath')
        ->findUsersListingById($ids);

    //now I have multiple users I want to iterate through each user for associating additional data with each user

     foreach($users as $user)
     {
        $temp = array();

        //I am able to access getId method which is  defined in User entity
        $temp['id'] = $user->getId();

        //however I am not able to  access method from UserRepository, I tried something like below which gives me error  call to undefined function sayHelloWorld
        $temp['status'] = $user->sayHelloWorld();

       ....

     }


}

....

How can I access repository methods for an entity? Is it possible ? If not then what are the alternatives for the solution?


回答1:


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:

Controller > Repository > Entities.

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.

Controller > Service > Repository > Entities

Alternative solutions:

  • Create a Twig extension that access a service (which access a repository) or a repository.
  • Create a method in your repository, call the method in your controller, map the data to IDs (keys of array are the IDs), pass the array to the template and then pull the data from the array using the entity IDs
  • Create a method in your repository, call the method in your controller, inject the data into your entities and access the data through the entity in your template.

There are probably others but you would know better how your application is organized.




回答2:


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.




回答3:


If the bundle is Acme/DemoBundle, then one would expect at a minimum

User entity

namespace Acme/DemoBundle/Entity

use Doctrine\ORM\Mapping as ORM;


/**
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="Acme/DemoBundle/Entity/UserRepository")
 */
class User 
{
...
}

User repository

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 %}



回答4:


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.



来源:https://stackoverflow.com/questions/24712889/how-to-access-repository-methods-for-an-entity-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!