因为这是通过 CLI 运行的,所以脚本无法知道正确的域来生成绝对 URI。
我最终在 module/Application/src/Application/View/Helper/CliDomain.php
创建了一个视图助手
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class CliDomain extends AbstractHelper {
protected $_config_protocol;
protected $_config_domain;
public function __construct(array $cliConfig) {
$this->_config_protocol = $cliConfig['scheme'];
$this->_config_domain = $cliConfig['domain'];
}
public function __invoke() {
return $this->_config_protocol.'://'.$this->_config_domain;
}
}
并在module/Application/config/module.config.php
中配置工厂
return array(
...
'view_helpers' => array(
...
'cliDomain' => function ($sm) {
$config = $sm->getServiceLocator()->get('config');
if (!isset($config['cli_url'])) {
throw new \InvalidArgumentException('Please add a "cli_url" configuration to your project in order for cron tasks to generate emails with absolute URIs');
}
return new \Application\View\Helper\CliDomain($config['cli_url']);
},
在项目的 config/autoload/global.php 文件中,我向返回的数组添加了一个新键
<?php
return array(
...
'cli_config' => array(
'scheme' => 'http',
'domain' => 'prod.example.com',
),
);
对于登台服务器,我在 config/autoload/local.php
中添加了一个匹配的配置条目
<?php
return array(
...
'cli_config' => array(
'scheme' => 'http',
'domain' => 'staging.example.com',
),
);
因此,在问题的视图脚本中,我只是在 URL 中添加了对帮助程序的调用,而不必费心强制规范。
<a href="<?php echo $this->cliDomain() . $this->url('some-route'); ?>">a link!</a>