Zend Framework URL View Helper
I've been working with Zend Framework a lot lately, which is one reason for the drought in posting, and have kept running into a recurring uncertainty using the URL view helper. The URL view helper included with the Zend Framework is a little confusing at random times for me so in the hopes of making sense out of everything long term the below is a brief outline of how the Zend Framework URL view helper works and what not.
The Zend Framework URL view helper is used to render a URL that follows the rules setup using the Zend Route module. This is nice because you can change the routes defined for your application and not have to worry about how your URLs are structured.
The basic syntax is below:
<?php $this->url(array $urlOptions = array(), $name = null, $reset = false, $encode = true); ?>
Using the above for a template below is an example of the usage and output:
<?php //outputs /a/b/c/ echo $this->url(array('module' => 'a','controller'=>'b','action'=>'c'), null, FALSE); ?>
As you can see the URL view helper outputs a simple URL to the module "a", controller "b" and the action "c".
Things get a little trickier when you want to pass along some variables though. By default the above example will append any existing variables, that are outside of the MVC paradigm, onto any new URLs created. For example, if the page url is the below:
/* /a/b/c/foo/4/bar/yes */
And you call the below call to the URL view helper:
<?php echo $this->url(array('module' => 'a2','controller'=>'b2','action'=>'c2'), null, FALSE); ?>
You'll get the below:
/* /a2/b2/c2/foo/4/bar/yes */
When I first ran into this issue I was flummoxed. It was kind of a problem (to put it mildly). To get around this you have to set the "reset" value to TRUE. Doing so will keep any existing query variables out of your URL.
To add fresh variables to the URL view helper you use the below syntax:
<?php //outputs /a2/b2/c2/bar/yes echo $this->url(array('module' => 'a2','controller'=>'b2','action'=>'c2','bar'=>'yes'), null, TRUE); ?>
That will, hopefully, keep you from making the same mistake and the subsequent head bashing that would be sure to ensue.