setTranslator上的ZF2致命控制台错误

时间:2015-10-14 08:40:32

标签: php zend-framework2 command-line-interface translation

我的cli控制器为译员抛出了一个错误。

Fatal error: Call to undefined method Zend\Mvc\Router\Console\SimpleRouteStack::setTranslator() in ..

出错的功能

设置路线转换器

public function onPreRoute($e)
{
    $application    = $e->getTarget();
    $serviceManager = $application->getServiceManager();
    $serviceManager->get('router')->setTranslator($serviceManager->get('translator'));
}

通过这个git问题跟踪器,我注意到有一个问题,因为它不兼容。我的问题是,如何防止cli模块尝试设置翻译器,因为它现在抛出致命错误。

Git url:https://github.com/doctrine/DoctrineORMModule/issues/333

由于

1 个答案:

答案 0 :(得分:1)

我遇到过这个问题一次,因为CLI请求路由与标准请求对象不是同一个对象(很明显)

因此Zend\Http\Request不等于Zend\Console\Request

它不是同一个模块,而且,它不是事件相同的结构,如果事件实现相同的接口,则某些方法不存在。

Zend\Http\Request extends AbstractMessage(这个扩展消息) 直接Zend\Console\Request extends Message

你的问题是一个很好的例子,我们也可以谈谈 $request->getUri()也不起作用。

为了防止这种情况发生,我提供的解决方案并不像我想的那样优雅,但却有效。如果有人有更优雅的解决方案,欢迎您分享。

所以解决方案是:

if (php_sapi_name() !== 'cli' && $request->getServer('HTTP_X_FORWARDED_FOR', false)) {

// Your code that not compliant with console routes
}

您也可以使用此条件声明:

 if (!($request instanceof \Zend\Console\Request) and !$request->isXmlHttpRequest()) {
// Your code that not compliant with console routes or ajax calls
}

为了找到这个解决方案,我受到了Zend骨架应用程序的启发。 In their index.php他们这样做了:

if (php_sapi_name() === 'cli-server') {
    $path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
    if (__FILE__ !== $path && is_file($path)) {
        return false;
    }
    unset($path);
}

我刚看到他们在我第一次下载它之后做了一些更改;)

相关问题