Base Url of Zend Framework 2

拜拜、爱过 提交于 2019-12-17 20:59:09

问题


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.

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


回答1:


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

Edit: 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');

Update for Zend Framework 3

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



回答2:


You can also use BasePath Helper in your view.

And if it is for setting the src attribute of an image, no need to set it at controller level.



来源:https://stackoverflow.com/questions/22079460/base-url-of-zend-framework-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!