Using HTTP routes within ZF2 console application

2019-07-18 19:55发布

问题:

I'm trying to write a console action to regenerate the XML sitemap for my application. ZF2 is detecting that I'm running the CLI version of PHP and is thus using console routing, but it then chokes with a "Route with name 'xxx' not found" when Zend Navigation tries to build the sitemap, because it doesn't know about any of the named HTTP routes. The same code works perfectly fine when used through the normal HTTP controller.

Is there a way to make HTTP routes work within a console application?

回答1:

The "router" will be a cli or http router based on your request. However, if you load the HttpRouter in the service manager, you get explicitly the router for http requests. Then you have to make sure this router is injected in the navigation, instead of the default (thus, cli) one.

The problem is the navigation builder is very badly constructed. Thus, you have to hack around this. I assume here you generate this XML inside a controller:

public function generateAction()
{
    $event  = $this->getEvent();
    $http   = $this->getServiceLocator()->get('HttpRouter);
    $router = $event->getRouter();

    $event->setRouter($http);

    // Get your navigation here
    // Build your XML here

    $event->setRouter($router);
}