gpt4 book ai didi

symfony - 如何访问 symfony2 中实体的存储库方法?

转载 作者:行者123 更新时间:2023-12-04 00:27:20 24 4
gpt4 key购买 nike

我遇到了一个问题,请帮帮我。这是场景:

我有一个实体“User”和相应的存储库“UserRepository”,在我的实体内部只有 getter 和 setter 方法。我已写入 UserRepository 的所有自定义查询。现在在我的 UserController 中,我试图访问我无法访问的存储库方法。
例如
用户实体:

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

....

}
?>

用户存储库:
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';
}

}
?>

用户 Controller
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();

....

}


}

……

如何访问实体的存储库方法?是否可以 ?如果不是,那么解决方案的替代方案是什么?

最佳答案

您可以使用学说中的 postLoad 事件并将所需的所有内容注入(inject)实体。事件监听器如下所示:

    <?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());

}
}

和 service.yml:
services:
app.myentity.listener:
class: AppBundle\EventListener\MyEntityListener
tags:
- { name: doctrine.event_listener, event: postLoad }

当然,您的实体需要方法 setEntityManager 并且您已准备好。

关于symfony - 如何访问 symfony2 中实体的存储库方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24712889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com