Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Symfony Messenger component documentation#9437

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
javiereguiluz merged 15 commits intosymfony:masterfromsroze:add-message-component
Apr 16, 2018
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
15 commits
Select commitHold shift + click to select a range
585491d
Move the documentation from the main PR to RST format.
srozeMar 14, 2018
b40bc71
Fixed the RST syntax issues
javiereguiluzMar 18, 2018
b26de80
minor doc fixes for the Message component
wieseMar 23, 2018
88ba8fe
Merge pull request #1 from wiese/patch-3
srozeMar 23, 2018
5c828e4
Update the documentation a bit, and add more FrameworkBundle document…
srozeMar 27, 2018
31a56ee
Uses `::` to display as code blocks
srozeMar 27, 2018
2493c90
Update typos and missing reference
srozeMar 27, 2018
bcfae23
Finish the documentation about the custom adapter
srozeMar 27, 2018
25c0b6e
It helps multiple applications
srozeMar 27, 2018
a15752b
Fix unresolved reference
srozeMar 27, 2018
fb88abc
Add Messenger in the topics
srozeMar 27, 2018
509e149
Add a documentation about middlewares and update based on reviews
srozeMar 27, 2018
3fb973c
Update based on comments
srozeMar 29, 2018
32403ea
Update the documentation to reflect the latest changes
srozeApr 12, 2018
c5306b8
Minor wording change
srozeApr 15, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added_images/components/messenger/overview.png
View file
Open in desktop
Loading
Sorry, something went wrong.Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
192 changes: 192 additions & 0 deletionscomponents/messenger.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
.. index::
single: Messenger
single: Components; Messenger

The Messenger Component
=======================

The Messenger component helps applications send and receive messages to/from other applications or via message queues.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

-    The Messenger component helps applications send and receive messages to/from other applications or via message queues.+    The Messenger component helps applications send messages to and receive messages from other applications and via message queues.

sroze and grisha-chasovskih reacted with thumbs down emoji

Installation
------------

.. code-block:: terminal

$ composer require symfony/messenger

Alternatively, you can clone the `<https://github.com/symfony/messenger>`_ repository.

.. include:: /components/require_autoload.rst.inc

Concepts
--------

.. image:: /_images/components/messenger/overview.png

**Sender**:
Responsible for serializing and sending messages to _something_. This
something can be a message broker or a third party API for example.

**Receiver**:
Responsible for deserializing and forwarding messages to handler(s). This
can be a message queue puller or an API endpoint for example.

**Handler**:
Responsible for handling messages using the business logic applicable to the messages.

Bus
---

The bus is used to dispatch messages. The behaviour of the bus is in its ordered
middleware stack. The component comes with a set of middleware that you can use.

When using the message bus with Symfony's FrameworkBundle, the following middleware
are configured for you:

#. ``LoggingMiddleware`` (logs the processing of your messages)
#. ``SendMessageMiddleware`` (enables asynchronous processing)
#. ``HandleMessageMiddleware`` (calls the registered handle)

Example::

use App\Message\MyMessage;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\HandlerLocator;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;

$bus = new MessageBus([
new HandleMessageMiddleware(new HandlerLocator([
MyMessage::class => $handler,
])),
]);

$result = $bus->handle(new MyMessage(/* ... */));

.. note:

Every middleware needs to implement the ``MiddlewareInterface`` interface.

Handlers
--------

Once dispatched to the bus, messages will be handled by a "message handler". A

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

"dispatched" is confusing here: according to the Bus section, the bus is responsible for dispatching messages; and the method used to get a message on to the bus ishandle().

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

No, it'sdispatch :)

message handler is a PHP callable (i.e. a function or an instance of a class)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

OskarStark and grisha-chasovskih reacted with thumbs up emoji
that will do the required processing for your message::

namespace App\MessageHandler;

use App\Message\MyMessage;

class MyMessageHandler
{
public function __invoke(MyMessage $message)
{
// Message processing...
}
}

Adapters
--------

In order to send and receive messages, you will have to configure an adapter. An
adapter will be responsible of communicating with your message broker or 3rd parties.

Your own sender
~~~~~~~~~~~~~~~

Using the ``SenderInterface``, you can easily create your own message sender.
Let's say you already have an ``ImportantAction`` message going through the
message bus and handled by a handler. Now, you also want to send this message as
an email.

First, create your sender::

namespace App\MessageSender;

use App\Message\ImportantAction;
use Symfony\Component\Message\SenderInterface;

class ImportantActionToEmailSender implements SenderInterface
{
private $toEmail;
private $mailer;

public function __construct(\Swift_Mailer $mailer, string $toEmail)
{
$this->mailer = $mailer;
$this->toEmail = $toEmail;
}

public function send($message)
{
if (!$message instanceof ImportantAction) {
throw new \InvalidArgumentException(sprintf('Producer only supports "%s" messages.', ImportantAction::class));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I would linebreak this, but again not sure what the norm is in Symfony. I know you guys don't like linebreaks, but maybe it's different for docs? Since you might want to avoid the wrapping

}

$this->mailer->send(
(new \Swift_Message('Important action made'))
->setTo($this->toEmail)
->setBody(
'<h1>Important action</h1><p>Made by '.$message->getUsername().'</p>',
'text/html'
)
);
}
}

Your own receiver
~~~~~~~~~~~~~~~~~

A receiver is responsible for receiving messages from a source and dispatching
them to the application.

Let's say you already processed some "orders" in your application using a
``NewOrder`` message. Now you want to integrate with a 3rd party or a legacy
application but you can't use an API and need to use a shared CSV file with new
orders.

You will read this CSV file and dispatch a ``NewOrder`` message. All you need to
do is to write your custom CSV receiver and Symfony will do the rest.

First, create your receiver::

namespace App\MessageReceiver;

use App\Message\NewOrder;
use Symfony\Component\Message\ReceiverInterface;
use Symfony\Component\Serializer\SerializerInterface;

class NewOrdersFromCsvFile implements ReceiverInterface
{
private $serializer;
private $filePath;

public function __construct(SerializerInteface $serializer, string $filePath)
{
$this->serializer = $serializer;
$this->filePath = $filePath;
}

public function receive(callable $handler) : void
{
$ordersFromCsv = $this->serializer->deserialize(file_get_contents($this->filePath), 'csv');

foreach ($ordersFromCsv as $orderFromCsv) {
$handler(new NewOrder($orderFromCsv['id'], $orderFromCsv['account_id'], $orderFromCsv['amount']));
}
}

public function stop(): void
{
// noop
}
}

Receiver and Sender on the same bus
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To allow us to receive and send messages on the same bus and prevent an infinite
loop, the message bus is equipped with the ``WrapIntoReceivedMessage`` middleware.
It will wrap the received messages into ``ReceivedMessage`` objects and the
``SendMessageMiddleware`` middleware will know it should not route these
messages again to an adapter.
1 change: 1 addition & 0 deletionsindex.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,7 @@ Topics
frontend
http_cache
logging
messenger
performance
profiler
routing
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp