Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with object Zend\View\Helper\Url, from the controller

sorry for my bad english, i'm from Russia

began to learn zend framework 2... Sample in controller, readAction():

use Zend\View\Helper\Url;

....

$helperUrl = new Url();
$address  = $helperUrl('news', array('action' => 'index'));

As a result, thrown exception:

Zend\View\Exception\RuntimeException

File:
    W:\home\zf2\vendor\zendframework\
       zendframework\library\Zend\View\Helper\Url.php:80
Message:
    No RouteStackInterface instance provided

Please, help me. what I'm doing wrong?

like image 285
Mark Kunts Avatar asked Oct 17 '12 03:10

Mark Kunts


2 Answers

You can't use a viewhelper in a controller - and you don't need to. There's also a Url controller plugin that does pretty much the same.

Controller plugins are invokable classes, you can use them like this (controller's action context):

$url = $this->url()->fromRoute($route, $params, $options, $reuseMatchesParams);

All parameters are optional. For further information, check the code in Zend\Mvc\Controller\Plugin\Url or read the docs.

like image 165
Daniel M Avatar answered Oct 23 '22 04:10

Daniel M


Helpers and plugins, while they can be directly instantiated, usually shouldn't, as they typically are managed by a PluginManager. The PluginManager is a subclass of the ServiceManager, and, as such, provides a lot of functionality around plugin creation, including injection of standard collaborators, usage of factories to provide dependency injection, and more.

In the case of the Url helper, there is a factory that ensures it has the configured router injected -- if you instantiate it directly, you won't have this, and it won't be able to do its job, as you noticed!

As Daniel noted, you also want to make sure you're getting a plugin that's appropriate for the context. If you're in a controller, check to see if there's a controller plugin that will do the job for you. Daniel linked to the docs in his post.

like image 31
weierophinney Avatar answered Oct 23 '22 04:10

weierophinney