MyUrl view helper for Zend Framework

on December 02, 2008. in Development, Programming. A 2 minute read.

I started writing some boring introduction but I’ll just skip to the point.

The problem

Zend Framework’s built in URL view helper — Zend_View_Helper_Url — is discarding the query string of the URL, thus breaking some links.

Example: If I’m on a page like:

http://project/foo/bar/?param1=value1

and in the bar.phtml I use the Url helper like this:

<?php
<?= $this->url(array('param2' => 'value2')); ?>

I expect this:

http://project/foo/bar/param2/value2/?param1=value1

or something similar to this. This would be just perfect:

http://project/foo/bar/param1/value1/param2/value2

But no, it gives:

http://project/foo/bar/param2/value2/

The solution

After working on several workarounds, currently this is the best one I can think of — take the link that is created by the built-in Url helper and add the query string on that link:

<?php

// Usage:
// <?= $this->myUrl($this->url(array('param2' => 'value2'))); ?>
// Output:
// http://project/controller/action/param2/value2/?param1=value1
class Zend_View_Helper_MyUrl
{
    public function myUrl(&$url, &$toAdd = array())
    {
        $requestUri = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
        $query = parse_url($requestUri, PHP_URL_QUERY);
        if($query == '')
        {
            return $url;
        }
        else if(empty($toAdd))
        {
            return $url . '/?' . $query;
        }
        else
        {
            $toAdd = (array)$toAdd;
            $query = explode("&", $query);

            $add = '/?';

            foreach($toAdd as $addPart)
            {
                foreach($query as $queryPart)
                {
                    if(strpos($queryPart, $addPart) !== False)
                    {
                        $add .= '&' . $queryPart;
                    }
                }
            }
            return $url . $add;
        }
    }
}

The second parameter, $toAdd, should be an array of parameters that we want to add to the URL. Say, if I have a query string like:

?param1=value1&someotherparam=anditsvalue

but want only to add the param1=value1 to the URL, I would pass “param1” as the second parameter. Not passing anything as the second parameter will result in adding the complete query string to the URL.

This is an ugly hack to make ugly links work, but it works. Thoughts?

Cheers!