Tutorial

How to Install and Setup Kohana, a PHP Web-Application Development Framework

Published on December 30, 2013
Default avatar

By O.S Tezer

How to Install and Setup Kohana, a PHP Web-Application Development Framework

Introduction


Amongst many PHP based frameworks, Kohana sets itself apart from the rest with its ideology of following common conventions and rules to develop fully object oriented web applications. This BSD licensed framework does not come with commercial strings attached and it has a build-by-the-community, for-the-community type of philosophy.

In this three-part DigitalOcean series, we will be covering all the essentials a developer should be familiar with in order to start building web applications using the PHP5 Kohana framework. We will begin with going over some of the basics, continuing through the key concepts and modules after installing the framework.

Note: This is the first article in our Kohana series - and it mainly consists of the basics and its installation. To continue with learning the framework to create web-applications, check out its sequel Building Web Applications with HMVC PHP5 Framework Kohana.

Glossary


1. Web Application Development Frameworks


1. What Are Frameworks?
2. What Makes a Framework "Light"?

2. Kohana Framework


1. Kohana's Features
2. Kohana's Standard (Out-of-The-Box) Modules

3. Model - View - Controller Pattern


1. Routing Structure
2. Model
3. View
4. Controller
5. Template Files

4. Programming with Kohana and Preparations


5. Downloading and Installing the Kohana Framework


6. Getting Started with Kohana Installation


1. Bootstrapping The Setup
2. Setting Application Directory Permissions
3. Finalizing Everything and Testing

Web Application Development Frameworks


Kohana is a web application development framework. Given PHP’s nature as a language and the way the code written is executed on computers, there is no strict requirement to exploit frameworks to quickly develop applications when working with it. However, for any serious application that aims to have a long(-ish) lifecycle (making use of code already written once and with more than a single developer working on it), using a framework means making a ton of things much simpler.

What Are Frameworks?


Much like the dictionary definition of the word framework, web application frameworks provide both an essential structure to begin developing [applications] and a glue layer to hold everything together in a sound and logical way that makes sense for those who are familiar with the framework itself.

These bases come with many of the necessary common tools that are almost always needed to develop web applications such as processing incoming requests, generating and populating templates, returning responses, handling security and authentication, managing cookies (and sessions) and more.

What Makes a Framework “Light”?


Depending on the amount of tools a framework is shipped with out of the box, it is either referred to as a lightweight or an all-in-one (full stack, batteries included, etc.) solution. Kohana, albeit being extremely powerful and functionally rich, can still be considered light because of the freedom it gives to developers working with it, and the way it has been designed and set to operate.

Kohana Framework


Kohana HMVC (Hierarchical Model View Controller) framework offers - probably - all the tools necessary to build a modern web application that can be developed rapidly and deployed/maintained easily using the PHP [5] language.

Kohana’s Features


Compared to other similar solutions, Kohana sets itself apart not with its features but with the way it presents these features and how it performs them.

  • Kohana comes with many of the commonly required additional tools (modules)such as encryption, validation, database access etc.

  • It offers the possibility to simply expand the defaults.

  • Allows building commercial applications with its BSD licensing.

  • Getting started and setting up is extremely fast and easy compared to heavy and complicated frameworks.

  • All the modules and the way things function are designed and built using classes and object. The framework sustains the “Don’t Repeat Yourself” principle.

  • Offers profiling and debugging tools.

  • Its code is very well documented and it comes with a relatively good documentation with examples and good explanations.

  • Prefers following conventions over [endless and frustrating] configurations.

Kohana’s Standard (Out-of-The-Box) Modules


Below are some of the out-of-the-box modules of Kohana.

  • Auth: User authentication and authorization.

  • Cache: Common interface for caching engines.

  • Codebench: Code benchmarking tool.

  • Database: Database agnostic querying and result management.

  • Image: Image manipulation module.

  • ORM (Object Relational Mapper): A modeling library for object relational mapping.

  • Unittest: Unit testing module.

Model - View - Controller Pattern


The MVC (Model - View - Controller) application pattern is used to divide code and logical structures into groups depending on their role and what they are set out to perform. Each of these parts process information within themselves and then share the necessary output between each other to complete jobs collectively, forming the final presentation (i.e. results) to the end user (i.e. the result of a URL visited).

Routing Structure


