Best practice to create absolute URLs with Zend framework?

徘徊边缘 提交于 2019-12-20 09:37:42

问题


Is there a best practice for creating absolute URLs using the Zend framework? I wonder if there is some helper or if this would just be concatenating the scheme, host, etc. from the $_SERVER variable and then add the relative path generated by Zend.


回答1:


phpfour's way is OK, but you have to check for https://, ftp:// and mailto: too... :)

I prefefer having all urls root-absolute (/files/js/jquery.js). The "hardcore zend way" is

<?php 
// document root for example.com is in /htdocs 
// but application's index.php resides in /htdocs/myapp/public
echo $this->baseUrl('css/base.css'); 
//will return /myapp/public/css/base.css

echo $this->serverUrl() . $this->baseUrl('css/base.css');
//will return http://www.example.com/myapp/public/css/base.css

echo '//' . $this->getHelper('ServerUrl')->getHost() . $this->baseUrl('css/base.css');
//will return protocol relative URL //www.example.com/myapp/public/css/base.css



回答2:


Without mvc

echo $this->serverUrl() . $this->baseUrl('cass/base.css');

or with mvc

echo  $this->serverUrl() . $this->url(array('controller'=>'index','action'=>'index'),null,true);



回答3:


In my applications, I keep a "baseUrl" in my application config and I assign that to registry on bootstrapping. Later I use the following View Helper to generate the URL:

<?php

class Zend_View_Helper_UrlMap
{
    public function UrlMap($original)
    {
        $newUrl  = $original;
        $baseUrl = Zend_Registry::get('baseUrl');

        if (strpos($newUrl, "http://") === false) {
            $newUrl = $baseUrl . $newUrl;
        }

        return $newUrl;
    }
}

Benefit: I can make any change on all the URLs in the view from one place.

Hope this helps.




回答4:


I wouldnt use $_SERVER, I would use the values from Zend_Controller_Request_Http::getServer($keyName); (or the direct getters on the request object when that applies - i forget which ones are direct members of the object and which ones need to be accessed with getServer). Technically these are the exact same values, but IMO its better access it the Zend way than to use the raw PHP access. But yes catting those together should get you what you need. This is actually the way i did it for an SSL controller plugin/url helper.

There could be a better way though...




回答5:


Use the below method.

<a href="<?php echo $this->serverUrl() . $this->url('application', ['action' => 'detail']) ?>">



来源:https://stackoverflow.com/questions/1881254/best-practice-to-create-absolute-urls-with-zend-framework

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