Ecotone
SponsorBlogGithubSupport and ContactCommunity Channel
  • About
  • Installation
  • How to use
    • CQRS PHP
    • Event Handling PHP
    • Aggregates & Sagas
    • Scheduling in PHP
    • Asynchronous PHP
    • Event Sourcing PHP
    • Microservices PHP
    • Resiliency and Error Handling
    • Laravel Demos
    • Symfony Demos
      • Doctrine ORM
  • Tutorial
    • Before we start tutorial
    • Lesson 1: Messaging Concepts
    • Lesson 2: Tactical DDD
    • Lesson 3: Converters
    • Lesson 4: Metadata and Method Invocation
    • Lesson 5: Interceptors
    • Lesson 6: Asynchronous Handling
  • Enterprise
  • Modelling
    • Introduction
    • Message Bus and CQRS
      • CQRS Introduction - Commands
        • Query Handling
        • Event Handling
      • Aggregate Introduction
        • Aggregate Command Handlers
        • Aggregate Query Handlers
        • Aggregate Event Handlers
        • Advanced Aggregate creation
      • Repositories Introduction
      • Business Interface
        • Introduction
        • Business Repository
        • Database Business Interface
          • Converting Parameters
          • Converting Results
      • Saga Introduction
      • Identifier Mapping
    • Extending Messaging (Middlewares)
      • Message Headers
      • Interceptors (Middlewares)
        • Additional Scenarios
      • Intercepting Asynchronous Endpoints
      • Extending Message Buses (Gateways)
    • Event Sourcing
      • Installation
      • Event Sourcing Introduction
        • Working with Event Streams
        • Event Sourcing Aggregates
          • Working with Aggregates
          • Applying Events
          • Different ways to Record Events
        • Working with Metadata
        • Event versioning
        • Event Stream Persistence
          • Event Sourcing Repository
          • Making Stream immune to changes
          • Snapshoting
          • Persistence Strategies
          • Event Serialization and PII Data (GDPR)
      • Projection Introduction
        • Configuration
        • Choosing Event Streams for Projection
        • Executing and Managing
          • Running Projections
          • Projection CLI Actions
          • Access Event Store
        • Projections with State
        • Emitting events
    • Recovering, Tracing and Monitoring
      • Resiliency
        • Retries
        • Error Channel and Dead Letter
          • Dbal Dead Letter
        • Idempotent Consumer (Deduplication)
        • Resilient Sending
        • Outbox Pattern
        • Concurrency Handling
      • Message Handling Isolation
      • Ecotone Pulse (Service Dashboard)
    • Asynchronous Handling and Scheduling
      • Asynchronous Message Handlers
      • Asynchronous Message Bus (Gateways)
      • Delaying Messages
      • Time to Live
      • Message Priority
      • Scheduling
      • Dynamic Message Channels
    • Distributed Bus and Microservices
      • Distributed Bus
        • Distributed Bus with Service Map
          • Configuration
          • Custom Features
          • Non-Ecotone Application integration
          • Testing
        • AMQP Distributed Bus (RabbitMQ)
          • Configuration
        • Distributed Bus Interface
      • Message Consumer
      • Message Publisher
    • Business Workflows
      • The Basics - Stateless Workflows
      • Stateful Workflows - Saga
      • Handling Failures
    • Testing Support
      • Testing Messaging
      • Testing Aggregates and Sagas with Message Flows
      • Testing Event Sourcing Applications
      • Testing Asynchronous Messaging
  • Messaging and Ecotone In Depth
    • Overview
    • Multi-Tenancy Support
      • Getting Started
        • Any Framework Configuration
        • Symfony and Doctrine ORM
        • Laravel
      • Different Scenarios
        • Hooking into Tenant Switch
        • Shared and Multi Database Tenants
        • Accessing Current Tenant in Message Handler
        • Events and Tenant Propagation
        • Multi-Tenant aware Dead Letter
      • Advanced Queuing Strategies
    • Document Store
    • Console Commands
    • Messaging concepts
      • Message
      • Message Channel
      • Message Endpoints/Handlers
        • Internal Message Handler
        • Message Router
        • Splitter
      • Consumer
      • Messaging Gateway
      • Inbound/Outbound Channel Adapter
    • Method Invocation And Conversion
      • Method Invocation
      • Conversion
        • Payload Conversion
        • Headers Conversion
    • Service (Application) Configuration
    • Contributing to Ecotone
      • How Ecotone works under the hood
      • Ecotone Phases
      • Registering new Module Package
      • Demo Integration with SQS
        • Preparation
        • Inbound and Outbound Adapters and Message Channel
        • Message Consumer and Publisher
  • Modules
    • Overview
    • Symfony
      • Symfony Configuration
      • Symfony Database Connection (DBAL Module)
      • Doctrine ORM
      • Symfony Messenger Transport
    • Laravel
      • Laravel Configuration
      • Database Connection (DBAL Module)
      • Eloquent
      • Laravel Queues
      • Laravel Octane
    • Ecotone Lite
      • Logging
      • Database Connection (DBAL Module)
    • JMS Converter
    • OpenTelemetry (Tracing and Metrics)
      • Configuration
    • RabbitMQ Support
    • Kafka Support
      • Configuration
      • Message partitioning
      • Usage
    • DBAL Support
    • Amazon SQS Support
    • Redis Support
  • Other
    • Contact, Workshops and Support
