如何在 CakePHP shell 中使用 Ratchet websocket


How to use Ratchet websocket inside CakePHP shell

我想创建一个Websocket,需要从这个访问CakePHP ORM。我正在使用带有以下代码的棘轮Websocket:

<?php
use Ratchet'MessageComponentInterface;
use Ratchet'ConnectionInterface;
    // Make sure composer dependencies have been installed
    require __DIR__ . '/vendor/autoload.php';
/**
 * chat.php
 * Send any incoming messages to all connected clients (except sender)
 */
class MyChat implements MessageComponentInterface {
    protected $clients;
    public function __construct() {
        $this->clients = new 'SplObjectStorage;
    }
    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }
    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {
                $client->send($msg);
            }
        }
    }
    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
    }
    public function onError(ConnectionInterface $conn, 'Exception $e) {
        $conn->close();
    }
}

运行代码:

$app = new Ratchet'App('localhost', 8080);
$app->route('/chat', new MyChat);
$app->route('/echo', new Ratchet'Server'EchoServer, array('*'));
$app->run();

我需要做两件事:

  1. 我需要在MyChat类中访问CakePHP ORM。
  2. 我需要在 CakePHP 任务 shell 中启动该类。

第二个非常简单,但第一个我不知道如何初始化ORM类以在MyChat类中抛出查询。

我已经解决了将自身传递给MyChat构造函数的问题,如下所示:

$app->route('/chat', new MyChat($this));

要访问ORM,您可以像任何其他类一样设置模型类,并使用它们或任何您需要的内容进行查询。

编辑

如果你打算使用蛋糕壳,你只需要使用 App::uses 导入你的模型,甚至更好的是,你可以使用 'uses' 数组变量。文档中的详细信息 book.cakephp.org/2.0/en/console-and-shells.html