kohanaは静的ファイルにキャッシュメカニズムを提供する

1634 ワード

静的ファイルとは、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/下のファイルをキャッシュします