Magento Event On Any Page Load - magento

I am wondering if there is an event that is fired once every time a page is loaded before rendering to html in magento?
This might be useful if you want to do some business logic for semi-static attributes that don't rely on user sessions.
For example I will be using this to deliver the canonical tag to the header of magento.

There are several request-related events which are dispatched for most page-/content-generating requests. Below is a partial list in processing order of some useful ones, and I expect others may comment on this post with some others. Many of these are not suitable for your need (I've noted in bold below where you should begin considering). There are also a few block-instantiation-related events which, although they could be observed for your purpose, are generic to every block and really aren't appropriate.
The first practical singly-fired event is controller_front_init_before. This event is dispatched in Front Controller initialization in response to all dispatched requests. Because it is dispatched before the action controllers are invoked, only global-area observers will be able to observe this event.
Assuming the request is routed from the Front Controller through the routers to an action controller, there are some events which can be observed prior to rendering in preDispatch() - note the generic controller_action_predispatch event handle which could be consumed for all events vs the two dynamic event handles:
Mage::dispatchEvent('controller_action_predispatch', array('controller_action' => $this));
Mage::dispatchEvent('controller_action_predispatch_' . $this->getRequest()->getRouteName(),
array('controller_action' => $this));
Mage::dispatchEvent('controller_action_predispatch_' . $this->getFullActionName(),
array('controller_action' => $this));
How a response is being rendered may affect the events available; the main variations would come from whether or not layout updates are being used to render the response (and how). For example, core_layout_update_updates_get_after could be used to inject a layout update file to the list of configured module layout update files (a rare but potentially useful case). The controller actions are closely coupled with the layout modeling, so there are a few events which could work:
controller_action_layout_load_before
controller_action_layout_generate_xml_before
controller_action_layout_generate_blocks_before and controller_action_layout_generate_blocks_after - the latter of which would be the first applicable to your needs
Assuming that renderLayout() is being used in all actions about which you care, there are two events (one generic and one route-specific) which it dispatches:
Mage::dispatchEvent('controller_action_layout_render_before');
Mage::dispatchEvent('controller_action_layout_render_before_'.$this->getFullActionName());
After all of the routing, dispatching, view configuring, block instantiating, and rendering are done, there is one last-ditch event which is dispatched by the Front Controller before the response is sent: controller_front_send_response_before. This event is not suitable for your need, but it's a nice bookend to the controller_front_init_before event which began this answer.

http://www.nicksays.co.uk/magento-events-cheat-sheet-1-7/ this will help.
app/code/core/Mage/Core/Controller/Varien/Action.php this event
controller_action_layout_load_before
is fired
app/code/core/Mage/Core/Block/Abstract.php event
core_block_abstract_to_html_before
above two events might be of help.

I think you are looking for this event controller_action_layout_render_before_RouteName_ControllerName_ActionName
you can also log all the events which are fired on any page load from Mage class in below function
public static function dispatchEvent($name, array $data = array())
{
Mage::log($name);
Varien_Profiler::start('DISPATCH EVENT:'.$name);
$result = self::app()->dispatchEvent($name, $data);
Varien_Profiler::stop('DISPATCH EVENT:'.$name);
return $result;
}

We can use controller_front_init_routers event using observer. In that observer method,you can get request object as follows.
$request = $observer->getEvent()->getData('front')->getRequest();

Related

Assert laravel model observer's event fired in PHPUnit

I'm going to write some tests for my laravel 7 controller methods (endpoints) to be sure that they fire model observer event (for example saved event on Product model)
as you now model observer events do not fire while using mass update and it's possible my teammates use a mass update (by mistake), then any event does not fire and it breaks the remaining processes
So by these tests, I can be sure that all parts that rely on model observer events work currently.
In laravel testing document mentioned that if you want to assert an event has been dispatched use this code (for example):
public function testOrderShipping()
{
Event::fake();
$order = factory(Order::class)->create();
// Assert an event was dispatched
Event::assertDispatched(OrderCreated::class);
}
Is it possible to assert model observer's event has been fired (dispatched) too?

Difference between "Signals" (js-signals) and "Observables" (mobx, mobx-react)?

Could they work together for a perfect states management and bidirectional data binding?
Mobx implements observable pattern in javascript. By using mobx and mobx-react, people can refer mobx observables in react and assign autorun, reaction, and comptued routines to them. Every time an observable changes its references relationship, autorun, reaction and computed routines fired.
This is really helpful when you developed a rich content application, say editor.
While js-signals works differently, a signal can register callbacks and its priority. When a component changes, a programmer have a choice to dispatch the signal to fire all associated callbacks (just like events)
Which pattern is better, could they work together smoothly?
Background
I am working on an editor which uses signals intensively. I also prefer to use observable patterns to manage states of the editor. My personal feelings, when the observable grows up (just like 200 global variables), it becomes hard to maintain.
I am appreciated for your thoughts. Developers who succeeded in using those techniques are welcomed.
js-signals is just an event emitter library and mobx is just a state/observer libary.
You can simply fire and handle events. as long as the handler wraps the changes of mobx State in a mobx.action. the changes in state are handled properly and react components are updated properly/observer events fired properly:
class Store {
#mobx.observable name = "test"
}
var store = new Store();
//custom object that dispatch a `started` signal
var myObject = {
started : new signals.Signal()
};
function onStarted(name){
mobx.runInAction(() => {
store.name = name;
});
}
myObject.started.add(onStarted); //add listener
mobx.observe(store,"name",change=> {
myObject.started.dispatch(change.name+'x'); //woops now we have an infinite loop!
});
myObject.started.dispatch('foo'); //dispatch signal passing custom parameters
// myObject.started.remove(onStarted); //remove a single listener

Difference between dispatch and emit in Flux/React Native

I'm new in Flux/React Native.
I'm quite confused about dispatch vs emit using in Flux.
What is the main difference between them? And what happen when I use same Action Type in dispatch and emit.
For example:
Dispatcher.dispatch({
actionType: 'ACTION1'
});
SomeStore.emit('ACTION1');
In Flux, events are emitted by the store indicating a change in its state. This 'change' event is listened to by views. This will prompt a view to fetch new state from the store. Mind you, the event never contains payload / information about the new state. It is really just what it reads - an event.
Actions are slightly different. While they are indeed events, they are things that occur in our domain eg., Add item to cart. And they carry a payload that contains information about the action, eg.,
{
id: ‘add-item-to-cart’,
payload: {
cartId: 123,
itemId: 1234,
name: ‘Box of chocolates’,
quantity: 1
}
}
Actions are 'dispatched' from the views and the store(s) responds to the dispatch by possibly changing its state and emitting a 'change' event.
So basically:
A view dispatches an action with a payload (usually due to a user interaction) via the dispatcher
The store (which had previously registered itself with the dispatcher)
is notified of the action and uses the payload to change its state and emit an event.
The view (which had previously registered itself with the store) is notified of the change event which causes it to get the new state from the store and change itself.
So that's the difference. And about the question "use same Action Type in dispatch and emit", it doesn't really make sense, does it?
I suggest you read this blog post - http://blog.andrewray.me/flux-for-stupid-people/ (The title means no offence BTW :))
You already know this, but I'll say it again: A unidirectional data flow is central to the Flux pattern. That means data (not control) always flows in one direction.

Laravel testing without firing cache events

I am using the array cache driver while testing, however I want to disable the Cache Events.
I can do this with
$this->withoutEvents();
I'd rather just stop the one event, however
$this->expectsEvents(Illuminate\Cache\Events\KeyForgotten::class);
will throw an error if the event is not called.
One solution would be a function that on the outside allows an event to fire and hides it but doesn't throw an error if the event doesn't occur.
I think I need to mock the Events Dispatcher like so
$mock = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
$mock->shouldReceive('fire')->andReturnUsing(function ($called) {
$this->firedEvents[] = $called;
});
$this->app->instance('events', $mock);
return $this;
The question would be how to carry on dispatching the non caught events?

Can someone explain callback/event firing

In a previous SO question it was recommended to me to use callback/event firing instead of polling. Can someone explain this in a little more detail, perhaps with references to online tutorials that show how this can be done for Java based web apps.
Thanks.
The definition of a callback from Wikipedia is:
In computer programming, a callback is
executable code that is passed as an
argument to other code. It allows a
lower-level software layer to call a
subroutine (or function) defined in a
higher-level layer.
In it's very basic form a callback could be used like this (pseudocode):
void function Foo()
{
MessageBox.Show("Operation Complete");
}
void function Bar(Method myCallback)
{
//Perform some operation
//When completed execute the callback method
myCallBack().Invoke();
}
static int Main()
{
Bar(Foo); //Pops a message box when Bar is completed
}
Modern languages like Java and c# have a standardized way of doing this and they call it events. An event is simply a special type of property added to a class that contains a list of Delegates / Method Pointers / Callbacks (all three of these things are the same thing. When the event gets "fired" it simply iterates through it's list of callbacks and executes them. These are also referred to as listeners.
Here's an example
public class Button
{
public event Clicked;
void override OnMouseUp()
{
//User has clicked on the button. Let's notify anyone listening to this event.
Clicked(); //Iterates through all the callbacks in it's list and calls Invoke();
}
}
public class MyForm
{
private _Button;
public Constructor()
{
_Button = new Button();
//Different languages provide different ways of registering listeners to events.
// _Button.Clicked += Button_Clicked_Handler;
// _Button.Clicked.AddListener(Button_Clicked_Handler);
}
public void Button_Clicked_Handler()
{
MessageBox.Show("Button Was Clicked");
}
}
In this example the Button class has an event called Clicked. It allows anyone who wants to be notified when is clicked to register a callback method. In this case the "Button_Clicked_Handler" method would be executed by Clicked event.
Eventing/Callback architecture is very handy whenever you need to be notified that something has occurred elsewhere in the program and you have no direct knowledge of when or how this happens.
This greatly simplifies notification. Polling makes it much more difficult because you are responsible for checking every so often whether or not an operation has completed. A simple polling mechanism would be like this:
static void CheckIfDone()
{
while(!Button.IsClicked)
{
//Sleep
}
//Button has been clicked.
}
The problem is that this particular situation would block your existing thread and have to continue checking until Button.IsClicked is true. The nice thing about eventing architecture is that it is asynchronous and let's the Acting Item (button) notify the listener when it is completed instead of the listener having to keep checking,
The difference between polling and callback/event is simple:
Polling: You are asking, continuously or every fixed amount of time, if some condition is meet, for example, if some keyboard key have been pressed.
Callback: You say to some driver, other code or whatever: When something happens (the keyboard have been pressed in our example), call this function, and you pass it what function you want to be called when the event happens. This way, you can "forget" about that event, knowing that it will be handled correctly when it happens.
Callback is when you pass a function/object to be called/notified when something it cares about happens. This is used a lot in UI - A function is passed to a button that is called whenever the button is pressed, for example.
There are two players involved in this scenario. First you have the "observed" which from time to time does things in which other players are interested. These other players are called "observers". The "observed" could be a timer, the "observers" could be tasks, interested in alarm events.
This "pattern" is described in the book "Design Patterns, Elements of Reusable Object-Oriented Software" by Gamma, Helm, Johnson and Vlissides.
Two examples:
The SAX parser to parse XML walks
trough an XML file and raises events
each time an element is encountered.
A listener can listen to these
elements and do something with it.
Swing and AWT are based on this
pattern. When the user moves the
mouse, clicks or types something on
the keyboard, these actions are
converted into events. The UI
components listen to these
events and react to them.
Being notified via an event is almost always preferable to polling, especially if hardware is involved and that event originates from a driver issuing a CPU interrupt. In that case, you're not using ANY cpu at all while you wait for some piece of hardware to complete a task.

Resources