我想在Zend Framework 2的控制器中获取基本URL 作为img tag的src属性的值传递。我将我的图像放在公共文件夹中。
如何在Zend Framework 2的控制器中获得基本URL ?
答案 0 :(得分:10)
您可以在绝对网址中使用ServerUrl查看助手,在任何视图中使用相对的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
编辑:哦对不起,问题是关于在控制器级别获取该值,而不是查看。在任何控制器中,您都可以执行此操作:
$helper = $this->getServiceLocator()->get('ViewHelperManager')->get('ServerUrl');
$url = $helper->__invoke('/foo');
// or
$url = $helper('/foo');
Zend Framework 3更新
由于ZF3默认情况下控制器不是ServiceLocatorAware,因此您需要将助手实例注入控制器,最好是使用工厂。
对于新手来说,一个示例工厂可能看起来像:
<?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 :(得分:6)
您还可以在视图中使用BasePath Helper。
如果用于设置图像的src
属性,则无需在控制器级别设置它。