Zend Framework 2的基本URL

Foy*_*Vai 4 zend-framework2

我想在Zend Framework 2的控制器中获取基本URL作为img tag的src属性的值传递.我将我的图像放在公共文件夹中.

如何在Zend Framework 2的控制器中获取基本URL

edi*_*igu 10

对于任何视图中的相对 URL,您可以将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
Run Code Online (Sandbox Code Playgroud)

编辑:哦对不起,问题是关于在控制器级别获取该值,而不是查看.在任何控制器中,您都可以这样做:

$helper = $this->getServiceLocator()->get('ViewHelperManager')->get('ServerUrl');
$url = $helper->__invoke('/foo');
// or
$url = $helper('/foo');
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

和控制器上的构造函数签名如下:

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

public function __construct(ServerUrl $helper)
{
    $this->urlHelper = $helper;
}
Run Code Online (Sandbox Code Playgroud)


jml*_*oux 6

您还可以在视图中使用BasePath Helper.

如果它是用于设置src图像的属性,则无需在控制器级别设置它.