Search code examples
phpcomposer-phpratchet

NameScape Error. Stuck in 'MyApp\Chat'


Getting Error in Ratchet Simple Example:

Fatal error: Uncaught Error: Class 'MyApp\Chat' not found

My File Structure is like:

root\composer.json 
root\bin\chat-server.php 
root\src\MyApp\Chat.php

Composer.json is

{
    "autoload": {
        "psr-0": {
            "MyApp": "src"
        }
    },
    "require": {
        "cboden/ratchet": "0.3.*"
    }
}

chat-server.php is

<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;

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

    $server = IoServer::factory(
        new Chat(),
        8080
    );

    $server->run();

and Chat.php is

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

class Chat implements MessageComponentInterface {
    public function onOpen(ConnectionInterface $conn) {
    }

    public function onMessage(ConnectionInterface $from, $msg) {
    }

    public function onClose(ConnectionInterface $conn) {
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
    }
}

I have tried following, but still now works: PHP Fatal error: Class 'MyApp\Chat' not found in /MyApp/chat-server.php


Solution

  • Check your autoload naming https://getcomposer.org/doc/04-schema.md#psr-0

    It should be like that:

    {
        "autoload": {
            "psr-0": {
                "MyApp\\": "src/"
            }
        },
        "require": {
            "cboden/ratchet": "0.3.*"
        }
    }
    

    And do

    composer dump-autoload