首页 > 解决方案 > Symfony Messenger 与 API 平台集成:API 平台不发送消息

问题描述

我尝试使用 Symfony Messenger 集成并基于https://api-platform.com/docs/core/messenger/创建了一个非常简单(同步)的示例。

API 端点正确返回了202响应代码,但不幸的是,API 平台没有发送消息——Xdebug 既不会在断点处中断,\Symfony\Component\Messenger\RoutableMessageBus::dispatch也不会在\Symfony\Component\Messenger\TraceableMessageBus::dispatch.

更多详细信息:消息处理程序中的Adump('foo')不会被调用,并且从消息处理程序中记录日志消息也不会导致日志条目。

任何建议这个问题的原因可能是什么?

注意: Symfony Messenger 在我的项目中似乎工作正常——我可以成功地发送消息,例如在控制器动作中。

我将 Symfony 4.4.11 和 API Platform 2.5.6 与 PHP 7.2 一起使用。

这是消息处理程序:

<?php
declare(strict_types=1);
namespace App\Api\MessageHandler;

use App\Entity\RPC\MarkNotificationAsRead;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class MarkNotificationAsReadMessageHandler implements MessageHandlerInterface
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function __invoke(MarkNotificationAsRead $markNotificationAsRead)
    {
        dump($markNotificationAsRead);
        $this->logger->info('Lorem ipsum!');
    }
}

这是代表 API 资源的类的代码:

<?php
declare(strict_types=1);
namespace App\Entity\RPC;

use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ApiResource(
 *     messenger=true,
 *     collectionOperations={
 *         "post"={"status"=202}
 *     },
 *     itemOperations={},
 *     output=false
 * )
 */
final class MarkNotificationAsRead
{
    /**
     * @var string
     * @Assert\NotBlank
     */
    public $foo;
}

注意:这个类目前放在Entity命名空间中,但我没有为它添加任何 Doctrine 配置。

标签: symfonyapi-platform.com

解决方案


我刚刚解决了我的问题:我必须为 API 平台启用 Messenger。使用bin/console debug:config api_platform我意识到默认情况下它是禁用的:

# config.yml
api_platform:
    messenger:
        enabled: true

推荐阅读