Laravel:在侦听器上的字符串上调用成员函数send()



我正在尝试在新用户注册时做pushnotification。所以我创建了events称为MemberNotificationEvents的,当我在我的signUpController流上触发一个事件event(new MemberNotificationEvent($UserDetails));完全消失,但在MemberNotificationListener上出现一个public function handle(MemberNotificationEvent $event)返回错误:

在字符串上调用成员函数 send((

我放了MemberNotificationListener的完整代码:

<?php
namespace AppListeners;
use AppEventsMemberNotificationEvent;
use AppServicesPushNotificationService;
use IlluminateContractsQueueShouldQueue;
class MemberNotificationListener implements ShouldQueue
{
private $pushNotificationService;
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
$this->pushNotificationService = PushNotificationService::class;
}
private function getMessageBody($username)
{
return "Awesome! Welcome " . $username . " to IDM";
}
/**
* Handle the event.
*
* @param  object  $event
* @return void
*/
public function handle(MemberNotificationEvent $event)
{
$username = $event->UserDetails->name; 
$message = $this->getMessageBody($username);
$this->pushNotificationService->send($event,['body' => $message]); // throw error
}
}

我的代码中有什么问题?

问题出在以下行上:

$this->pushNotificationService = PushNotificationService::class;

当你做SomeClass::class时,这意味着你提供的类名 - 而不是实际的类。

因此,当您稍后执行$this->pushNotificationService->send(...)时,推送通知服务只是类名而不是服务类。

问题的第二部分是你需要一个实际的对象放在那里。Laravel可以在构造函数中为您注入它,然后您可以提供它。喜欢这个:

public function __construct(PushNotificationService $service)
{
$this->pushNotificationService = $service;
}