I needed to load javascript files on a per controller basis in a Zend Framework (ZF) based project. In the past I would have done this with some conditional logic that would load things based on a page number or name or some such. In ZF all that is needed is to stick some code in the controller’s init method, a line in the layout header and we are good to go.
Here is the code to stick in your controller:
public function init()
{
$this->view->headScript()->appendFile('/mysite/public/js/somefile.js')
->appendFile('/mysite/public/js/someother.js');
}
Here is the line you stick in the layout.phtml header:
echo $this->headScript();
That’s it! Now you can have controller specific js loaded and keep your sites code overhead under control by keeping uneeded js files out of your layout.phtml.






#1 by Helmut on July 23, 2010 - 11:44 am
As this might work for 2 or 3 controllers, what happens when you have a few tenths or hundredths of controllers? The probability of introducing errors might be greater than using the logic to find the user’s location.
#2 by Stuart on July 23, 2010 - 11:56 am
Hi Helmut, thanks for the input. How do you see this happening? It seems to me that the chance of error is equal either way. This method keeps the javascript that is specific to a certain controller paired only with that controller. Makes it easier to maintain and control and keeps the layout template cleaner.
One possible solution, though, might be to create an action helper that does the conditional checking for you and then include that action helper in the init.
#3 by Helmut on July 23, 2010 - 12:08 pm
Hey Stuart,
What I meant is say you have 60 controllers them all share the same configuration in the header but then you have to make a change to them because a JS file has been moved to a different area or has been deleted. Now you have to go through all 60 controllers to make the change and make sure it is done properly not making a mistake.
But I guess if you make Abstract controllers with specific settings that then can be extended that would be “better”?
#4 by Stuart on July 23, 2010 - 12:13 pm
Ahh… I see. Abstract controller would be one solution. Perhaps an action helper that handles such checking would be useful, though perhaps less robust?
#5 by Helmut on July 23, 2010 - 12:29 pm
Yeah, I guess I was thinking on the long run but in any case your recommendation is excellent.
#6 by Stuart on July 23, 2010 - 1:02 pm
Cool. At first I was wondering what you meant but after thinking about it I realized your point is a good one. Now, because of thinking about it, I have another approach to use should such a situation arise. Thanks, Helmut!