php - symfony 发生错误:通知:未定义的属性:::$容器

标签 php database symfony sockets websocket

我正在使用 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/

相关文章:

Symfony2 : how to log user out manually in controller?

sql - 加入甲骨文最高值(value)

mysql - 使用多表左连接插入时在单个表中插入重复行

PHP 在 HTML 论坛上运行带有多个参数的 shell 命令

php - 在 Joomla 中,如何为 index.php 创建 3x3(9 格)代码?

php - 从数据库中搜索字符串并获取接近单词的 php

php - Doctrine2 错误 "Expected known function, got ' COUNT'"when in order by clause

php - Symfony 访问控制与路由内部变量

mysql的PHP表错误

php - node.js 中的基本 smtp 服务器