我是使用作曲家的新手,並且因爲Rachet和websockets而引起了我的注意。我能夠獲得Rachet websocket聊天應用程序的工作,但現在我想在示例中使用我自己的類。試圖瞭解如何在命名空間中添加我自己的類
我有相同的目錄結構聊天的例子中發現here這些名稱的變化:
/src/MyApp/Chat.php = /src/Websocket/SocketControl.php
/bin/chat-server.php = /bin/socket-server.php
我composer.json:
{
"autoload": {
"psr-0": {
"Websocket": "src"
}
},
"require": {
"cboden/ratchet": "^0.3.3"
}
}
在我src
文件夾我添加了一個文件夾MyClass
並有一個文件Foo.php
看起來是這樣的:
<?php
class Foo{
function __construct(){
echo "Foo construct!\n";
}
}
我怎麼能得到一個新的Foo在我SocketControler例如像:
<?php
namespace Websocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class SocketControl implements MessageComponentInterface {
protected $clients;
protected $foo;
public function __construct() {
$this->clients = new \SplObjectStorage;
$this->foo = new Foo();
echo "New construct!\n";
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
您告訴作曲者Websocket名稱空間位於src目錄中。所以如果你將foo設置爲命名空間Websocket \ MyClass,並嘗試使用Websocket \ MyClass \ Foo,它應該可以工作。 – JimL
@JimL我不知道如何告訴作曲家? – K3NN3TH
我將Foo類文件移動到Websocket fodler中,並將其名稱空間設置爲Websocket,並且可以工作,但我應該理解爲什麼我無法在不同的目錄中使用不同的名稱空間訪問它 – K3NN3TH