Getting started with Kohana (Day 1)

Note : I will use XAMPP web server (which have PHP 5.3.x) and Kohana version 3.2. a simple beginner tutorial for anyone who really newbie at kohana.

Step 1 : Install Kohana

Download the framework here. Unzip that file on your ‘htdocs’ XAMPP. I will name my project “badass”. So I’ll rename the Kohana package folder into “/badass”. Try it on your localhost http://localhost/badass. Then you should find this page:

If all of the requirements passed, you can continue to step 2.

Intermezzo 1 : Kohana File Structure

Kohana is a HMVC (Hierarchical model–view–controller) which mean that you can split your application into such modules. Each module can have independent MVC (Model, View, again Controller). So what? So.. you can steal the module if you need the same module in the future for other application.

What the, you don’t know MVC. I think wikipedia have explained it well here, dude.

So your kohana package contains these folder in the root :

    • badass/application/
    • badass/module/
    • badass/system/
    • badass/example.htaccess
    • badass/index.php
    • badass/install.php
    • etc etc...

I will explain briefly what are these folders.

# Application – it’s where your application files such as MVC-look alike located NORMALLY. Your everything about your application will be here, young padawan.

The MVC configuration is like this :

    • /classes/controller/
    • /classes/model/
    • /views/

BUT, because kohana is a HMVC, you can have hierarchial of those folders configuration. It can look like this later:

# Module –  it’s where your plugin will be put NORMALLY. You can make your own module, if you want. Lol, some of my dudes build their own framework by customizing the module. Ah, don’t worry, Kohana isn’t angry about this. Kohana has BSD license. So feel free to make your own framework.

# System – ugh.. it’s Kohana core system, again NORMALLY. Better leave it if you don’t know anything.

I said NORMALLY three times, you know. (Really, you don’t know what people might doing these days, tweaking, customizing, etc this framework.)

Different enough with CI structure, huh?

Step 2 : Hello world!

1. Remove or rename install.php.

Open /application/bootstrap.php

2. Change these :

Timezone

/**
 * Set the default time zone.
 *
 * @see  http://kohanaframework.org/guide/using.configuration
 * @see  http://php.net/timezones
 */
date_default_timezone_set('Australia/Sydney');

Base URL (Because my project is badass, so here it is, from “/” to “/badass“)

/**
 * Initialize Kohana, setting the default options.
 *
 * The following options are available:
 *
 * - string   base_url    path, and optionally domain, of your application   NULL
 * - string   index_file  name of your index file, usually "index.php"       index.php
 * - string   charset     internal character set used for input and output   utf-8
 * - string   cache_dir   set the internal cache directory                   APPPATH/cache
 * - boolean  errors      enable or disable error handling                   TRUE
 * - boolean  profile     enable or disable internal profiling               TRUE
 * - boolean  caching     enable or disable internal caching                 FALSE
 */
Kohana::init(array(
	'base_url' => '/kohana',
));

3. Then be ready, young padawan, open your badass again now, http://localhost/badass

Good job, lads, let’s continue to step 3.

Intermezzo 2 : How Kohana route their config at first?

Well, for me it’s disturbing if I don’t know where I start learn my framework. From what I learn, Kohana briefly works like this : index.php in your badass folder will access /application/bootstrap.php. Bootstrap will check default class that will be accessed first (check the last code) :

/**
* Set the routes. Each route must have a minimum of a name, a URI and a set of
* defaults for the URI.
*/
Route::set('default', '((/(/)))')
->defaults(array(
'controller' => 'welcome',
'action' => 'index',
));

So, bootstrap.php will access class Welcome, action Index.

Step 3 : URL rewriting, no more index.php

I’m tired now. I won’t explain anything in such detail again, yes. By default if you want to access your class-action you should access this :

http://localhost/badass/index.php/classname/actionname/param1/param2/...

I thinks it’s not cool to have index.php hanging around. You can remove it if you want, so that it will be accessed like this later :

http://localhost/badass/classname/actionname/param1/param2/...

So, we will play .htaccess for a bit. In kohana package, the example of .htaccess is already prepared.

badass/example.htaccess

Rename it to .htaccess (if you understand the mod : the permission should at least executable). Edit the file, change the base url. More or less like this


# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /badass/

# Protect hidden files from being viewed

	Order Deny,Allow
	Deny From All

# Protect application and system files from being viewed
RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

We should configure our web server for a bit so that .htaccess we have prepared works. We should enable rewrite_module in apache config. In my case this config can be found in folder httpd.conf (xampp/apache/conf/httpd.conf). Uncomment by clear the # of rewrite module like this :

...
LoadModule rewrite_module modules/mod_rewrite.so
...

For other web server maybe need other configuration. Just google it, my point is rewrite_module have to be enabled.

One last thing, update your bootstrap.php :


/**
* Initialize Kohana, setting the default options.
*
* The following options are available:
*
* - string base_url path, and optionally domain, of your application NULL
* - string index_file name of your index file, usually "index.php" index.php
* - string charset internal character set used for input and output utf-8
* - string cache_dir set the internal cache directory APPPATH/cache
* - boolean errors enable or disable error handling TRUE
* - boolean profile enable or disable internal profiling TRUE
* - boolean caching enable or disable internal caching FALSE
*/
Kohana::init(array(
'base_url' => '/badass',
'index_file' => FALSE
));

Voila, from now on you don’t have to worry index.php hanging around anymore.

Next, step 4.

Step 4 : Playing a bit with Controller and View

As I explained before that MVC-thingy is located in application folder :

  • /classes/controller/
  • /classes/model/
  • /views/

