5

I need constructor or init function that can be run for my custom module. I need to call it every time when request made to my module's controller in magento.

3 Answers 3

6

You can add following function to use your logic to your custom module's controller:

   protected function _construct()
    {
        // your logic of construct
    }

I hope this will help

4

Magento already has this. You can use _construct if you want your logic when the controller is instantiated or you can use preDispatch that is called when an action is called.
Just make sure that your controller extends Mage_Core_Controller_Front_Action if it's a frontend controller or Mage_Adminhtml_Controller_Action if it's an admin controller.

0

Kamesh Jungi's answer is correct for both Magento 1 and Magento 2, but it is vitally important to be careful to use the Magento single-underscore pseudo constructor:

protected function _construct() // Note SINGLE underscore
{
    // Your fine code
}

The framework invokes this pseudo-constructor, and it does not override the native PHP constructors in base classes.

You must also ensure that your Controller class extends the Magento Controller. Marius' answer is applicable to Magento 1 (e.g. Mage_Adminhtml_Controller_Action for admin controllers), for Magento 2 it would be Magento\Backend\App\Action.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.