我想獲得基地URL在Zend Framework 2的控制器中作爲img tag的src屬性的值傳遞。我把我的圖像放在公共文件夾中。Zend Framework 2的基地網址
我怎樣才能得到基地URL在控制器的Zend Framework 2?
我想獲得基地URL在Zend Framework 2的控制器中作爲img tag的src屬性的值傳遞。我把我的圖像放在公共文件夾中。Zend Framework 2的基地網址
我怎樣才能得到基地URL在控制器的Zend Framework 2?
您可以使用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;
}
您也可以在視圖中使用BasePath Helper。
如果是用於設置圖像的src
屬性,則無需將其設置爲控制器級別。
爲什麼不使用絕對路徑? ''? –
@TimFountain使用完整的網址可能會比較方便,例如,您在不發送圖像的情況下使用貴公司的徽標呈現html郵件。 – SmasherHell