在Zf2中的Module.php文件中查找BaseUrl

时间:2014-07-09 10:07:47

标签: zend-framework2 base-url

我需要在module.php文件或服务文件中找到baseUrl。早些时候,我正在使用

                $event = $this->getEvent();
                $request = $event->getRequest();
                $router = $event->getRouter();
                $uri = $router->getRequestUri();
                $baseUrl = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(), $request- >getBaseUrl());

但是,我才知道这只会在Controller的Action方法中运行。我如何在其他地方获得baseUrl?

1 个答案:

答案 0 :(得分:0)

Module.php -

中试试
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e) {

        $e->getApplication()
            ->getEventManager()
            ->getSharedManager()
            ->attach('*', 'route', array($this, 'some_function_name'));
    }

    public function some_function_name(MvcEvent $e) {
        $request = $e->getRequest();
        $router = $e->getRouter();
        $uri = $router->getRequestUri();
        $baseUrl = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(),       $request->getBaseUrl());

        //[...some other code ... ]
    }

    //[...some other code ... ]
}