Creating URL in Zend Customer View Helper
This may seem simple, but I was banging my head trying to create a URL in a custom view helper in Zend Framework. I have routing setup which gets the module from the sub-domain in use so I couldn’t use a simple hardcoded URL.
Basically but invoking an instance of the front controller its possible to grab the router and assemble a url. Assemble is the function used in the view helper. The URL is built up from an array of module, controller, action, etc, followed by a second parameter of the route to use. The code is as follows:
<?php /** * View helper which returns link category URL * * @author Lloyd Watkin* @since 25/01/2010 * @package ViewHelper * @subpackage LinksUrl */ class Pro_View_Helper_LinksUrl extends Zend_View_Helper_Abstract { /** * Returns link category URL * * @param Doctrine_Record $category * @param string $module * @param string $controller * @param string $action * @return string Url */ public function linksUrl($category, $module = 'www', $controller = 'links', $action = 'index') { $router = Zend_Controller_Front::getInstance()->getRouter(); return $router->assemble(array( 'module' => $module, 'controller' => $controller, 'action' => $action, 'category' => "{$category->id}-{$category->name}", ), 'www-index'); } }
Another way to do this is to invoke Zend_View_Helper_Url itself and call the Url method (if you want to use the helper itself). This can be done by using the following code:
<?php /** * View helper which returns link category URL * * @author Lloyd Watkin* @since 25/01/2010 * @package ViewHelper * @subpackage LinksUrl */ class Pro_View_Helper_LinksUrl extends Zend_View_Helper_Abstract { /** * Returns link category URL * * @param Doctrine_Record $category * @param string $module * @param string $controller * @param string $action * @return string Url */ public function linksUrl($category, $module = 'www', $controller = 'links', $action = 'index') { $link = new Zend_View_Helper_Url(); return $link->url(array( 'module' => $module, 'controller' => $controller, 'action' => $action, 'category' => "{$category->id}-{$slug}", ), 'www-index'); } }
Both almost identical. Not a hard thing to do in the framework but can catch you out ;)











































