How to rectify [PHP Fatal error: Interface 'Ratchet\MessageComponentInterface' not found ] in ratchet

人盡茶涼 提交于 2021-01-27 07:25:34

问题


I'm trying to create a basic websocket chat from a tutorial in YouTube and I'am facing this error in the terminal when I run

php bin/server.php

Fatal error: Interface 'Ratchet\MessageComponentInterface' not found in /var/www/html/websocket/bin/chat.php on line 6

My code is as follows for chat.php:

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class chat implements MessageComponentInterface
    {
        protected $clients;
        public function __construct()
            {
                $this->clients=new \SplObjectStorage;
            }

        public function onOpen(ConnectionInterface $conn)
            {
                $this->clients->attach($conn);
            }

        public function onClose(ConnectionInterface $conn)
            {
                $this->clients->detach($conn);
            }

        public function onMessage(ConnectionInterface $conn,$msg)
            {
                foreach($this->clients as $client){
                    if($client !==$conn){
                        $client->send($msg);
                    }
                }
            }

        public function onError(ConnectionInterface $conn, \Exception $e)
            {
                echo "the following error occured: ".$e->getMessage();
                 $conn->close();
            }
    }

Code for server.php:

<?php
require 'chat.php';
require __DIR__ .'/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

$server=IoServer::factory(new HttpServer(new WsServer (new chat())) , 8080);
$server->run();

Any help would be appreciated.


回答1:


Include the autoload.php file which has all the definitions for autoloading before using the Ratchet\MessageComponentInterface.

Include this code snippet just after defining the namespace:

require dirname(__DIR__) . '/vendor/autoload.php';




回答2:


go to the composer.json and change

{
    "require": {
        "cboden/ratchet": "^0.4"
    }
}

to

{
    "autoload": {
        "psr-4": {
            "MyApp\\": "src"
        }
    },
    "require": {
        "cboden/ratchet": "^0.4"
    }
}

and open command promote with administration update the composer like

composer update

you should have to be on the same folder directory where the composer.json is on



来源:https://stackoverflow.com/questions/34378161/how-to-rectify-php-fatal-error-interface-ratchet-messagecomponentinterface-n

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