Zend Framework Source Code Snippets

BaseUrl view helper

Bookmark and Share
1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
<?php
/**
 * Helper for retrieving base URL
 *
 * @package  * @version $Id: $
 */
class Zend_View_Helper_BaseUrl extends Zend_View_Helper_Abstract
{
    /**     * @var string
     /
    protected $_baseUrl;
 
    /**     * Return base URL of application
     *
     * @return string
     */
    public function baseUrl()    {
        if (null === $this->_baseUrl) {
            if ($baseUrl = Zend_Registry::get('configuration')->app->url) {
                $this->_baseUrl = $baseUrl;
            } else if (isset($this->view->baseUrl)) {                $this->_baseUrl = $this->view->baseUrl;
            } else {
                $request = Zend_Controller_Front::getInstance()->getRequest();
                $this->_baseUrl = $request->getBaseUrl();
            }        }
 
        return $this->_baseUrl;
    }
} 
## Example Usage:
 
<a href="<?php echo $this->baseUrl();?>">Home</a>

Comments

Slim Slim
4 years ago

In my application I'm using thing like this

$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$view->baseUrl = substr($_SERVER['PHP_SELF'], 0, -9);

Usage:
<a href="<?php echo $this->baseUrl; ?>">Home</a>

davedevelopment davedevelopment
4 years ago

You might want to go careful with that, $_SERVER['PHP_SELF'] is potentially unsafe.

<?php echo $this->escape($this->baseUrl);?>

Would be safer

djaarf djaarf
4 years ago

$baseurl = str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname($_SERVER['SCRIPT_FILENAME']));

What do you think?

eztam eztam
3 years ago

I would change a little thing. Instead of reinitializing the protected $_baseUrl everytime you call this helper I would initialize it in the constructor to only return it on call.

You must login before commenting on a snippet. If you do not have an account, please register.

Snippet description

I extend the usual BaseUrl helper by trying to receive an absolute url from my configuration settings, rather than trusting the framework to best guess.

Snippet details

Created:
davedevelopment davedevelopment
4 years ago
Edited:
davedevelopment davedevelopment
4 years ago
Revision Id:
3
Edit Message:
Initial Release
Tags:
view helper base url
Comments:
4
Views:
5378
Points:
1 (1 votes)

History

r3

Initial Release

davedevelopment davedevelopment
4 years ago