magento中生成https链接的简单方法

来源:互联网 发布:淘宝图片很不清楚 编辑:程序博客网 时间:2024/04/30 14:23

有关magento中https的基础知识,请看 《magento中的启用https》

如果是在项目的后期才决定采用https,那么就要面临一个问题:大量的生成url的代码需要修改,这是一个很大的工作量。


我们先来总结一下magento下生成url的方法:

1. 从全局上看,有两个方法:

Mage::getUrl('xx/xxx/xxxx'  , array( '_secure' => true ))Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_LINK, true )


其中Mage::getUrl()如下:

    public static function getUrl($route = '', $params = array())    {        return self::getModel('core/url')->getUrl($route, $params);    }



2. 在controller中,有redirect方法:

    protected function _redirect($path, $arguments=array())    {        $this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));        return $this;    }

3. 在template中,有 getUrl 方法:

    /**     * Returns url model class name     *     * @return string     */    protected function _getUrlModelClass()    {        return 'core/url';    }    /**     * Create and return url object     *     * @return Mage_Core_Model_Url     */    protected function _getUrlModel()    {        return Mage::getModel($this->_getUrlModelClass());    }    /**     * Generate url by route and parameters     *     * @param   string $route     * @param   array $params     * @return  string     */    public function getUrl($route = '', $params = array())    {        return $this->_getUrlModel()->getUrl($route, $params);    }

        由以上的1,2,3点可知,系统在生成url的方法绝大多数是调用Mage_Core_Model_Url::getUrl() 方法( 其中Mage::getBaseUrl()没法rewrite,只能一个个改,如果开发中允许覆盖核心代码的话,那就直接修改getBaseUrl ), 于是我们能得到一个简便的方法就是重写Mage_Core_Model_Url::getUrl() ,把使用https参数加进来,重写后的方法如下:


   /**     * Build url by requested path and parameters     *     * @param   string|null $routePath     * @param   array|null $routeParams     * @return  string     */    public function getUrl($routePath = null, $routeParams = null)    {        /*         use https         if url show in web browser start with https, all urls in the webpage must be start with https,         for example: if main page is https, but ajax request send in this page is http, then ajax request will fail                      if main page is http, but ajax request send in this page is https, then ajax request will fail also                    *///use httpsif( isset($_SERVER['SERVER_PORT']) && 443==$_SERVER['SERVER_PORT'] ){    //if it has set $routeParams,then add  '_secure' => true    if( is_array($routeParams) ){if( !isset($routeParams['_secure']) ){$routeParams['_secure']=true;}    }else{       //set $routeParams to use https$routeParams=array('_secure'=>true);    }}             return parent::getUrl($routePath,$routeParams);          }





这个功能已变成开源module,地址 https://github.com/newjueqi/usehttps

模块就是为了解决同一个页面中混杂着http和https的问题,特别是使用ajax时,如果当前的url是https,但request的url是http,那么ajax请求会失败。
如果当前页面是http,那么ajax的请求必须是http。
如果当前页面是https,那么ajax的请求必须是https。



【文章作者】曾健生

【作者邮箱】zengjiansheng1@126.com

【作者QQ】190678908

【作者博客】blog.csdn.net/newjueqi




原创粉丝点击