Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dzimidula's avatar

How to properly add external php files

I have a small websockets chat written, the php part is just 2 files, server.php and Chat.php, they are both inside a bin folder and depend on ratchet and some other libraries which I downloaded to the laravel installation via composer.

server.php

require __DIR__.'/../vendor/autoload.php';
require 'Chat.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();

Chat.php

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {

    protected $clients;

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

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

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

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

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

}

Now, I have that bin folder inside the laravel root, and so I am able to start the server since the server.php is looking for dependencies in vendor one level up, but what I wanna do is use all the laravel goodies within these files, especially within Chat.php.

So now for example if I write use DB in Chat.php it gives an error (which I understand, it has no way of knowing laravel), so my question is how do I include this bin folder and its files so that I can use all the laravel goodies within them?

0 likes
8 replies
jbloomstrom's avatar

Just skimming through your code, it looks like you have a typo in the onError method. Not sure if that's the only source of your trouble.

$conn-close();

Should be:

$conn->close();
jimmck's avatar

@dzimidula Hey! I do it the same with Rachet and ZMQ. Have a bin dir

<?php
use React\EventLoop\Factory;
use React\ZMQ\Context;
use App\lib\push\Pusher;

require dirname(__DIR__) . '/vendor/autoload.php';
$loop = Factory::create();
$pusher = new Pusher;
// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array ($pusher, 'onBlogEntry'));
// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(new Ratchet\Http\HttpServer(new Ratchet\WebSocket\WsServer(new Ratchet\Wamp\WampServer($pusher))), $webSock);
$loop->run();
<?php namespace App\lib\push;

    use Ratchet\ConnectionInterface;
    use Ratchet\Wamp\WampServerInterface;

    class Pusher implements WampServerInterface
    {
        /**
         * A lookup of all the topics clients have subscribed to
         */
        protected $subscribedTopics = array ();
        protected $id;

        public function onSubscribe(ConnectionInterface $conn, $topic)
        {
            $this->subscribedTopics[$topic->getId()] = $topic;
        }

        /**
         * @param string JSON'ified string we'll receive from ZeroMQ
         */
        public function onBlogEntry($entry)
        {
            //$entryData = json_decode($entry, true);
            $entryData = $entry;
            if ($entryData === null) {
                $entryData = 'NULL DATA???';
            }

            print PHP_EOL . "Message is [" . $entryData . "]" . PHP_EOL;
            // If the lookup topic object isn't set there is no one to publish to
            /*
            if (!array_key_exists($entryData['category'], $this->subscribedTopics)) {
                return;
            }
            */
            $topic = $this->subscribedTopics['cvg_cat'];
            // re-send the data to all the clients subscribed to that category
            $topic->broadcast($entryData);
        }

        /* The rest of our methods were as they were, omitted from docs to save space */
        public function onUnSubscribe(ConnectionInterface $conn, $topic)
        {
        }

        public function onOpen(ConnectionInterface $conn)
        {
        }

        public function onClose(ConnectionInterface $conn)
        {
        }

        public function onCall(ConnectionInterface $conn, $id, $topic, array $params)
        {
            // In this application if clients send data it's because the user hacked around in console
            $conn->callError($id, $topic, 'You are not allowed to make calls')->close();
        }

        public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible)
        {
            // In this application if clients send data it's because the user hacked around in console
            $conn->close();
        }

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

Give it a shot.

dzimidula's avatar

@jimmck I didn't really get it, anyway I tried the following:

I made a ChatController with this namespace: namespace App\Http\Controllers; and I made chatserver,php in the root folder with this using statement: use App\Http\Controllers\ChatController;, however when I run it from console I get this: Class 'App\Http\Controllers\ChatController' not fou nd in C:\wamp\www\laraveltesting\chatserver.php:13

Any ideas how to make chatserver.php recognize the app/http/controllers files?

jimmck's avatar

@dzimidula You don't reference your controller from the chat server. The server runs indendently

dzimidula's avatar

@jimmck The ChatController is the Chat.php script from my original post + the namespace, I have to call that class in the server.php, that's how my example works.

dzimidula's avatar

Ok managed to get it to work somehow with help from some tutorial.

chatserver.php in the root

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;

require  'vendor/autoload.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatController()
        )
    ),
    8080
);

$server->run();

ChatController

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use DB;

class ChatController extends Controller implements MessageComponentInterface {

    protected $clients;

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

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

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

            DB::table('messages')->insert(
                 ['message' => $msg]
             );
        }
    }

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

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

}

However I still can't use Laravel goodies inside the ChatController, Fatal error: Uncaught Error: Class 'DB' not found in C:\wamp\www\laraveltesting\app\Http\Controllers\ChatController.php:31

Any idea why?

jimmck's avatar

@dzimidula Man have you looked at the sample code I posted?

  1. The require vendor... is for the autoloader. It has to be the First LINE in your script.
  2. It goes in your chat server script.
  3. What is your ChatController? Is it a Laravel controller? If yes it does not belong in your server as a reference.
  4. Also I cannot read your code as its all grey in box.
  5. I just pasted your code in sublime so I can read.
  6. You don't reference the controller in your server. Look at my Push server. Its only job in life is to push messages onto the ZMQ managed queue. What kind of transport are you using? ZMQ, plain sockets. Some other library? Gotta know.

You need to first understand how namespaces get resolved in a Autoloader. Put that require at the top.

dzimidula's avatar

I don't know why the code is grey, yours is grey too, it's a forum issue.

I put vendor autoload at the top and same error message appears. As you can see from my previous post I have made progress, chat code is now in a laravel controller and the chatserver.php is in the root, it works (the server starts without problems) but when I send a message I get this error:

Fatal error: Uncaught Error: Class 'DB' not found in C:\wamp\www\laraveltesting\app\Http\Controllers\ChatController.php:31

For some reason it cannot use the DB, even though I am extending the laravel controller.

If I remove DB::table('messages')->insert( ['message' => $msg] ); from

from ChatController then it works, but obviously the point is to use the DB and any other laravel goodies inside the ChatController.

Please or to participate in this conversation.