gpt4 book ai didi

php - Doctrine\ORM\EntityManager,在类 MessageComponentInterface 中未指定

转载 作者:行者123 更新时间:2023-12-04 16:13:40 24 4
gpt4 key购买 nike

我在我的 symfony 2.8 项目中使用 Ratchet websocket 库。
我的问题是如何定义存在于另一个 Controller 方法中的实体管理器。

class WesocketController implements MessageComponentInterface
{
protected $clients;

public function __construct()
{
$this->clients = new \SplObjectStorage;
}

public function onMessage(ConnectionInterface $from, $msg)
{
echo $msg;
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

$myController = new OtherController();
$myController->test();

foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
}
我在其他 Controller 中的功能:
public function test()
{
// echo('yassine');

$em = $this->getDoctrine()->getManager();

$newTest = new VisitsTest();
$newVisitsTest
->setTestDate(new \DateTime())
->setClient(null);
$em->persist($newTest);
$em->flush();
}
错误:
PHP Fatal error:  Uncaught Error: Call to a member function has() on null in MyApp/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
错误在另一个 Controller 的这一行
$em = $this->getDoctrine()->getManager();
请帮助如何解决这个问题
谢谢

最佳答案

对于 Controller 操作,请考虑 Autowirring your services

public function test(EntityManagerInterface $em){
$newTest = new VisitsTest();
$newVisitsTest
->setTestDate(new \DateTime())
->setClient(null);
$em->persist($newTest);
$em->flush();
}

这样,您就不会为您正在调用的每个操作打开一个新的 EntityManager

关于php - Doctrine\ORM\EntityManager,在类 MessageComponentInterface 中未指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59049846/

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