2014-02-27 36 views
4

我想獲得基地URL在Zend Framework 2的控制器中作爲img tag的src屬性的值傳遞。我把我的圖像放在公共文件夾中。Zend Framework 2的基地網址

我怎樣才能得到基地URL在控制器的Zend Framework 2?

+1

爲什麼不使用絕對路徑? ''? –

+0

@TimFountain使用完整的網址可能會比較方便,例如,您在不發送圖像的情況下使用貴公司的徽標呈現html郵件。 – SmasherHell

回答

10

您可以使用ServerUrl視圖助手絕對的URL和BasePath相對那些在任何視圖。

$this->serverUrl();    // output: http://your.domain.com 
$this->serverUrl('/foo');  // output: http://your.domain.com/foo 
$this->basePath();    // output:/
$this->basePath('img/bar.png'); // output: /img/bar.png 

編輯:噢,對不起,問題是關於得到的控制器水平值,無法查看。在任何控制器,你可以這樣做:由於控制器不ServiceLocatorAware默認情況下ZF3爲Zend框架3

$helper = $this->getServiceLocator()->get('ViewHelperManager')->get('ServerUrl'); 
$url = $helper->__invoke('/foo'); 
// or 
$url = $helper('/foo'); 

更新,需要助手的實例注入到控制器,最好使用廠。

新秀,一個例子工廠可能看起來像:

<?php 
namespace Application\Controller\Factory; 

use Interop\Container\ContainerInterface; 
use Zend\ServiceManager\Factory\FactoryInterface; 

class ExampleActionFactory implements FactoryInterface 
{ 
    /** 
    * Factories are invokable 
    * 
    * @param ContainerInterface $dic 
    * @param string    $requestedName 
    * @param array|null   $options 
    * 
    * @throws \Psr\Container\ContainerExceptionInterface 
    * 
    * @return ExampleAction 
    */ 
    public function __invoke(ContainerInterface $dic, $requestedName, array $options = null) 
    { 
     $helper = $dic->get('ViewHelperManager')->get('ServerUrl'); 

     return new ExampleAction($helper); 
    } 
} 

和控制器像一個構造函數簽名:

/** 
* @var ServerUrl 
*/ 
private $urlHelper; 

public function __construct(ServerUrl $helper) 
{ 
    $this->urlHelper = $helper; 
} 
+1

這個問題是有效地獲得baseUrl控制器,但它確實是一個更好的做法,在視圖中使用它。 – jmleroux

+0

不錯的一個。自從使用ZF2以來一直使用ZF2,甚至不知道這個幫手。始終以連接協議和主機名結束。 – Andris

+1

感謝您更新您關於ZF3的問題 – evilReiko

6

您也可以在視圖中使用BasePath Helper

如果是用於設置圖像的src屬性,則無需將其設置爲控制器級別。