开发者

How do I set/change content-type headers for an entire Zend Framework Application

I've already seen this question: Zend Framework how to set headers and I am aware of how to set headers on a per controller basis.

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

However i'd like to set the content-header in my config file and have it set all my responses to use that content type. Is there some built in method/convention I'm missing out on? I'll settle for setting something in the bootstrap as 2nd best choice.

This is in my config:

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

and I'm using 开发者_如何学运维modules and layouts if its any help (default module in this case)

Regards.


You can write a plugin for this which automatically sets the content-type to a default when no other content-types have been set already. Example:

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


There is no need for checking if the header was already set. Since setHeader() will by default leave existing header with the same name without replacing.

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


Actually, if $replace === false, Zend will add (by default) the header even if already exists and you will have duplicate header names.

    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
    );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