鍍金池/ 問答/PHP/ 在laravel中使用Mosquitto-PHP

在laravel中使用Mosquitto-PHP

題目描述

在laravel中使用Mosquitto-PHP,總是出現(xiàn)MosquittoClient找不到的錯誤

題目來源及自己的思路

我已經(jīng)編譯了mosquitto.so,并加入了php.ini, 并且使用如下代碼沒有問題:

<?php

$c = new Mosquitto\Client;
$c->onConnect(function() use ($c) {
    $c->publish('mgdm/test', 'Hello', 2);
    $c->disconnect();
});

$c->connect('test.mosquitto.org');

// Loop around to permit the library to do its work
// This function will call the callback defined in `onConnect()`
// and disconnect cleanly when the message has been sent
$c->loopForever();

echo "Finished\n";

由于項目中是使用laravel框架,我將上述代碼放到里面后,總出現(xiàn)SymfonyComponentDebugExceptionFatalThrowableError: Class 'MosquittoClient' not found 的錯誤。

laravel時的代碼如下:

<?php                                                                                                                                                                  
namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Log;
use Mosquitto\Client;

class QueueService
{
    public function __construct(){
    }   

    public function send($payload, $cb){
        if(!is_callable($cb)){
            $cb = function(){};
        }   

        if(!$payload){
            $cb([
                'status' => true,
                'code' => '', 
                'data' => ['c' => $c, 'send' => $send],
                'message' => '消息體為空'
            ]); 
            return;
        }   

        $broker = env('AMQP_ACTIVEMQ_BROKER', '');
        $port = env('AMQP_ACTIVEMQ_PORT', '');
        $topic = env('AMQP_ACTIVEMQ_TOPIC', '');
        if(!$broker || !$topic || !$port){
            $cb([
                'status' => true,
                'code' => '', 
                'data' => [], 
                'message' => '消息隊列參數(shù): Broker 或 Topic 錯誤'
            ]);
            return;
        }

        try{
            $url = $broker.":".$port;
            //$c = new \Mosquitto\Client;
            $c = new Client;
            $c->onConnect(function($rc, $message) use ($c, $topic, $payload) {
                $c->publish($topic, $payload, 2);
            });

            $c->onPublish(function($mid) use($c){
                $cb([
                    'status' => true,
                    'code' => '',
                    'data' => [
                        'mid' => $mid
                    ],
                    'message' => '請求成功'
                ]);
                $c->disconnect();
            });

            $c->connect($url);
            $c->loopForever();
        } catch (\Exception $e) {
            $cb([
                'status' => false,
                'code' => '',
                'data' => [],  
                                'message' => '出現(xiàn)錯誤: '.$e->getMessage()
            ]);
            return;
        }
    }
}

有沒有大神知道如何在laravel中使用MosquittoClient這個類?

回答
編輯回答
雨萌萌

namespace 問題,新建對象的時候指定下路徑便可,如下:

$c = new \Mosquitto\Client;
2017年10月6日 22:19