Content with Style

Web Technique

Controller separation with ActionStack and Zend_Layout

by Pascal Opitz on November 6 2008, 22:47

Thinking about my past projects, I realized that previously my controllers where doing way too much that they shouldn't, and quickly the comments controller would update user content and so on. I had a good look at how I wanted to structure my code, and decided that the controllers only should do things that belong to them, but call other controllers if they needed stuff from them.

A Built In Solution

The Zend view renderer actually gives you a mechanism for this. In every action you can set the response segment that you are targeting. In combination with the action stack helper, this enables you to call all the actions that you need and then output all the response segments you have created where you'd need them within the layout, separating bits of markup into single actions.

Let's have a look at a code example:

class FooController extends BaseController {
 public function indexAction() {
 $this->_helper->actionStack('list', 'foo');
 $this->_helper->actionStack('foo', 'bar');
 $this->_helper->actionStack('bar', 'bar');

 public function listAction() {

class BarController extends BaseController
 public function fooAction() {

 public function barAction() {

Then in the layout:

 echo $this->layout()->bar; 
 echo $this->layout()->foo; 
 echo $this->layout()->list; 

Further Reading


  • With the same problem, cakePHP seems to suggest to pull data by calling methods in other controllers, such as function indexAction() {   //do index stuff   $bar_data=$this->requestAction(\'/controller/method/\');   $this->set(\'data\', $bar_data); } That seems to give you the same tools, although more opportunity for further using this data in the controller. Downside is, from what I can see, it\'s another invitation to not writing clean code by pulling information from everywhere and putting it into one large array for the view here, and different ones there. With your way you seem to be limited to working of different data sources in the view.

    by Matthias Willerich on November 10 2008, 22:36 #

  • One question that I would ask myself: Should I be working with, what\'s essentialy meant to be output, further down the line in the controller? Personally I could imagine that it can be confusing if the view script spits out something, and then it gets processed massively.

    by Pascal Opitz on November 11 2008, 08:39 #