有有幾種方法可以使用ZF微型工具完成這項工作。
ZF中有一些類似的視圖助手像CodeIgniter那樣。您可以將它們用於視圖腳本和佈局模板中。
讓我們開始使用您的模塊的module.config.php
。您可以按如下
'view_manager' => [
'base_path' => 'http://www.yoursite.com/',
]
下view_manager
鍵設置base_path
鍵現在,如果您使用以下視圖助手
echo $this->basePath();
// Outputs http://www.yoursite.com/
如果您使用以下一個
echo $this->basePath('css/style.css');
// Outputs http://www.yoursite.com/css/style.css
但是,如果你不使用上述配置
echo $this->basePath('css/style.css');
// Outputs css/style.css
由於@tasmaniski說約$this->serverUrl();
你也可以在視圖腳本中使用它。這個好東西不需要像$this->basePath()
任何配置,如果你在ZF的控制器動作需要該。做到這一點的控制器動作最簡單的方法是
public function indexAction()
{
$uri = $this->getRequest()->getUri();
$baseUrl = sprintf('%s://%s/', $uri->getScheme(), $uri->getHost());
// Use this $baseUrl for your needs
// Outputs http://www.yoursite.com/
}
否則,你可以得到它下面的方式,但這個工程一樣$this->basePath()
public function indexAction()
{
// This is for zf2
$renderer = $this->getServiceLocator->get('Zend\View\Renderer\RendererInterface');
// This is for zf3
// Assuming $this->serviceManager is an instance of ServiceManager
$renderer = $this->serviceManager->get('Zend\View\Renderer\RendererInterface');
$baseUrl = $renderer->basePath('/uri');
// Use this $baseUrl for your needs
// Outputs http://www.yoursite.com/uri
}
此外,還有兩個功能,可以是在控制器操作的不同條件下使用。如果使用重寫規則,那些將返回空字符串。這些是
$this->getRequest()->getBaseUrl();
$this->getRequest()->getBasePath();
這些都不像你所期望的那樣工作。必須參考issue知道這是爲什麼!
部分它適用於我,在服務器端它的罰款,但在本地主機,其服務器的URL到本地主機不localhost/my_app ..我怎麼能理解這一點。所以接受你的答案作爲我的解決方案。 –