我有一个控制台控制器和一个发送电子邮件的动作(在下面的module.config.PHP中定义)
'console' => array( 'router' => array( 'routes' => array( 'cronroute' => array( 'options' => array( 'route' => 'sendEmails','defaults' => array( 'controller' => 'Application\Controller\Console','action' => 'send-emails' ) ) ),) ) ),
在操作中,我想发送一封电子邮件,其中包含指向该网站上其他操作的链接.这通常使用URL View Helper来完成,但由于Request类型是Console而不是HTTP,因此不起作用.我试图创建一个HTTP请求,但我不知道如何给它站点域或Controller / Action链接.
我的控制器代码:
$vhm = $this->getServiceLocator()->get('viewhelpermanager'); $url = $vhm->get('url'); $urlString = $url('communication',array('action' => 'respond','id' => $id,array('force_canonical' => true));
这会引发错误:
====================================================================== The application has thrown an exception! ====================================================================== Zend\Mvc\Router\Exception\RuntimeException Request URI has not been set
如何在具有站点方案,域和路径/到/ action的控制台控制器中创建HTTP请求?我如何将其传递给URL View Helper?
以下是此问题的解决方法:
原文链接:https://www.f2er.com/php/136834.html<?PHP // Module.PHP use Zend\View\Helper\ServerUrl; use Zend\View\Helper\Url as UrlHelper; use Zend\Uri\Http as HttpUri; use Zend\Console\Console; use Zend\ModuleManager\Feature\ViewHelperProviderInterface; class Module implements ViewHelperProviderInterface { public function getViewHelperConfig() { return array( 'factories' => array( 'url' => function ($helperPluginManager) { $serviceLocator = $helperPluginManager->getServiceLocator(); $config = $serviceLocator->get('Config'); $viewHelper = new UrlHelper(); $routerName = Console::isConsole() ? 'HttpRouter' : 'Router'; /** @var \Zend\Mvc\Router\Http\TreeRouteStack $router */ $router = $serviceLocator->get($routerName); if (Console::isConsole()) { $requestUri = new HttpUri(); $requestUri->setHost($config['website']['host']) ->setScheme($config['website']['scheme']); $router->setRequestUri($requestUri); } $viewHelper->setRouter($router); $match = $serviceLocator->get('application') ->getMvcEvent() ->getRouteMatch(); if ($match instanceof RouteMatch) { $viewHelper->setRouteMatch($match); } return $viewHelper; },'serverUrl' => function ($helperPluginManager) { $serviceLocator = $helperPluginManager->getServiceLocator(); $config = $serviceLocator->get('Config'); $serverUrlHelper = new ServerUrl(); if (Console::isConsole()) { $serverUrlHelper->setHost($config['website']['host']) ->setScheme($config['website']['scheme']); } return $serverUrlHelper; },),); } }
当然,您必须在config中定义默认主机和方案值,因为无法在控制台模式下自动检测它们.