Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento router: How can I catch parameters in all URLs?

Think of a small and basic affiliate system. I want an URL like

www.myshop.com/mynewproduct.html?afid=123

Every time afid is found in the URL, a method should be called (basically to save "afid" in the session and when the customer buys stuff, I want to track it).

like image 749
Max Avatar asked Jul 29 '09 07:07

Max


2 Answers

You don't need a router for this. You'll want to setup an event listener that fires for every page load, and then access the variables in the request collection. The controller_front_init_routers event should do.

So, setup your module's config with the following

<global>
    <events>
        <controller_front_init_routers>
            <observers>
                <packagename_modulename_observer>
                    <type>singleton</type>
                    <class>Packagename_Modulename_Model_Observer</class>
                    <method>interceptMethod</method>
                </packagename_modulename_observer>
            </observers>
        </controller_front_init_routers>    
    </events>
</global>

And then create the following class

app/code/local/Packagename/Modulename/Model/Observer.php
class Packagename_Modulename_Model_Observer {
    public function interceptMethod($observer) {
        $request    = $observer->getEvent()->getData('front')->getRequest();
        $afid       = $request->afid;

        //do whatever you want with your variable here
    }
}

The interceptMethod can be named whatever you want.

like image 112
Alan Storm Avatar answered Dec 08 '22 17:12

Alan Storm


I know this is a very old answer, but it is valid to mention we shouldn't use the controller_front_init_routers event if we intend to store those parameters in session, which is the scenario for the original question. For example, if you instantiate customer/session at this point you won't be able to perform a customer login anymore. Alan pointed this himself in http://alanstorm.com/magento_sessions_early. BTW, thanks Alan for this great article.

like image 30
Vinícius Ferraz Avatar answered Dec 08 '22 17:12

Vinícius Ferraz