2011-05-07 22 views
4

私は既にこの質問を見てきました: Zend Framework how to set headers と私はコントローラごとにヘッダを設定する方法を知っています。Zend Framework全体のコンテンツタイプヘッダを設定/変更するには

$this->getResponse() ->setHeader('Content-type', 'text/html; charset=utf-8')

しかし私は私の設定ファイル内のコンテンツ・ヘッダーを設定し、それがそのコンテンツタイプを使用するすべての私の応答を設定したいのですが。いくつかのメソッド/コンベンションが組み込まれていますか?私はブートストラップの何かを第2の最良の選択肢として設定するために解決します。

これは私の設定です:

resources.view.doctype = "XHTML1_STRICT" 
resources.view.encoding = "UTF-8" 
resources.view.contentType = "text/html;charset=utf-8" 

と、私はそのすべてのヘルプ(この場合はデフォルトモジュール)場合

よろしくモジュールとレイアウトを使用しています。

答えて

8

他のコンテンツタイプが既に設定されていない場合、自動的にコンテンツタイプをデフォルトに設定するプラグインを作成できます。例:

class YourApp_Controller_Plugin_ContentType extends Zend_Controller_Plugin_Abstract 
{ 
    public function dispatchLoopShutdown() 
    { 
     $response = $this->getResponse(); 
     $http_headers = $response->getHeaders(); 

     /** 
     * Check whether the Content-Type header is defined. 
     */ 
     $content_type_found = false; 
     foreach ($http_headers as $_header) 
     { 
      if ($_header['name'] === 'Content-Type') 
      { 
       $content_type_found = true; 
       break; 
      } 
     } 

     /** 
     * When no Content-Type has been set, set the default text/html; charset=utf-8 
     */ 
     if (!$content_type_found) 
     { 
      $response->setHeader('Content-Type', 'text/html; charset=utf-8'); 
     } 
    } 
} 
+0

最初はプラグインの方法が少し奇妙だと思っていましたが、試してみるとうまくいきました。ありがとう。 –

+0

おかげさまで、私が手伝ってくれたことをうれしく思います。 –

2

ヘッダーがすでに設定されているかどうかを確認する必要はありません。 setHeader()は、デフォルトで、置き換えずに同じ名前の既存のヘッダーを残します。

class YourApp_Controller_Plugin_ContentType extends Zend_Controller_Plugin_Abstract 
{ 
    public function dispatchLoopShutdown() 
    { 
     $response = $this->getResponse(); 

     /** 
     * When no Content-Type has been set, set the default text/html; charset=utf-8 
     */ 
     $response->setHeader('Content-Type', 'text/html; charset=utf-8'); 
    } 
} 
1

実は、$replace === false場合は、すでに存在している場合でも、Zendのは、(デフォルトで)ヘッダを追加すると、あなたは、重複するヘッダー名を持つことになります。

if ($replace) { 
     foreach ($this->_headers as $key => $header) { 
      if ($name == $header['name']) { 
       unset($this->_headers[$key]); 
      } 
     } 
    } 

    $this->_headers[] = array(
     'name' => $name, 
     'value' => $value, 
     'replace' => $replace 
    );