题目描述
在laravel中使用Mosquitto-PHP,总是出现MosquittoClient找不到的错误
题目来源及自己的思路
我已经编译了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框架,我将上述代码放到里面后,总出现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' => '消息队列参数: 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' => '出现错误: '.$e->getMessage()
]);
return;
}
}
}
有没有大神知道如何在laravel中使用MosquittoClient这个类?
namespace
问题,新建对象的时候指定下路径便可,如下: