2009-12-10 92 views
15

是否有使用Zend框架創建絕對URL的最佳做法?我想知道是否有一些助手,或者如果這只是將$ _SERVER變量中的方案,主機等連接起來,然後添加由Zend生成的相對路徑。使用Zend框架創建絕對URL的最佳實踐?

回答

24

phpfour的方式是確定的,但你必須檢查https://開頭,FTP://和郵寄地址:太... :)

我prefefer有所有URL根絕(/files/js/jquery.js)。該 「鐵桿Zend的方式」 是

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

+1,最好在99%的時間內使用標準方法 - Zend Framework已經爲您提供了這一點。如果您需要手動更改網址庫,您也可以自行將其設置在引導程序中。 – 2009-12-10 18:23:02

+2

echo $ this-> serverUrl()。 $這 - >的baseUrl( 'cassbase.css'); (這是絕對使用zend serverurl視圖助手) – 2011-02-19 18:04:07

+0

$ this-> baseUrl返回一個URL相對於Web服務器的根,如下所述:http://framework.zend.com/manual/en/zend.view.helpers .html#zend.view.helpers.initial.baseurl,TMHO這個答案是錯誤的。 – AsTeR 2012-05-15 20:19:23

0

我不會使用$ _SERVER,我會使用Zend_Controller_Request_Http::getServer($keyName);(或者請求對象上的直接獲取方法,這些方法適用時我忘記了哪些是對象的直接成員,哪些需要使用getServer來訪問) 。從技術上講,這些都是完全相同的值,但IMO更好地使用它的Zend方式,而不是使用原始PHP訪問。但是,把它們放在一起應該可以得到你所需要的東西。這實際上是我爲SSL控制器插件/ url助手做的。

有可能是雖然一個更好的辦法...

2

在我的應用程序,我保持「的baseUrl」在我的應用程序的配置,我賦值給上引導註冊表中。後來我用下面的視圖助手生成的網址:

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

好處:我可以在從一個地方的視圖中的所有網址的任何變化。

希望這會有所幫助。

+2

'Zend_Registry'是相當不必要的。更好的方法是使用'Zend_Controller_Front :: setBaseUrl()'和'Zend_Controller_Front :: getBaseUrl()'。這樣,你也可以使用包含的視圖助手,所以你不必自己推出。 – 2009-12-10 18:29:15

13

沒有MVC

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

或MVC

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

使用下面的方法。

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