Base Url of Zend Framework 2

2020-02-06 08:49发布

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 ??

2条回答
Rolldiameter
2楼-- · 2020-02-06 09:22

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;
}
查看更多
Evening l夕情丶
3楼-- · 2020-02-06 09:24

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.

查看更多
登录 后发表回答