Laravel 4 model events the same as regular events - laravel

Are model events the same as regular events. And do you place model events as regular events? I'm trying to create a profile row when a user registers.

You can handle model events via some helper functions or using model observers.
But yes, behind the scenes, these events are fired Laravel's event dispatcher, so technically you could bind functions to those events via the Event facade, too.

Related

Eloquent model observer performance

If I have multipile models and I working heavy with events so in my AppServiceProvider I create a observer for my models like:
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
User::observe(UserObserver::class);
User2::observe(UserObserver2::class);
User3::observe(UserObserver3::class);
User4::observe(UserObserver4::class);
User5::observe(UserObserver5::class);
User6::observe(UserObserver6::class);
User7::observe(UserObserver7::class);
User8::observe(UserObserver8::class);
User9::observe(UserObserver9::class);
}
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
//
}
}
does it create some performance penalty? as If I understand the observe method correctly for every app access it will loop through all my models observers method and will match them to eloquent events so if I have 30 models observers it can cause a bad performance?
is there some clever way of declaring the observe class only when the model is in use? so instead of declaring the observers in each app access even when not needed each model will know about its observer only when its in use?
With model observers specifically, there is a performance impact that's greater than typical event registration. The extra overhead comes from how Laravel handles the observer event mapping. Since the events being registered are based on the existing methods, Laravel makes a minimum of 13 calls to method_exists per observer.
For just a couple of observers, that isn't a big deal. However, if you start using observers for audit trail processes and involve several models, this cost can start to add up.
As an example, I once worked on application that had four generalized observers that observed around 300 models between them (some of the models were shared by observers). This turned into over 600 Model::observe calls, and therefore over 7,800 calls into method_exists.
I've actually created a package (reedware/laravel-events) to solve this problem. You instead register observers (and other events) through a configuration file, and the events can be cached. The caching mechanism actually works for observers too (which doesn't work for Laravel out of the box), so the cost of observers becomes extremely minimal.
Alternatively, you could ditch the observer design pattern, and use the Model::creating(...) hooks within a bootable trait, or just throw custom events and register listeners for them.
If you use events with Laravel, the events will be registered (but not fired) on every request.
To be more precise, that the events will be registered means that User::observe(UserObserver::class); will loop through all methods of UserObserver and save them in an array of a dispatcher of the User class. Only if an update / create method through the User model is executed, the registered UserObserver method will be fired, i.e. called from the dispatcher.
So if you have 30 Models each with 5 methods in the Observer class, that would be 150 array bindings on every request to the dispatcher. However, the methods of your observer are not called during each request, only when the event fires. Thus, I don't believe that 150 array assignments will make an impact on the request time, compared to the time it takes to load a 120kb Logo or to execute query calls.
Best thing is of course to measure it for yourself. Measure the time of a request with binding the observer and without. You could use debugbar for it.
Side note: Using deferred providers won't make any difference, because you have to place the observer calls into the boot method of a provider. From the docs:
If your provider is only registering bindings in the service container, you may choose to defer its registration until one of the registered bindings is actually needed.

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).

Coordination between classes in Cocoa

I have a program with a lot of controllers which need to co - ordinate with each other . I'm confused about which mechanism to use . What are the pro and con of using :
Delegate
Bindings
Notifications
Key Value observing
Specifically is there any problem with using notifications all over place ? I'm planning to do that as it allows a class to just put out some information and not bother about anything else.
Use delegates if you want your object to have knowledge of specific methods to call when it needs to inform an observer of a state change. Notifications are more appropriate when you have multiple observers. Both of these require manual intervention, i.e. you need to explicitly call the delegate methods or post notifications when state changes.
Bindings and KVO work hand-in-hand, and are automatic ways to update state in one object (e.g. UI) when state in another object changes.

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

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

Synchronizing Event Calls from Threads to Event Handlers on Windows Forms

I have an object that is updated from a polling loop on a thread. This object fires particular events when data changes, etc.
I'm trying to use this object in conjunction with a windows form, where I create event handlers on the form to update the UI. Of course, this causes cross-thread operation exceptions if I try to manipulate the UI directly in these handlers.
I can get it to work by going through the standard procedure of checking InvokeRequired, using a delegate, blah blah blah. But I want to publish this object as a library, and I don't want end-users to have to worry about all that.
I want my object to somehow take care of synchronizing those event callbacks with the form so that end-users can manipulate the UI elements in those handlers worry-free.
Is there a way to do this??
If your object is always related to a single form, there is a simple trick indeed. The important fact here is, that you instanciate your object from the thread you like to affect the form later.
The trick is to instanciate a simple Control (new Control()) in your object in the constructor. When you perform logic on your form, use the Invoke/BeginInvoke methods on this simple control, to dispatch the action to the correct calling thread. So you have the dispatching logic directly in your object and there is no need for other users of your object to take care about this.

Resources