kohana为静态文件提供缓存机制

静态文件指的是: css/js/images

1. 匹配静态文件的方法

// classes/controller/base.php
class Controller_Base extends Controller {
        // match static media files
	public function action_media()
	{
		// Generate and check the ETag for this file
		$this->request->check_cache(sha1($this->request->uri));


		// Get the file path from the request
		$file = $this->request->param('file');


		// Find the file extension
		$ext = pathinfo($file, PATHINFO_EXTENSION);


		// Remove the extension from the filename
		$file = substr($file, 0, -(strlen($ext) + 1));


		if ($file = Kohana::find_file('media', $file, $ext))
		{
			// Send the file content as the response
			$this->request->response = file_get_contents($file);
		}
		else
		{
			// Return a 404 status
			$this->request->status = 404;
		}
		
		// Set the content type for this extension
		$this->request->headers['Content-Type'] = File::mime_by_ext($ext);
		$this->request->headers['Content-Length'] = filesize($file);
		$this->request->headers['Last-Modified'] = date('r', filemtime($file));
	}
}

重点,在上面的 $this->request->check_cache() 方法,注意是利用了 HTTP 头信息的 ETag 作校验。

2. 设置路由

// the media files
Route::set('media', 'media(/<file>)', array(
		'file' => '.+'
	))
	->defaults(array(
		'controller' => 'base',
		'action'     => 'media',
		'file'       => NULL,
	));

3. 程序会自动把路径在 /media/ 下面的文件做缓存

你可能感兴趣的:(cache,kohana)