Thursday 24 September 2009

Kohana PHP framework - some tips

Recently, I've been working with the Kohana PHP Framework and there are a few hurdles I've come across and gotten past - here are a few tips.

Making your own Controller

The default gateway controller with a fresh install of Kohana is 'welcome'. This means that URIs are written a bit like this:

http://localhost/kohana/welcome/index

But it's not ideal to have 'welcome' in the URI all the time. So, if you want to choose a custom name like 'site', you need to make your own controller...
  1. Copy the welcome controller (welcome.php) in /kohana/applications/controllers/ and paste into the same folder.
  2. Rename the file to site.php
  3. Open the site.php file and change the class declaration to 'class Site_Controller extends Template_Controller'
  4. Now, go to /kohana/system/config/ and copy the file called routes.php to /kohana/application/config/ .
  5. Open up the file and edit like so: $config['_default'] = 'site';
That should do it. Your site will now build its URIs and route through the 'site' controller by default. You should make urls like so:

<?php html::anchor('site/index', 'Home Page'); ?>

Making your own default template

Simply go to /kohana/system/views/kohana/ and copy the template.php file to /kohana/application/views/kohana/. Edit the file as you wish. But, make sure your controller has this line pointing to it: public $template = 'kohana/template';

Making your CSS and Javascript work (get found)

So you make your XHTML template file and are ready to test everything - you stick your CSS in a .css file and your Javascript into a .js file and your images into an 'images' folder and put them in the root (/kohana/). You go to the page through the URI, e.g. http://localhost/kohana/site/index

Huh? What's this? Your CSS, Javascript and image files were not found!

Turns out you need to change the location of your files and add some PHP to your template.
  1. make a folder in root (/kohana/) called 'media'.
  2. make 3 folders called images, css and js inside your media folder and move your images, css and javascript files into their respective folders
  3. Edit your css and js files to point to the right path for the images, e.g: background-image: url(/kohana/media/simages/bg.png); (make sure the first / is there otherwise it won't work
  4. Now edit your template file to include this bit of code in the head section (I called my css file and js file css.css and js.js (imaginative huh?)):
<?php echo html::stylesheet(array('media/css/css'), array('screen')) .
html::script(array('media/js/js'), FALSE); ?>

Now this will put the typical XHTML tags into your page to include outside css and js files:
<link rel="stylesheet" type="text/css" href="/kohana/media/css/css.css" media="screen" />

<script type="text/javascript" src="/kohana/media/js/js.js">