Powered by GitBook
On this page
  • Implementing custom Gateway
  • Building your own Bus
  • Invoking Handler directly
  • Invoking Aggregate's Handler directly
  • Gateway reply
  • Gateway reply Content Type
  • Repository Interfaces
  • Parameters to Message Conversion

Was this helpful?

Export as PDF
  1. Messaging and Ecotone In Depth
  2. Messaging concepts

Messaging Gateway

Message Gateway PHP

PreviousConsumerNextInbound/Outbound Channel Adapter

Last updated 1 year ago

Was this helpful?

The Messaging Gateway encapsulates messaging-specific code (The code required to send or receive a ) and separates it from the rest of the application code.

It takes Application specific data and convert it which then is sent via This hide Messaging specific code, from user's code.

Command/Query/Event Buses are implementations of Messaging Gateways.

Ecotone aims for eliminating Framework related code from Business related code, that's why Gateway can defined as interface in user's code base. Ecotone is responsible for generating implementation for any interface.

Implementing custom Gateway

To implement custom Gateway, we will be using clear interfaces and message channel.

namespace Product;

use Ecotone\Messaging\Annotation\Gateway;

//1
interface ProductGateway
{
    #[MessageGateway("buyProduct")]  // 2
    public function buy(string $product) : void;
}

// An Command Handler that we want to call from our Gateway
class ProductService
{
   #[CommandHandler("buyProduct")]
   public function buyProduct(string $product): void
   {
      // do something
   }
}
  1. By default gateway will be available under interface name in DI, in that case Product\ProductGateway. If you want to register it under different name for example "productGateway", then pass it to annotation #[ClassReference("productGateway")]

If you are using Symfony Integration, then it will be auto registered in Dependency Container with possibility to auto-wire the gateway.

As Command/Query/Event buses are Gateways, you can auto-wire them. They can be injected into Controller and called directly.

In Lite Configuration you can retrieve it using messaging system configuration.

$productGateway = $messagingSystem->getGatewayByName(ProductGateway::class);

2. Gateway enables method to be used as Messaging Gateway. You may have multiple Gateways defined within interface. The "buyProduct" is a channel name that we will be requesting.

Building your own Bus

Invoking Handler directly

In some cases you may want to invoke Query/Command Handler directly, not via Bus. In that case you may define Message Gateway that routes to given Handler.

Service Command Handler:

class OrderService {
    #[CommandHandler("placeOrder")]
    public function makeOrder(string $order)
    {
        // make order
    }
}

Gateway:

interface OrderGateway {
    #[MessageGateway("placeOrder")] 
    public function placeOrder(string $order): void;
}

This also works for Query Handlers. This way we can build an interface, which provides API for given set of behaviours e.g. OrderApi.

Invoking Aggregate's Handler directly

You may expose Aggregate's Command and Query Handlers through interface.

Aggregate:

#[Aggregate]
class Order {
    #[CommandHandler("cancelOrder")]
    public function makeOrder(CancelOrder $command)
    {
        // do something
    }
}

Gateway:

interface OrderGateway {
    #[MessageGateway("cancelOrder")] 
    public function placeOrder(#[AggregateIdentifier] string $orderId, #[Payload] CancelOrder $command)): void;
}

Gateway reply

    #[MessageGateway("getPrice")] 
    public function getPrice(string $productName) : int;

Gateway reply Content Type

{
   public function __construct(private QueryBus $queryBus)
   {
       $this->queryBus = $queryBus;   
   }
   
   public function getTicketStatusAction(Request $request) : Response
   {
      return new Response(
         $this->queryBus->sendWithMetadata(
            new GetTicketStatusQuery($request->get("ticketId")),
            ["replyContentType" => "application/json"]
         );
      )    
   }
}

Repository Interfaces

Repository implemented via interfaces are just higher level abstraction of Message Gateway. You enable them by marking attribute #[Repository].

interface OrderRepository
{
    #[Repository]
    public function getOrder(string $twitId): Order;

    #[Repository]
    public function findOrder(string $twitId): ?Order;

    #[Repository]
    public function save(Twitter $twitter): void;
}

Parameters to Message Conversion

#[MessageGateway("orders")]
public function placeOrder(#[Payload] Order $order, #[Header("executorId")] string $executorId);

Parameter converter types:

  • This will convert string passed under $content parameter to message payload

public function sendMail(#[Payload] string $content) : void;
  • This convert $content to message's payload and will add to headers under "receiverEmail" key value of $toEmail

public function sendMail(#[Payload] string $content, #[Header()] string $toEmail) : void;

Using combination of Messaging Gateway and we can build our own Buses. Messaging Gateway will be responsible for building Message and sending to the Router. And Router will be then based on need route it by payload / headers or whatever is needed.

Gateway may return values, but as you probably remember, everything is connected via . So how does we get the reply? During building, gateway adds header replyChannel which contains automatically created Channel. During , if any value was returned it will be sent via reply Channel. This way gateway may receive the reply and return it.

If you have registered for specific Media Type, then you can tell Ecotone to convert result of any to specific format. This is especially useful, when we are dealing with QueryBus, when we want to return the result to the caller of the request. In order to do this, we need to make use of Metadataand replyContentType header.

Read more about Repositories in .

In order to build , Parameter Converters are introduced. You may configure them manually or let Ecotone make use of default parameter converters.

Router
Message Channels
Message
Endpoint's method invocation
Converter
Gateway
Command Handling section
Message
Message
Message
Message channel.