我是 Symfony 框架的新手,正在尝试使用 Messenger(https://symfony.com/doc/current/messenger.html)建立一个项目。我的理解是在使用“实现 MessageHandlerInterface”设置处理程序类之后,处理程序应该可以使用,但它似乎对我不起作用。我尝试了几种不同的方法,包括从头开始建立一个新项目。我正在使用 Symfony 5.0.4。
我这样设置项目:
symfony new --full testMessenger
composer require messenger
php bin/console make:controller
然后我创建了一个新的信使和处理程序,并从控制器调用它。这样做我得到了异常:“<strong>No handler for message "App\Message\Message".”</p>
php bin/console debug:messenger
输出:
Messenger
=========
messenger.bus.default
---------------------
The following messages can be dispatched:
-----------------------------------------------------
Symfony\Component\Mailer\Messenger\SendEmailMessage
handled by mailer.messenger.message_handler
Symfony\Component\Notifier\Message\ChatMessage
handled by chatter.messenger.chat_handler
Symfony\Component\Notifier\Message\SmsMessage
handled by texter.messenger.sms_handler
-----------------------------------------------------
我的代码与消息处理程序文档中的示例基本相同,但我将在此处添加。
// src/Message.php
<?php
namespace App\Message;
class Message
{
private $content;
public function __construct(string $content)
{
$this->content = $content;
}
public function getContent(): string
{
return $this->content;
}
}
// src/MessageHandler.php
<?php
namespace App\MessageHandler;
use App\Message\Message;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
class SmsNotificationHandler implements MessageHandlerInterface
{
public function __invoke(Message $message)
{
// ... do some work - like sending an SMS message!
}
}
// src/Controller/MessageController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use App\Message\Message;
class MessageController extends AbstractController
{
/**
* @Route("/message", name="message")
*/
public function index()
{
$this->dispatchMessage(new Message('Look! I created a message!'));
return $this->render('message/index.html.twig', [
'controller_name' => 'MessageController',
]);
}
}
//config/packages/messenger.yaml
framework:
messenger:
# Uncomment this (and the failed transport below) to send failed messages to this transport for later handling.
# failure_transport: failed
transports:
# https://symfony.com/doc/current/messenger.html#transport-configuration
# async: '%env(MESSENGER_TRANSPORT_DSN)%'
# failed: 'doctrine://default?queue_name=failed'
# sync: 'sync://'
routing:
# Route your messages to the transports
# 'App\Message\YourMessage': async