Kohana 3.1 Wiki Tutorial Routes

Posted on May 16, 2011

In the original Kohana wiki application the URLs in the views were hardcoded. If we wanted to change the domain name or restructure a route we would need to go through the application and change every single URL.

Thankfully the Kohana Route class comes with a method url() which allows us to generate URLs to routes we have specified in the application. In the first tutorial we defined the following routes in application/bootstrap.php:

Route::set('wiki-edit', 'wiki/<page>/edit')
	->defaults(array(
		'controller'=> 'wiki',
		'action'	=> 'edit_page',
	));

Route::set('wiki-save', 'wiki/<page>/save')
	->defaults(array(
		'controller'=> 'wiki',
		'action'	=> 'save_page',
	));

Route::set('wiki-page', 'wiki/<page>')
	->defaults(array(
		'controller'=> 'wiki',
		'action'	=> 'view_page',
	));

Route::set('default', 'wiki')
	->defaults(array(
		'controller' => 'wiki',
		'action'     => 'view_page',
		'id'		 => 'index',
	));

Before we can generate routes we need to set some configuration options in application/bootstrap.php (line ~82). We need to specify the base_url and index_file attributes in the array passed to Kohana::init(). The application on my local install is located at 127.0.0.1/query7kwiki/index.php, so my Kohana::init() statement would read:

Kohana::init(array(
	'base_url'   => '/query7kwiki/',
	'index_file' => 'index.php'
));

In application/views/edit.php the form action attribute was hardcoded to the value /query7kwiki/index.php/wiki/. That can be replaced by:

<?php echo Route::url('wiki-save', array('page' => $page)); ?>

In application/views/single.php there is a link to the edit that specific page. We can replace the href of the anchor tag with:

<?php echo Route::url('wiki-edit', array('page' => $page)); ?>

In the view application/views/create.php change the href of the create page link to:

<?php echo Route::url('wiki-edit', array('page' => $page)); ?>

The wiki application is now portable and can safely be moved to a different server without functionality breaking.

Leave a Reply

You must be logged in to post a comment.