what is the difference between event listerners and subscribers in symfony2 [duplicate] - events

I'm working in the Symfony2 framework and wondering when would one use a Doctrine subscriber versus a listener. Doctrine's documentation for listeners is very clear, however subscribers are rather glossed over. Symfony's cookbook entry is similar.

From my point of view, there is only one major difference:
The Listener is signed up specifying the events on which it listens.
The Subscriber has a method telling the dispatcher what events it is listening to
This might not seem like a big difference, but if you think about it, there are some cases when you want to use one over the other:
You can assign one listener to many dispatchers with different events, as they are set at registration time. You only need to make sure every method is in place in the listener
You can change the events a subscriber is registered for at runtime and even after registering the subscriber by changing the return value of getSubscribedEvents (Think about a time where you listen to a very noisy event and you only want to execute something one time)
There might be other differences I'm not aware of though!

Don't know whether it is done accidentally or intentionally.. But subscribers have higher priority that listeners - https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPass.php#L73-L98
From doctrine side, it doesn't care what it is (listener or subscriber), eventually both are registered as listeners - https://github.com/doctrine/common/blob/master/lib/Doctrine/Common/EventManager.php#L137-L140
This is what I spotted.

You should use event subscriber when you want to deal with multiple events in one class, for example in this symfony2 doc page article, one may notice that event listener can only manage one event, but lets say you want to deal with several events for one entity, prePersist, preUpdate, postPersist etc... if you use event listener you would have to code several event listener, one for each event, but if you go with event subscriber you just have to code one class the event susbcriber, look that with the event subscriber you can manage more than one event in one class, well thats the way i use it, i preffer to code focused in what the model business need, one example of this may be went you want to handle several lifecycle events globaly only for a group of your entities, to do that you can code a parent class and defined those global methods in it, then make your entities inherit that class and later in your event susbcriber you subscribe every event you want, prePersist, preUpdate, postPersist etc... and then ask for that parent class and execute those global methods.

Another important thing: Doctrine EventSubscribers do not allow you to set a priority.
Read more on this issue here

Both allow you to execute something on a particular event pre / post persist etc.
However listeners only allow you to execute behaviours encapsulated within your Entity. So an example might be updating a "date_edited" timestamp.
If you need to move outside the context of your Entity, then you'll need a subscriber. A good example might be for calling an external API, or if you need to use / inspect data not directly related to your Entity.

Here is what the doc is saying about that in 4.1.
As this is globally applied to events, I suppose it's also valid for Doctrine (not 100% sure).
Listeners or Subscribers
Listeners and subscribers can be used in the same application indistinctly. The decision to use either of them is usually a matter
of personal taste. However, there are some minor advantages for each
of them:
Subscribers are easier to reuse because the knowledge of the events is kept in the class rather than in the service definition.
This is
the reason why Symfony uses subscribers internally;
Listeners are more flexible because bundles can enable or disable each of them conditionally depending on some configuration value.
http://symfony.com/doc/master/event_dispatcher.html#listeners-or-subscribers

From the documentation :
The most common way to listen to an event is to register an event
listener with the dispatcher. This listener can listen to one or more
events and is notified each time those events are dispatched.
Another way to listen to events is via an event subscriber. An event
subscriber is a PHP class that's able to tell the dispatcher exactly
which events it should subscribe to. It implements the
EventSubscriberInterface interface, which requires a single static
method called getSubscribedEvents().
See the example here :
https://symfony.com/doc/3.3/components/event_dispatcher.html

Related

Is there a hook for reacting to a catching up Axon projection?

I want to implement a Axon projection providing a subscription query. The projection persists entities of a specific based on the events (CRUD). The following should happen if a replay of the projection is executed:
Inform about a empty collection via the subscription query.
Process the events until the projection catches up with the event store.
Inform about the current state of the entities via the subscription query.
My intention is that the subscription query should not inform about many events in a very short time and I want to prevent informing about many intermediate positions (e.g. create and delete a specific entity, it should not be used in the subscription query, because it is not available after catching up).
Currently I cannot implement the third step, because I miss a hook for reacting to the moment when the Axon projection is catching up again.
I use Axon v4.5 and Spring Boot v2.4.5.
At the moment, the Reference Guide is sadly not extremely specific on how to achieve this. I can assure you though that work is underway to improve the entire Event Processor section, including a clearer explanation of the Replay process and the hooks you have.
However, the possible hooks are stated as it is (you can find them here).
What you can do to know whether your event handlers are replaying yes/no, is to utilize the ReplayStatus enumeration. This enum can be used as an additional parameter to your #EventHandler annotated method, holding just two states:
REPLAY
REGULAR
This enumeration allows for conditional logic within an event handler on what to do during replays. If an event handler for example not only updates a projection but also sends an email, you'd want to make sure the email isn't sent again when replaying.
To further clarify how to use this, consider the following snippet:
#EventHandler
public void on(SomeEvent event, ReplayStatus replayStatus) {
if (replayStatus == REGULAR) {
// perform tasks that only may happen when the processor is not replaying
}
// perform tasks that can happen during regular processing and replaying
}
It's within the if-block where you could invoke the QueryUpdateEmitter, to only emit updates when the event handler is performing the regular event handling process.