Following the MVC pattern, a request goes through a process - similar to the example below - before a result gets returned.

  (1)                       (2)                    (3)
Request       --->       Parsing       --->     Matching
[Data] .. [] >> .. [] > [] [] [] .. .. .>. .. . ........

  (4)                       (5)                    (6)
Routing       --->      Controller     --->     Response
 ----- .. >> .. >> ..  ../\ .. /\  []  >> [] >>  [Data] 
                         ||  . ||
                         \/  . \/
                       Model   View

Model


In model, definition of object classes and handling the data operations exist. In this layer, there is no direct interaction with other parts of the application (e.g. views). When a new event takes place, model let’s its parent (i.e. the controller) know.

View


View layer consists of files where the views (e.g. data representations) are generated. The controller object, using the view, presents the final result to the user.

Controller


In controller, the parsed data from the request gets processed using the model and the view, generating the file response through actions. Controllers act like a glue, connecting all pieces to work together.

Template Files


Template files form a base which are generally used to facilitate maintenance of the representation of certain data presented by the application to the end user. In terms of PHP applications, PHP language equally acts like a templating language hence providing the templating syntax.

Programming with Kohana and Preparations


Kohana, as a light framework, consists of a bunch of files scattered across carefully structured directories which, in the end, is transferred to the production server and used to run the web application. Therefore, each Kohana package can be considered a [new] web application.

Note: In our examples, we will be working on a droplet, running the latest version of Ubuntu. To build web applications with Kohana, you can work on your home computer until the production step and later push your code for publication.

Note: We are going to use a default LAMP (Linux - Apache - MySQL - PHP) set up in our droplet to work with Kohana. To quickly set up a LAMP stack on a Ubuntu droplet, you can use:

sudo apt-get install tasksel
sudo tasksel install lamp-server

Downloading and Installing the Kohana Framework


The latest available version of Kohana is 3.3.1. In order to download it to our VPS, we will use wget (i.e. the GNU Wget command line tool).

wget https://github.com/kohana/kohana/releases/download/v3.3.1/kohana-v3.3.1.zip

After the download, we need to expand the zipped package. For this we will be using the unzip command and set ""my_app as the extraction folder.

# You might need to install *unzip* before extracting the files    
aptitude install -y unzip 

# Unzip and extract the files
unzip kohana-v3.3.1.zip -d my_app

# Remove the zip package
rm -v kohana-v3.3.1.zip

Once we are ready with the framework package, we can move it to a more permanent location to get it to work with Apache. The default location for our LAMP installation is /var/www/

# Remove the *index.html* inside /var/www
rm -v /var/www/index.html

# Move the application directory inside
mv my_app /var/www/

# Enter the directory
cd /var/www/my_app    

From now on, your installation will be accessible from the WWW.

# Visit: http://[your droplet's IP adde.]/my_app/ 
http://95.85.44.185/my_app/

Note: Kohana is not yet ready to work. Its configuration needs to be set first (i.e. bootstrapped).

Getting Started with Kohana Installation


Bootstrapping The Set Up


Before we start going over the steps to learn about developing an application, let’s bootstrap and finish off its installation procedure.

Run the following to edit the bootstrapping file using the nano text editor:

nano application/bootstrap.php

Edit your timezone:

# Find date_default_timezone_set and set your timezone
date_default_timezone_set('Europe/London');

Set your locale:

# Find setlocale and set your locale
setlocale(LC_ALL, 'en_UK.utf-8');

Set the base application directory location:

# Find base_url and set the base application directory
# Relative to the base Apache directory (i.e. /var/www/)

Kohana::init(array(
    'base_url' => '/my_app/',
));

Enable modules:

# Find Kohana::modules and uncomment them

Kohana::modules(array(
    'auth'       => MODPATH.'auth',       // Basic authentication
    'cache'      => MODPATH.'cache',      // Caching with multiple backends
    'codebench'  => MODPATH.'codebench',  // Benchmarking tool
    'database'   => MODPATH.'database',   // Database access
    'image'      => MODPATH.'image',      // Image manipulation
    'orm'        => MODPATH.'orm',        // Object Relationship Mapping
    'oauth'      => MODPATH.'oauth',      // OAuth authentication
    'pagination' => MODPATH.'pagination', // Paging of results
    'unittest'   => MODPATH.'unittest',   // Unit testing
    'userguide'  => MODPATH.'userguide',  // User guide and API documentation
));

