简体   繁体   中英

ZF2 - pass variables to zend build-in helper

I would like to pass variable (that would be service menager) to a build-in helper of zend. Is it possible? To be more clearly:

  1. There is a zend helper called Url, which constructs url's
  2. In this helper I would like to get some data from database, so I need to pass there connection or model (doesn't matter really)
  3. Depends on data get in point 2. I would like to construct my custom link

Well, the thing looks like this: I'm trying to make own custom routing. So in database I have controller, action and it's alias. For example:

 Home\Controller\Home | index | myalias

Routing works fine, that means that if I type url:

 example.com/myalias

Then Zend will open Home controller and index action. But on whole page I have url's made by Zend build-in Url helper, which looks like this:

$this->url('home', array('action' => 'index'));

So link looks:

example.com/home/index

I would like to change link to

example.com/myalias

without changing links generated by Url helper on whole page. So before helper return url, should check if that url have alias, and if so then should return that alias exept regular url.

In Module.php of the module where you have he helper class file, write the following -

//use statements

class Module {
    //public function getAutoloaderConfig() { [...] }

    //public function getConfig() { [...] }

    public function getViewHelperConfig() {
        return array(
            'factories' => array(
                'Url' => function ($sm) {
                    $locator = $sm->getServiceLocator();
                    $viewHelper = new View\Helper\Url;

                    //passing ServiceLocator to Url.php
                    $viewHelper->setServiceLocator($locator);  //service locator is passed.

                    return $viewHelper;
                },
            ),
        );
    }
}

Now in the Url.php, we need a function setServiceLocator() and getServiceLocator() .

//use statements

class Url {

    public $serviceLocator;

    public function getServiceLocator() {
        return $this->serviceLocator;
    }

    public function setServiceLocator($serviceLocator) {
        if($this->serviceLocator == null)
            $this->serviceLocator = $serviceLocator;

        return;
    }

}

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM