Introduction to Kohana PHP Framework

Exclusive offer: get 50% off this eBook here
PHP Team Development

PHP Team Development — Save 50%

Easy and effective team work using MVC, agile development, source control, testing, bug tracking, and more

$20.99    $10.50
by Mambe Churchill Nanje | December 2009 |

In this article by Mambe Churchill Nanje, we will introduce you to Kohana PHP framework. We will cover the following :

  1. Overview
  2. Why use Kohana PHP framework?
  3. Key features of Kohana PHP Framework
  4. Getting started with Kohana PHP Framework
  5. Developing a simple contact form with Kohana PHP Framework

Overview

Kohana PHP Framework is an open source PHP software development framework that helps php developers to build web applications faster, and also, more effectively by providing them with a set of built-in objects/classes. It also enforces highly organized coding standards.

The Kohana PHP Framework is just like Ruby on Rails; it implements the well known software engineering design pattern—Model View Controller(MVC). The Model View Controller software design pattern guides engineers to design their software codes into three separate parts which includes:

  • Models: The objects that manipulate data sources and data stores.
  • Views: The html and css files with inline php codes that present the user interface and controls to the application users.
  • Controllers: Objects in charge of the business logic, displaying the page(views), and routing the click actions from the views to the model and back to the views.

Kohana was originally based upon the well documented codeigniter php framework, but it stands out due to its strict use of OOP best practices and standards.

Kohana PHP is officially defined by its creators to be a PHP 5 framework that uses the model view controller architectural pattern. It aims to be secure, lightweight, and easy to use.

Why use Kohana PHP framework?

PHP is a very easy to use programming language, that's the reason why its loved by the web development community. It's easy to use nature and learning curve has attracted a lot of users. But PHP has one downside. Most experienced developers don’t love coding php due to its little Object orientation, and its often nasty codes. With Kohana PHP, any php developer from beginner to expert will all get to write standard codes which we see in the Java World, or the .NET world. Kohana bridges the gap between amateur web developers and designers who love php because its easy, and the experienced web developers who go fully into Object Oriented codes and nothing less. Kohana enforces true software engineering and brings it closer to the php world which has little or no standards. So the major reason why you should use Kohana PHP Framework for your php work is to ensure that your codes are of standards, and you follow the best practices which go a long way to help teams of developers from beginners to experts to easily work together with the PHP programming language.

Kohana PHP Framework solves the problem of beginners, and intermediate developers who have nasty codes and are killing the overall work of the team. With the well documented and standard practices of Kohana, a developer in India can write the code and a developer in Africa can optimise the code without asking a lot of questions, because everything will clearly be a model, view or a controller, and it will be easy to understand what it was meant for exactly.

Key features of Kohana PHP framework

Kohana PHP has some very good features that makes it stand out from all other PHP frameworks. The features include: 

  • Fully Object Oriented: Object oriented programming is an industry standard since the introduction of C++. Many developers working with Java programming languages are comfortable with Object and classes, and they prefer the order it brings to programming. Kohana PHP being fully Object oriented, it automatically brings this order and industry standard programming to PHP; with this, you wont get developers saying you are just a php developer because Kohana PHP is a standard software programming platform for enterprise and web applications.
  • In built templating: Kohana PHP like most other standard web frameworks has a very easy to use template engine. You get a simple html file, covert it into a kohana template by renaming it to template.php, fit in two php variables— $title and $content, to signify where the title of the page and where the content will be displayed. That’s all you need to have a kohana php template.
  • In built Internationalization: Kohana PHP strongly supports internationalization and good documentation. With Kohana, all you need to do is create the various language files and use an internationalization object to reference the files depending on the language from page to page. Switching the language, automatically switches the language file referenced.
  • Robust ORM Engine: ORM stands for Object Relational Mapping. It’s a programming concept in which your codes directly manipulate the database tables as objects, while the SQL gets generated for you behind the scenes. The ORM in Kohana is easy due to its use of convention over configuration. Its the best ORM I have seen in the php world and its 100% stable. To make use of the ORM, you simply extend the ORM class in your model and that model will be able to manipulate your database without any SQL code.
  • MVC: the framework is based on MVC, and this helps to bring about a lot of order, eases code maintenance and team work. I can get any Kohana PHP application, and easily understand what every code does because it must flow from a controller to a view or to a model then to a view. And that’s all about it.
  • Clean and Search Engine Friendly URLs: Kohana PHP framework has a good implementation of controllers where every url call or reference in a kohana based site refers to a controller and its function, as in site/controller/function/parammeters. For example, calling a blog controller to show a post with ID 1 will be as simple as your-site.com/index.php/blog/showPost/1 where index.php is the front controller, blog is a controller object and show post a blog->showPost function that takes a parameter which is the post ID.
  • Libraries and helpers and third party classes: With kohana php, you have a set of libraries and helpers for almost everything you need as a web developer. For instance, sending out an email is as easy as calling email::send() function. There are more helpers and libraries, getting to read about them on the Kohana php website will make you feel like your life as a developer has been taken away and you are just a secretary.

