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 ??
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With