Life cycle events

Last modified by Ashterix on 2024/07/11 12:46

Events were added to JsonRpcBundle starting from version 7.0.
Now the components of the RPC server lifecycle operate through events, and you have the opportunity to subscribe to them to make its operation more flexible.

Using events requires certain knowledge and skills from you; certain actions during event subscription can lead to unexpected results, so you use events at your own risk.

List of Events

During its lifecycle, the RPC server uses its own events, which are based on Symfony Event

 Event  Description  

 rpc.request 

class RpcRequestEvent

Occurs when an RPC request is received. Use this event to check or modify the request before processing it.

 

 rpc.pre_execute 

class RpcPreExecuteEvent

Occurs before executing the RPC method. Use this event to prepare or modify calls before their execution.

 

 rpc.post_execute 

class RpcPostExecuteEvent
Occurs after executing the RPC method. You can use this event to process results or perform actions after the method call completes.  

 rpc.response 

class RpcResponseEvent
Occurs before sending the RPC response. Use this event to check or modify responses before sending them to the client.  

 rpc.error 

class RpcErrorEvent
Occurs when an error occurs while processing an RPC request. You can use it to handle errors or perform actions in case of an error.  

 rpc.async_request 

class RpcAsyncRequestEvent
Occurs when an asynchronous RPC request is received. Use it to process or modify asynchronous requests before their execution.  

 rpc.async_output 

class RpcAsyncOutputEvent
Occurs when an asynchronous response is sent. You can use it to check or modify asynchronous responses before sending them.  

Subscribing to Events Using Symfony Listeners

To subscribe to these events, you can create Symfony listeners. A basic listener example looks like this:

Example of a custom event subscriber
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

namespace App\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Ufo\JsonRpcBundle\Event\RpcRequestEvent;
use Ufo\JsonRpcBundle\Event\RpcEvent;

#[AsEventListener(event: RpcEvent::REQUEST, method: 'onRpcRequest')]
class RpcEventListener
{
   public function onRpcRequest(RpcRequestEvent $event): void
    {
       // your own event handler
   }
}

After creating the listener, it will be automatically registered thanks to the attributes. For more detailed information, see the Symfony documentation on events: Symfony Event System

This will allow your listener to subscribe to events and perform the necessary actions during the RPC server's lifecycle.