Also with Kohana PHP, you can get any available php class from the internet and use it in the kohana framework by simple dropping the file in a folder in your kohana site known as vendor, and then, instantiating the class in your codes. That’s all! It sounds too good to be true but thats all you need to use that PEAR object or that zend class or that php class you have been using for years with kohana framework on your next project.

PHP Team Development Easy and effective team work using MVC, agile development, source control, testing, bug tracking, and more
Published: September 2009
eBook Price: $20.99
Book Price: $34.99
See more
Select your format and quantity:

Getting started with kohana php framework

Getting started with Kohana PHP would require full understanding of php programming language and being able to configure a local apache, php and mysql server.

  1. Download the kohana source files on http://www.kohanaphp.com and drop the folder in your local server's www or htdocs folder. Rename the folder to your-site.com so that you can access it as http://localhost/your-site.com.
  2. Configure Kohana framework to understand where it’s being hosted. This is done in a file config.php found at htdocs/your-site.com/application/config/config.php locate the setting $config['base_url']= and set it to 'localhost/your-site.com/' .
     Thats all you need to get Kohana in place.
  3. Check if the local server can work with Kohana PHP and also fully support all its features.
    Visit http://localhost/your-site.com and see if kohana reports any errors; else, if it reports success then your good to start building your applications. Go into your-site.com folder and delete or rename install.php
     Now you are ready to start coding your first kohana application.

Developing a simple contact form with kohana php framework

Now that you have configured the server, we are going to build a simple contact form with the Kohana PHP Framework.