Spring Integration order of Spring Integration Events

I'm dealing with Spring Integration Events and need to ensure proper order of event calls. I have two listeners. One is called TerminalErrorListener and catches TcpConnectionExceptionEvent and TcpDeserializationExceptionEvent. Second is called TerminalDisconnectEventListener and catches TcpConnectionCloseEvent.
In my case I use NIO and manually extended TcpNioConnection with my class which contains one extra field. This field is called Originator and carries information about what caused TcpConnectionCloseEvent and here comes my question.
I define the originator inside TerminalErrorListener and need to ensure that TerminalDisconnectEventListener is called after the TerminalErrorListener.
How can I generally ensure (probably I can guarantee that close event is called after the error) that this will happen? Is there any priority mode or default flow model which can be seen in some kind of diagram? I mean when are specific events called and what is the general sequence of all events.
Thanks for answer.
With NIO, there is no guarantee that you will get the deserialization failure event before the connection close event.

Axon How can I add an event listener/interceptor to intercept events before they reach their handlers?

I have a projection class (to build a read model) and I want to add an interceptor for its events in a way that if the id passed in the event leads to a null object (non-existent in my db) then I want to block it, otherwise let it pass.
This way I will escape adding a null checker on EVERY event handler.
#EventHandler
public void onEvent(Event event) {
Entity entity = getEntity(event.getId());
if(entity!=null){ // what I don't want to add on every event handler
dostuff();
}
}
I found that axon provides an interface called EventListener but I'm not sure how to work with it and I'm not sure if this will be intercepting ALL of my events or if I will be able to intercept select events.
There is no mention anywhere for this interface but in the official documentation (with no actual examples or so)
You are right on the part the the Reference Guide still needs some improvements #bleh10 - I can assure you, they're being worked on, the team is just spread out relatively thin.
In absence of the sought after example, I think I can give you some guidance.
What you're looking for is a MessageHandlerInterceptor implementation, specifically for the EventMessage type. As the naming suggests, it intercepts messages prior to being handled, which corresponds perfectly with the question you've posed.
Secondly, you obviously need a place to configure these. Within an Axon application, the technical aspect of delivering events to your #EventHandler annotated methods, is the Event Processor. As such, it is in charge of ensuring the Event Messages flowing through it are intercepted as desired.
Hence, the place to configure your EventMessage MessageHandlerInterceptor, is on the EventProcessor implementation you've chosen. To ensure a given Event Handling Component is set in a specific EventProcessor, you can specify it's Processing Group by annotating the class with the #ProcessingGroup annotation.
From there on, you can easily configure specific properties for your Event Processor by utilizing the EventProcessingConfigurer. More specifically, I'd suggest to use the EventProcessingConfigurer#registerHandlerInterceptor(String, Function<Configuration, MessageHandlerInterceptor<? super EventMessage<?>>>) method for this.
The first String parameter is meant to describe the name of your Processing Group. The second is a Function which receive the Axon Configuration and should output a MessageHandlerInterceptor which can deal with the EventMessage class.
Hope this helps you out!

Difference between Laravel queued event listeners vs jobs

I'm trying to wrap my head around Laravel's queued event listener vs jobs.
To me, it seems like that both are very similar:
Both implement the ShouldQueue interface (in the case of event listener, this is an option)
Both implement the handle() and failed() (optional) methods to perform their respective tasks.
Essentially, to me, both are queued items that can be run asynchronously.
What I am able to distinguish so far is that jobs have more "advanced" features/configurations like $timeout, $tries properties and you may also delay the 'trigger' of a job (courtesy of the Illuminate\Bus\Queueable trait).
There are more I'm sure, but I'm pointing out the one that pops out to me.
So, the question is, what's the actual difference between the two and more importantly, when do you favor one over the other?
Good question, I will begin by how laravel docs explains it
Events : Laravel's events provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other.
Where as
Jobs : Job classes are very simple, normally containing only a handle method which is called when the job is processed by the queue.
Essentially both are pushing jobs on to queues and/or do some processing its asked to do, the main difference I would say is how they are called.
Events are on the lookout to be called where as Jobs are always explicitly called.
Power of Events is that we can register multiple listeners for a single event and the event helper will dispatch the event to all of its registered listeners without us calling them explicitly. where in case of Jobs we would have to call them each one explicitly.
In short if you have a scenario where an event would trigger multiple method calls event would help. If its a single method call Jobs are good.
Events Scenario: user signs up -> Send email, Dispatch complimentary swag, Create a subdomain for a user profile userxyz.site.com etc etc
Jobs Scenario: user signs up -> Send email.
In the exact context of the question: "Event" is a "Queued Event Listener". Every Laravel Event has a Listener bound to it (the event listener), then, when we queue that event (in the listener) it is magically a "Queued Event Listener"
Well, they are very similar, the eventlistener takes an event as a parameter in the handle method, jobs don't.
Events are good in situations where you want to decouple the triggering part from the action part. For instance when you have several modules in the project and you want one module to react on an event in another.
One limitation of events compared to jobs are job chaining. If you for instance trigger several events from a controller you can't be sure that the worker dispatches them in sequence and that the first is completed before the other is started.
In these (rare) situations I sometimes end up with (non queued) listeners that in turn dispatches (queued) jobs that do the actual work (chained or unchained).

