我正在使用 ratchet 和 symfony 2.8 开发一个网络套接字应用程序以连接到数据库并在有人连接到服务器时更改特定列中的值但我在这一行中收到错误
$sql = $this->container->get('database_connection');
完整的错误信息
发生错误:注意:未定义属性:check\roomsBundle\Sockets\Chat::$container
我在services.yml代码中注入(inject)
services:
database_connection:
class: check\roomsBundle\Sockets\Chat
arguments: ["@service_container"]
我的 Chat.php 代码
<?php
namespace check\roomsBundle\Sockets;
use tuto\testBundle\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class Chat implements MessageComponentInterface {
protected $clients;
//protected $db;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
$sql = $this->container->get('database_connection');
$users = $sql->query("UPDATE user SET ONoff= '1' WHERE UserId='2'");
}
}
最佳答案
好的,为了解决您的问题,您需要解决一些问题。
services:
database_connection:
class: check\roomsBundle\Sockets\Chat
arguments: ["@service_container"]
它所做的是当它调用将要传递给服务容器的构造函数时,但是使用构造函数传递给您的容器是不利的,相反您应该实现 Symfony\Component\DependencyInjection\ContainerAwareInterface
接口(interface),然后实现方法 setContainer
和可选的 getContainer
方法。
/**
* @param ContainerInterface|NULL $container
*/
public function setContainer(
ContainerInterface $container = NULL
)
{
$this->container = $container;
return $this;
}
/**
* @return ContainerInterface
*/
protected function getContainer()
{
return $this->container;
}
然后更新您的服务以在初始化时调用此方法。
services:
chat_service: # renamed because this is your chat service, not your database connection
class: check\roomsBundle\Sockets\Chat
calls:
- [setContainer, ["@service_container"]]
关于php - symfony 发生错误:通知:未定义的属性:::$容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894896/