We will create a template file, a controller that extends the template controller, a model and a contact form view.

  1. Creating the template file
    We assume you already have a design for your site. If you don't have a design template, visit http://www.oswd.org and download any of the templates. Convert the index.html file to template.php file and drop the file in your-site.com/application/views folder. Open the template.php file and insert the <?php echo $title; ?> in between the <title> tags as shown below.

    <title><?php echo $title; ?> </title>

    Then insert <?php echo $content; ?> any where in between the <body> tags. Now, we have our php master template for our kohana framework based website.

  2. Creating the site controller
     A controller is simply a php class file stored in the controllers’ folder on the kohana framework, and extends the abstract controller class or a sub class of the controller.
    Create a site.php file in htdocs/your-site.com/application/controllers and paste this code in the file.
    <?php 
    class site_controller extends template_controller{
      function index(){
        //create a notice variable to keep notifications to the user
         $notice="";
            //create a fields array to store allthe fields expected from the contact form
            $fields=array('name'=>'','email'=>'','message'=>'');
            //check for post or if someoen filled the form check for post data
            if($_POST){
                //if there is post data validate with the validation library
                $val=new Validation($_POST);
                //make all html fields required
                $val->add_rules("*", "required");
                //set validation to ensure that the email is a valid email
                $val->add_rules("email","valid::email");
                if($val->validate()){
                    // if validation returns true, send the email
                    $from=$_POST['email'];
                    $to="info@your-site.com";
                    $subject="contact from your-site.com";
                    $message=$_POST['name']." sent the following message: <br><br>";
                    $message.=$_POST['message'];
                    //call the email static method to send the mail
                    email::send($to, $from, $subject, $message,TRUE);
                    //set a notice informing the user the mail was sent $notice="Thanks
    <b>".$_POST['name']."</b> your message has been sent";
                }else{
                    //if validate object returns false, get the errors
                    $notice="Errors: <br>";
                    $errors=$val->errors('form_errors');
                    foreach($errors as $key=>$val){
                        $notice.=$val."<br>";
                    }
                    $fields=$_POST;
                }
            }
            //set all views to be able to access the notice variable
            View::factory()->set_global('notice',$notice);
            //set all views to access the fields variable 
            View::factory()->set_global('fields',$fields);
            //set the title of the template to contact page
            $this->template->title="contact page";
            //instantiate a view object and set it to the template
    content variable we crated above
    //this sets the content of the page to load the html
    found in application/views/contact_view.php
            $this->template->content=new View('contact_view');        
    }
    }
    ?>

    The code above creates a site controller which can be accessed at http://localhost/your-site.com/index.php/site, and the index function will be the default function called. It loads the contact_view.php file which when filled will later call back this same function, but this time the POST content will be available and the code flow will add the validation and sending of mails or error reporting. The code is well commented to make it easy to follow.

  3. Creating the contact view
    create a file contact_view.php in the folder htdocs/your-site.com/application/views and paste the following code in it.
    [code] 
    <style type="text/css">
    <!--
    .notice{
    border:1px solid #FFCC00;
    background-color:#FFFFCC;
    font-weight:bold;
    padding:4px;
    }
    -->
    </style>
    <?php
    //check if there is a notice and display the notice
    if(!empty($notice)){
    echo "<p class='notice'>".$notice."</p>";
    }
    ?>
    <p>
    <h1>CONTACT FORM</h1>
    <form action="" method="post">
    <table width="90%" border="0" class="grey-bg">
      <tr>
        <td><strong>Name:*</strong></td>
        <td><input name="name" type="text" id="name" value="<?=$fields['name']?>" /></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td><strong>Email:*</strong></td>
        <td><input name="email" type="text" id="email" value="<?=$fields['email']?>" /></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td valign="top"><strong>Message:*</strong></td>
        <td><textarea name="message" rows="4" id="message"><?=$fields['message']?></textarea></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="Submit" value="Submit" /></td>
      </tr>
    </table>
    </form>
     </p>
    [code]

    the contact_view which is called by the controller index function above will display the contact form, and filling it and submitting will either show errors or success.

The contact_view which is called by the controller index function above will display the contact form, filling it and submitting will either show errors or success.

Summary

From the above, you can see how easy it is to write kohana codes, and also how easy it makes life with its already available libraries and helpers like the validation and email classes I used above. There are more on http://learn.kohanaphp.com and over the internet.

I hope this serves as an appetizer for you to go and try on kohana php even more.

PHP Team Development Easy and effective team work using MVC, agile development, source control, testing, bug tracking, and more
Published: September 2009
eBook Price: $20.99
Book Price: $34.99
See more
Select your format and quantity:

About the Author :


Mambe Nanje Churchill is a Cameroonian software entrepreneur based in Buea. He is the founder and president of AfroVisioN Group, a software company which provides domestic and outsourced solutions to a broad range of customers. When he is not writing software or doing some form of related business, you might find Churchill watching MTV or shooting and editing music videos.

Books From Packt

Python Testing: Beginner's Guide
Python Testing: Beginner's Guide

MySQL Admin Cookbook
MySQL Admin Cookbook

Apache MyFaces 1.2 Web Application Development
Apache MyFaces 1.2 Web Application Development

Mastering phpMyAdmin 3.1 for Effective MySQL Management
Mastering phpMyAdmin 3.1 for Effective MySQL Management

Apache Maven 2 Effective Implementation
Apache Maven 2 Effective Implementation

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

PHP and script.aculo.us Web 2.0 Application Interfaces
PHP and script.aculo.us Web 2.0 Application Interfaces

Expert PHP 5 Tools
Expert PHP 5 Tools

Your rating: None Average: 5 (4 votes)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
c
Z
u
T
z
j
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software