ele_eel's diary

プログラムの事を少しと、デジタル系買物記。

サンプルコードからKohana 3 を学ぶ

新しいプログラムに取り掛かる時は「解説書よりサンプルコード」な人も多いと思います。KO3 を使い始める人には非常に参考になるサンプルを Kohana の主要開発者である shadowhand さんが公開しています。


shadowhand's wingsc at master - GitHub github.com
http://github.com/shadowhand/wingsc

CRUD のデータベース操作や、application/bootstrap.php でのURLルーティングが非常にためになります。


KO2 にあった本サーバ用定数 IN_PRODUCTION が bootstrap.php に追加されています。Kohana のイニシャライズの際にプロファイリングの有無やキャッシュの利用などを振り分けているようです。

<?php

/**
 * Set the production status by the domain.
 */
define('IN_PRODUCTION', $_SERVER['SERVER_ADDR'] !== '127.0.0.1');

/**
 * Initialize Kohana, setting the default options.
 */
Kohana::init(array(
	'base_url'   => '/',
	'index_file' => FALSE,
	'profiling'  => ! IN_PRODUCTION,
	'caching'    => IN_PRODUCTION
));


一番の注目はURLルーティングのやり方。今までuserguide のサンプルや Route クラスを見てもよくわからなかったです。

まず Routeのスタティックメソッドにキャッシュがあるのを知りました。キャッシュしたほうが処理速度に違いがでるんでしょうか。それから最後の設定の default のルーティングは、静的ページを読み込むようになっています。これで以前のようなコントローラーがなければ静的ページを読み込むといった処理ができます。
このルーティングの設定次第で URL からコントローラ名を推測されにくくなりそうです。

<?php
if ( ! Route::cache())
{
	Route::set('work', 'did(/<project>(/<action>))', array(
			'project' => '.+?(?:/with/.+?)?',
		))
		->defaults(array(
			'controller' => 'portfolio',
		));

	Route::set('calendar', 'will(/<action>)')
		->defaults(array(
			'controller' => 'calendar',
		));
	
	//途中省略

	Route::set('default', '(<page>)', array('page' => '.+'))
		->defaults(array(
			'controller' => 'static',
			'action'     => 'load',
			'page'       => 'is',
		));

	// Cache the routes
	Route::cache(TRUE);
}


最後はカスタムエラーページの設定の仕方。簡単に言えば、URIにエラーがあった場合は 404 エラーを返すということです。ここではエラーの際には全て 404 で返すようになってます。

<?php

/**
 * Execute the main request using PATH_INFO. If no URI source is specified,
 * the URI will be automatically detected.
 */
$request = Request::instance($_SERVER['PATH_INFO']);

try
{
	// Attempt to execute the response
	$request->execute();
}
catch (Exception $e)
{
	if ( ! IN_PRODUCTION)
	{
		// Just re-throw the exception
		throw $e;
	}

	// Log the error
	Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));

	// Create a 404 response
	$request->status   = 404;
	$request->response = View::factory('template')
		->set('title', '404')
		->set('content', View::factory('errors/404'));
}

その他、いろいろ参考になると思います。