4

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.

Liyali
  • 5,643
  • 2
  • 26
  • 40
Mouna Cheikhna
  • 38,870
  • 10
  • 48
  • 69

2 Answers2

5

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.

Liyali
  • 5,643
  • 2
  • 26
  • 40
1

You can create new class and extend Zend_Controller_Action then extend your newly created class not Zend_Controller_Action

example:

class CommonactionsController 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
}

and then:

class FirstController extends CommonactionsController {
    // here you can use all your common actions...
}

second controller..

class SecondController extends CommonactionsController {
    // here you can use all your common actions...
}

and so on...

Vytautas
  • 3,509
  • 1
  • 27
  • 43
  • I would recommand this method for new behaviors that must be implemented in every controllers, like making the controllers aware of a dependency injection container, otherwise I would rely on either action helpers or controller plugins – JF Dion Apr 20 '12 at 15:09
  • 3
    I would recommend @Liyali's solution over this one. I'm not saying this is bad, but the other is better. Just my opinion :). The reason being he mentions a big chunk of code which will need to be loaded for every controller, although it is needed in only two. An action helper is loaded only when needed. – vascowhite Apr 20 '12 at 17:05