Laravel 5 - Class' DB'未找到

时间:2016-07-30 11:14:27

标签: laravel-5

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控制器。

5 个答案:

答案 0 :(得分:3)

这个更好

use Illuminate\Support\Facades\DB;

或者您可以在DB之前使用斜杠(&#39; /&#39;),如下所示

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

答案 1 :(得分:0)

尝试使用此

use Illuminate\Support\Facades\DB;

而不是

use DB;

答案 2 :(得分:0)

如先前建议的那样首先使用

use Illuminate\Support\Facades\DB;

然后转到/bootstrap/app.php并取消注释

$app->withFacades();

答案 3 :(得分:0)

对于Laravel 5及更高版本,只需使用

UserNameTextBox

代替

use DB;

用于Laravel 4版本

答案 4 :(得分:0)

更改用途Illuminate \ Support \ Facades \ DB;使用数据库;