Save and exit by pressing CTRL+X and confirm with Y.

Setting Application Directory Permissions


In order to run Kohana, we need to mark two of its folders writable.

sudo chmod -R a+rwx application/cache
sudo chmod -R a+rwx application/logs

Finalizing Everything and Testing


Once we are done with bootstrapping the set up and configuring folder permissions, we can test it all again by visiting the application using a web browser

# Visit: http://[your droplet's IP adde.]/my_app/ 
http://95.85.44.185/my_app/

When you confirm that everything is set correctly and working fine, you can remove the install.php.

Run the following to remove the install file:

rm -v install.php

If you re-visit the URL from the previous step, you will be welcomed with a hello, world! message. This means that our requests are now routed through the HMVC process following the pattern correctly.

<div class=“author”>Submitted by: <a href=“https://twitter.com/ostezer”>O.S. Tezer</a></div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


Tutorial Series: An Introduction to Kohana, a PHP Web-Application Development Framework

In this three-part DigitalOcean series, we will be covering all the essentials a developer should be familiar with in order to start building web applications using the PHP5 Kohana framework. We will begin with going over some of the basics, continuing through the key concepts and modules after installing the framework.

About the authors
Default avatar
O.S Tezer

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
3 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

unfortunately no. now i’m getting 500 errors from nginx. i tried changing the root directory to a single kohana app and nothing is working. i also tried switching to apache2 and oddly i get exactly the same behavior. the default route works but any other controller/action gives a 404 or 403 error (nginx and apache respectively.)

i’ve been trying to get this working for days. meanwhile i have it running locally on several different machines without any problem. i don’t think i understand php-fpm and nginx enough to know why this is happening. but it looks like the server is not giving control over to kohana when it should?

do you have any ideas? i’m going crazy trying to get this up and running…

thanks

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 14, 2014

@gad2103: Try using the config from part 3 of the Kohana series. Does that work?

hello. i’m trying to set this up on ubuntu 14.04 with php-fpm. the nginx conf file doesn’t seem to be working.

i have my kohana app in a user subdirectory of my vps. so i set root /path/to/myusername/Sites/public

here is my conf file (sorry its a mess because i’ve been putting things in and taking them out to see what if anything will work)

server {
	listen 80 default_server;
	listen [::]:80 default_server ipv6only=on;

	root /home/gabreal/Sites/public;
	index index.html index.htm index.php;

	# Make site accessible from http://localhost/
	server_name localhost;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ @kohana =404;
		# Uncomment to enable naxsi on this location
		# include /etc/nginx/naxsi.rules
		#if (!-e $request_filename)
		#{
		#	rewrite ^/(.*)$ /index.php/$1 last;
		#}
	}

	# Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests
	#location /RequestDenied {
	#	proxy_pass http://127.0.0.1:8080;    
	#}

	error_page 404 /404.html;

	# redirect server error pages to the static page /50x.html
	#
	error_page 500 502 503 504 /50x.html;
	location = /50x.html {
		root /usr/share/nginx/html;
	}

	# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
	#
	location ~ \.php$ {
		
		try_files $uri $uri/ @kohana;
		#if ($request_uri ~* /grader/.*$) {
		#	root /home/gabreal/Sites/public/grader/grader;
		#}
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
	#	# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
	#
	#	# With php5-cgi alone:
		#fastcgi_pass 127.0.0.1:9000;
	#	# With php5-fpm:
		fastcgi_pass unix:/var/run/php5-fpm.sock;
		fastcgi_index index.php;
		include fastcgi_params;
	}

	location @kohana {
		rewrite ^/(.+)$ /index.php$request_uri last;
	}
	# deny access to .htaccess files, if Apache's document root
	# concurs with nginx's one
	#
	location ~ /\.ht {
		deny all;
	}
}

when i go to http://example.com/horizons/grader/ the app is obviously picking this up because it checks the cookie to see if the user is logged in and redirects to http://example.com/horizons/grader/user/login/. HOWEVER then i get nginx 404 error. so it looks like for some reason the kohana app isn’t getting to handle the uri routing.

i have this working perfectly on two local machines running apache and mod_php, but i need to deploy this to the vps. any help would be greatly appreciated!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel