我有一个小的WebSockets聊天写的,PHP的一部分仅仅是2个文件,server.php
和Chat.php
,他们都是一个bin
文件夹内,并取决于ratchet
和其他一些图书馆,我通过作曲家下载到laravel安装。如何正确添加外部PHP文件中Laravel 5
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();
}
}
现在,我有bin
文件夹中的laravel根里面,所以我能够启动服务器后server.php
期待对于供应商一级的依赖关系,但我想要做的是在这些文件中使用所有的laravel好东西,特别是在Chat.php
之内。
因此,现在例如,如果我写use DB
在Chat.php
它给出了一个错误(我明白,它无法知道laravel),所以我的问题是如何包含此bin文件夹及其文件,以便我可以使用它们中的所有laravel好东西?
我猜你的意思是应用程序/ HTTP /控制器,反正我做了一个'ChatController'这个命名空间:'命名空间应用程序\ HTTP \控制器;'和我做了'聊天服务器,php'在根文件夹中使用这个声明:'使用App \ Http \ Controllers \ ChatController;',但是当我从控制台运行它时,我得到这个:'Class'App \ Http \ Controllers \ ChatController'not fou nd in C:\ wamp \ www \ laraveltesting \ chatserver.php:13 ' – user6562256
要运行你的服务器,你需要调用server.php。所以它应该在一个控制器中。而chat.php只是一个帮助类来运行服务器,所以它是server.php的一个服务。这就是我提出上述结构的原因。 –
查看我的更新回答 –