Keep that in mind that “view” should be used for layout only. Most of us tempted to put logical code into “view”. Well, it’s up to us actually. But if you want to have MVC skill, you should learn to put all of logical code in “controller” class.

I will alter some changes in welcome class that already in folder controller :

welcome.php

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

	public function action_index()
	{
        //-- Set Contact Details to an Anonymous Object
        $contact_info = new StdClass;
        $contact_info->telephone = "1800 111 888";
        $contact_info->address = "123 Fake st. Springfield";
        $contact_info->email = "demo@demosite.com";

        //-- Render the view
        $view = View::factory('welcome/layout');
        $view->set("title", "Header");
        $view->set("header", View::factory('welcome/header'));
        $view->set("content", View::factory('welcome/content')->bind("contact_info", $contact_info));
        $this->response->body($view);
	}

	public function action_about()
	{
        //-- Arrange
        $page_title = "About Us - Kohana Demo Site";
        $page_header = "All About Us";
        $message = "This is where you learn about this website.  sdfafafdsafa.";

        //-- Render the view
        $view = View::factory('welcome/about');
        $view->set("title", $page_title);
        $view->set("header", $page_header);
        $view->set("message", $message);
        $this->response->body($view);
	}

	public function action_contact()
	{

        //-- Arrange
        $page_title = "Contact Us - Kohana Demo Site";
        $page_header = "Contact Information";
        $message = "I will let you know how to find us in this page.";

        //-- Set Contact Details to an Anonymous Object
        $contact_info = new StdClass;
        $contact_info->telephone = "1800 111 888";
        $contact_info->address = "123 Fake st. Springfield";
        $contact_info->email = "demo@demosite.com";

        //-- Render the view
        $view = View::factory('welcome/contact');
        $view->set("title", $page_title);
        $view->set("header", $page_header);
        $view->set("message", $message);
        $view->bind("contact_info", $contact_info);
        $this->response->body($view);
	}

}

I will add some view php class that called by welcome controller above :

layout.php

<!--?php defined('SYSPATH') or die('No direct script access.') ?-->
<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title><?php echo $title; ?></title>
    </head>
    <body>
        <div><?php echo $header; ?></div>
        <div><?php echo $content; ?></div>
    </body>
</html>

header.php

<!--?php defined('SYSPATH') or die('No direct script access.') ?-->

        <h1>HEADING 1</h1>
        <p>ini headernya bung</p>

content.php

<!--?php defined('SYSPATH') or die('No direct script access.') ?-->

        <ul>
            <li>Telephone: <?php echo $contact_info->telephone; ?></li>
            <li>Address: <?php echo $contact_info->address; ?></li>
            <li>Email: <?php echo $contact_info->email; ?></li>
        </ul>

about.php

<!--?php defined('SYSPATH') or die('No direct script access.') ?-->
<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title><?php echo $title; ?></title>
    </head>
    <body>
        <h1><?php echo $header; ?></h1>
        <p><?php echo $message; ?></p>
    </body>
</html>

contact.php

<!--?php defined('SYSPATH') or die('No direct script access.') ?-->
<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title><?php echo $title; ?></title>
    </head>
    <body>
        <h1><?php echo $header; ?></h1>
        <p><?php echo $message; ?></p>
        <ul>
            <li>Telephone: <?php echo $contact_info->telephone; ?></li>
            <li>Address: <?php echo $contact_info->address; ?></li>
            <li>Email: <?php echo $contact_info->email; ?></li>
        </ul>
    </body>
</html>

Yatta!! Now you can access three different pages :

http://localhost/badass/welcome/ or http://localhost/badass/ (because it will result the same)
http://localhost/badass/welcome/about
http://localhost/badass/welcome/contact

Wise man said that we shouldn’t fish for anyone that need help, but we should teach those ones to fish. So please learn it, and ask me if you confused.

Lastly. Wise man again said that you should RTFM (read the F{funny} manual), please.

NB. We haven’t work with M for model in MVC yet. Be prepared!

2 pemikiran pada “Getting started with Kohana (Day 1)

    • pertama dari sisi Authentication syalala.. gue juga gak terlalu ngerti dan gak pake juga sih.

      kedua by default kohana HMVC – hieararkial. Artinya lo bisa bikin aplikasi lo modular secara MVC nya. Ilustrasinya :
      # rootweb
      – controller
      – model
      – view
      > module penggajian
      – controller
      – model
      – view
      > module pemasaran
      – controller
      – model
      – view
      > modul dst…
      – …
      jadi MVC nya bisa dipisah per modul aplikasi kita (masing2 modul punya mvc sendiri). kalo bikin aplikasi lain trus misal kita butuh suatu modul di aplikasi lama, kita bisa tinggal ambil per modulnya aja.

      CI setelah gw gugel2 ternyata nggak HMVC, jadi semua model, view, controller dihajar masing-masing di satu folder models, views, ama controller. Tapi CI juga punya pluginnya sih coba aja google “codeigniter HMVC” ntar muncul pluginnya. Belom dicoba.

      ketiga, nggak tahu CI udah nanganin apa belom, tapi si kohana ini udah go HTML5

      sejauh ini yg gw temuin itu sih keunggulannya,

      kekurangannya? Dukungan komunitas CI jauh luar biasa besar. Jadi jangan khawatir kalo punya problem. Dokumentasi juga relatif lebih banyak. Perbandingannya bisa dilihat kalau kita google “kohana” (found around 490,000) dan “codeigniter” (found around 11,200,000) . Walau begitu kohana juga merupakan salah satu framework php papan atas sih.

      cmiiw

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s