Quick-n-dirty client (browser) caching via http headers

Hi,

I wanted the ability to control the client (browser) caching of pages on my site, this functionality doesn’t seem to be included in Yii so I wrote a quick-n-dirty solution for doing so by extending the base controller…


class Controller extends CController

{


...

	private $headers=null;


	/**

	 * Sets a client cache time in minutes by sending the correct HTTP headers

	 *

	 * @param integer $mins to cache, default 60 minutes

	 */

	public function setPageCacheable($mins = 60)

	{

		$secs = $mins * 60;

		$this->headers = array(

			'Pragma' => '',

			'Expires' => gmdate('D, d M Y H:i:s', time() + $secs) . ' GMT',

			'Cache-Control' => "max-age={$secs}, public, s-maxage={$secs}",

		);

	}


	public function afterRender($view, &$output)

	{

		if(!empty($this->headers))

		{

			foreach ($this->headers as $k => $v)

			{

				if(empty($v))

				{

					header_remove("$k");

				}

				else

				{

					header("$k: $v");

				}

			}


		}

		parent::afterRender($view, $output);

	}

...


}



Usage example:




...

	/**

	 * Displays the About page

	 */

	public function actionAbout()

	{

		// Set this page to client cacheable, default is 60 minutes

		$this->setPageCacheable();


		$this->render('about');

	}

...



PS. The inspiration for this came from mtHeader by mintao which is a much more complete header management solution if that’s what you need…