我有
ChatController
位于 app/http/controllers
,如下所示:
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();
}
}
我的根目录中有
chatserver.php
文件,如下所示:
<?php
require 'vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new ChatController()
)
),
8080
);
$server->run();
如果我删除
DB::table('messages')->insert(
['message' => $msg]
);
从
ChatController
并启动 chatserver.php
它可以工作,但如果我不删除它,服务器就会启动,但一旦我发送消息,我就会收到此错误:
Fatal error: Uncaught Error: Class 'DB' not found in C:\wamp\www\laraveltesting\app\Http\Controllers\ChatController.php:31
为什么不使用DB?我正在扩展 Laravel 控制器。
这个比较好
use Illuminate\Support\Facades\DB;
或者你可以在 DB 之前使用斜杠('/'),如下所示
/DB::table('messages')->insert(
['message' => $msg]
);
尝试使用这个
use Illuminate\Support\Facades\DB;
而不是
use DB;
如前所述 首次使用
use Illuminate\Support\Facades\DB;
然后去 /bootstrap/app.php 并取消注释
$app->withFacades();
对于 Laravel 5 及更高版本,只需使用这个
use DB;
而不是
use Illuminate\Support\Facades\DB;
用于 Laravel 4 版本
更改使用 Illuminate\Support\Facades\DB;使用数据库;
将其添加到您的测试类文件中(在
class
关键字之前),以便您的测试可以找到 Laravel 应用程序的位置并创建一个新应用程序。
if (!isset($app)) {
$app = new \Illuminate\Foundation\Application(
// E.g. if the current dir is app/tests/Unit/
// Your path may differ
realpath(__DIR__.'/../../')
);
}
并在要使用DB的测试方法中添加
global $app
public function testSomething()
{
global $app;
//
}