Add events for before/after a action of a controll

2019-02-03 09:45发布

问题:

I have a controller in Magento as below:

#File: ./app/local/FilFact/Test/IndexController
class FilFact_Test_IndexController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        $this->_testConfig();
    }
}

I need to add two events for:
before index action
after index action

How could I do that?

回答1:

This is simple as the Mage_Core_Controller_Varien_Action base class provides pre/post dispatch events.

If you open up the Mage_Core_Controller_Varien_Action class you find two methods: preDispatch() and postDispatch()

These method perform a few tasks and most importantly fire off three events.

controller_action_(pre|post)dispatch
controller_action_(pre|post)dispatch_{{routeName}}
controller_action_(pre|post)dispatch_{{fullActionName}}

The fullActionName is the route name, the controller name, and the action name separated by '_' and all lower case. (See Mage_Core_Controller_Varien_Action::getFullActionName for reference)

/app/code/local/FilFact/Test/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <FilFact_Test>
            <version>1.0.0</version>
        <FilFact_Test>
    </modules>
    <global>
        <models>
            <FilFact_Test>
                <class>FilFact_Test_Model</class>
            </FilFact_Test>
        </models>
    </global>
    <frontend>
        <routers>
            <filfact>
                <use>standard</use>
                <args>
                    <module>FilFact_Test</module>
                    <frontName>filfact</frontName>
                </args>
            </filfact>
        </routers>
        <events>
            <controller_action_predispatch_filfact_index_index>
                <observers>
                    <FilFact_Test>
                        <class>FilFact_Test/Observer</class>
                        <method>indexPreDispatch</method>
                    </FilFact_Test>
                </observers>
            </controller_action_predispatch_filfact_index_index>
            <controller_action_postdispatch_filfact_index_index>
                <observers>
                    <FilFact_Test>
                        <class>FilFact_Test/Observer</class>
                        <method>indexPostDispatch</method>
                    </FilFact_Test>
                </observers>
            </controller_action_postdispatch_filfact_index_index>
        </events>
    </frontend>
</config>

/app/code/local/FilFact/Test/Model/Observer.php

<?php
class FilFact_Test_Model_Observer
{
    public function indexPreDispatch(Varien_Event_Observer $observer)
    {
       // TODO: Your code
    }

    public function indexPostDispatch(Varien_Event_Observer $observer)
    {
       // TODO: Your code
    }
}