【问题标题】:How do I set/change content-type headers for an entire Zend Framework Application如何设置/更改整个 Zend 框架应用程序的内容类型标头
【发布时间】:2011-05-07 16:22:04
【问题描述】:

我已经看到了这个问题: Zend Framework how to set headers 而且我知道如何在每个控制器的基础上设置标题。

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

但是我想在我的配置文件中设置内容头,并让它设置我的所有响应以使用该内容类型。是否有一些我错过的内置方法/约定?我会满足于在引导程序中设置一些东西作为第二个最佳选择。

这是在我的配置中:

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

如果有帮助,我正在使用模块和布局(在这种情况下为默认模块)

问候。

【问题讨论】:

    标签: php zend-framework


    【解决方案1】:

    您可以为此编写一个插件,当尚未设置其他内容类型时,它会自动将内容类型设置为默认值。示例:

    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');
            }
        }
    }
    

    【讨论】:

    • 一开始我觉得这个插件的方法有点奇怪,但是试了一下感觉效果不错。谢谢。
    • 谢谢,很高兴听到我能提供帮助。
    【解决方案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');
        }
    }
    

    【讨论】:

      【解决方案3】:

      实际上,如果$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
          );
      

      【讨论】:

        猜你喜欢
        • 2011-02-06
        • 2021-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多