Difference between Observer, Pub/Sub, and Data Binding

What is the difference between the Observer Pattern, Publish/Subscribe, and Data Binding?
I searched around a bit on Stack Overflow and did not find any good answers.
What I have come to believe is that data binding is a generic term and there are different ways of implementing it such as the Observer Pattern or the Pub/Sub pattern. With the Observer pattern, an Observable updates its Observers. With Pub/Sub, 0-many publishers can publish messages of certain classes and 0-many subscribers can subscribe to messages of certain classes.
Are there other patterns of implementing "data binding"?
There are two major differences between Observer/Observable and Publisher/Subscriber patterns:
Observer/Observable pattern is mostly implemented in a synchronous way, i.e. the observable calls the appropriate method of all its observers when some event occurs. The Publisher/Subscriber pattern is mostly implemented in an asynchronous way (using message queue).
In the Observer/Observable pattern, the observers are aware of the observable. Whereas, in Publisher/Subscriber, publishers and subscribers don't need to know each other. They simply communicate with the help of message queues.
As you mentioned correctly, data binding is a generic term and it can be implemented using either Observer/Observable or Publisher/Subscriber method. Data is the Publisher/Observable.
Here's my take on the three:
Data Binding
Essentially, at the core this just means "the value of property X on object Y is semantically bound to the value of property A on object B. No assumptions are made as to how Y knows or is fed changes on object B.
Observer, or Observable/Observer
A design pattern by which an object is imbued with the ability to notify others of specific events - typically done using actual events, which are kind of like slots in the object with the shape of a specific function/method. The observable is the one who provides notifications, and the observer receives those notifications. In .net, the observable can expose an event and the observer subscribes to that event with an "event handler" shaped hook. No assumptions are made about the specific mechanism which notifications occur, nor about the number of observers one observable can notify.
Pub/Sub
Another name (perhaps with more "broadcast" semantics) of the Observable/Observer pattern, which usually implies a more "dynamic" flavor - observers can subscribe or unsubscribe to notifications and one observable can "shout out" to multiple observers. In .NET, one can use the standard events for this, since events are a form of MulticastDelegate, and so can support delivery of events to multiple subscribers, and also support unsubscription. Pub/Sub has a slightly different meaning in certain contexts, usually involving more "anonymity" between event and eventer, which can be facilitated by any number of abstractions, usually involving some "middle man" (such as a message queue) who knows all parties, but the individual parties don't know about each other.
Data Binding, Redux
In many "MVC-like" patterns, the observable exposes some manner of "property changed notification" that also contains information about the specific property changed. The observer is implicit, usually created by the framework, and subscribes to these notifications via some binding syntax to specifically identify an object and property, and the "event handler" just copies the new value over, potentially triggering any update or refresh logic.
Data binding re Redux
An alternative implementation for data binding? Ok, here's a stupid one:
a background thread is started that constantly checks the bound property on an object.
if that thread detects that the value of the property has changed since last check, copy the value over to the bound item.
I am a bit amused that all the answers here were trying to explain the subtle difference between Observer and Pub/Sub patterns without giving any concrete examples. I bet most of the readers still don't know how to implement each one by reading one is synchronous and the other is asynchronous.
One thing to note is: The goal of these patterns is trying to decouple code
The Observer is a design pattern where an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state.
Observer pattern
This means an observable object has a list where it keeps all its observers(which are usually functions). and can traverse this list and invoke these functions when it feels a good time.
see this observer pattern example for details.
This pattern is good when you want to listen for any data change on an object and update other UI views correspondingly.
But the Cons are Observables only maintain one array for keeping observers
(in the example, the array is observersList).
It does NOT differentiate how the update is triggered because it only has one notify function, which triggers all the functions stored in that array.
If we want to group observers handlers based on different events. We just need to modify that observersList to an Object like
var events = {
"event1": [handler1, handler2],
"event2": [handler3]
}
see this pubsub example for details.
and people call this variation as pub/sub. So you can trigger different functions based on the events you published.
I agree with your conclusion about both patterns, nevertheless, for me, I use Observable when I'm in the same process and I use the Pub/Sub in inter-process scenarios, where all parties only know the common channel but not the parties.
I don't know other patterns, or let me say this way, I've never needed another patterns for this task. Even most MVC frameworks and data binding implementations use usually internally the observer concept.
If you're interested in inter-process communication, I recommend you:
"Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions" -
https://www.enterpriseintegrationpatterns.com/
This book contains a lot of ideas about how to send messages between processes or classes that can be used even in intra-process communication tasks (it helped me to program in a more loose-coupled way).
I hope this helps!
One concrete difference is that an Observable is always engaged when an observer no longer wants to observe. But a subscriber can stop the subscription and the publisher will never be aware of these intent to unsubscribe

Resources