views:

51

answers:

2

Hello Experts,

I want to call a method before the execution of every and each controller's method. I don't want to go and call the method in every method. I just want to call it from one place and it will be called before any method of any controller in magento.

And I am sure we can do this but I don't know how it can be accomplished.

Please provide your suggestions.

Hope we can resolve this or may some expert guys already resolved this.

Thanks.

A: 

You have to create a method called preDispatch in your controller. This method is executed before the requested controller action.

something like:

public function preDispatch()
    {
        parent::preDispatch();

        //my code here
    }
Anda B
That will only execute prior to your own controller's code, not every controller as the OP asked
Jonathan Day
Oh yes, you're right, I didn't read the question very well.
Anda B
+3  A: 

You need to create an Observer that binds to the controller_action_predispatch Event. That will fire before every controller in the Magento codebase. There's a useful wiki page here that walks you through the process.

Jonathan Day
Thank you for your reply. I gone through the wiki page and I got that I have to to create observer for all modules( like customer,checkout,review etc.). Am I going in right direction or Is there any other way?
Shakti Singh
You only need to create the Observer once. That's the advantage of using the `controller_action_predispatch` event, it is thrown by *every* controller. Most events are specific to customer, checkout, review, etc but `controller_action_predispatch` is global.
Jonathan Day
did this work for you? Feel free to accept the answer if it did...
Jonathan Day
Hi Jonathan, Yes I am trying to implement this. I think it should work. Thanks
Shakti Singh