Search code examples
zend-frameworkzend-controller

Zend Framework - How can i share common code between some of a controller's actions?


To keep my controllers as DRY as possible i need to share some common code (a big chunk of code) between say 2 of my controller's actions and not all of them and i need access variables in this shared code in my actions.

For example:

class FirstController extends Zend_Controller_Action {

   public function firstAction() {
     //common code here: contains an array $columns 
   } 
   public function secondAction() { 
       //common code here: contains an array $columns also 

   } 

   //other actions
}

so how can I refactor this to put the common code in one place and be able to access $columns and in firstAction() and secondAction().

Thanks.


Solution

  • I don't recommend you to use a base controller. It's overkilling and heavy for such a small task. Since you want to share common code within one controller, use instead an action helper and a class attribute $columns that you can send as argument to your action helper.

    Read more about action helpers here.

    Action Helpers allow developers to inject runtime and/or on-demand functionality into any Action Controllers that extend Zend_Controller_Action. Action Helpers aim to minimize the necessity to extend the abstract Action Controller in order to inject common Action Controller functionality.