Zend Framework 2 的基本 URL [英] Base Url of Zend Framework 2

查看:24
本文介绍了Zend Framework 2 的基本 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to get Base URL in controller of Zend Framework 2 to pass as value of src attributes of img tag.I put my image in public folder.

如何在 Zend Framework 2 的控制器中获取 Base URL ?

How can I get Base URL in controller of Zend Framework 2 ??

推荐答案

您可以使用 ServerUrl 查看绝对 URL 和BasePath 用于任何视图中的相对.

You can use ServerUrl view helper for absolute URL's and BasePath for the relative ones in any view.

$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

抱歉,问题是在控制器级别而不是视图中获取该值.在任何控制器中,您都可以这样做:

Oh sorry, question was about getting that value in controller level, not view. In any controller you can do this:

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

Zend Framework 3 的更新

由于控制器在 ZF3 中默认不是 ServiceLocatorAware,您需要将帮助程序实例注入您的控制器,最好使用工厂.

Since controllers are not ServiceLocatorAware by default in ZF3, you need to inject the helper instance to your controller, preferably using a factory.

对于新手,示例工厂可能如下所示:

For rookies, an example factory may look like:

<?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);
    }
}

以及控制器上的构造函数签名,例如:

and a constructor signature on controller something like:

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

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

这篇关于Zend Framework 2 的基本 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