kohana documentaion

62
Kohana is an open source, object oriented MVC web framework built using PHP5 Anything can be extended using the unique filesystem design, little or no configuration is necessary, error handling helps locate the source of errors quickly, and debugging and profiling provide insight into the application How to use Controllers and Views How To Create and Use a Controller A Controller is a class file that stands in between the models and the views in an application. It passes information on to the model when data needs to be changed and it requests information from the model when data needs to be loaded. Controllers then pass on the information of the model to the views where the final output can be rendered for the users. Conventions for a controller Must reside in a controllers (sub-)directory Controller filename must be lowercase, e.g. articles.php Controller class must map to filename and capitalized, and must be prefixed with Controller_, e.g. Controller_Articles Must have the Controller class as (grand)parent Controller methods that are not declared public and are not preceded by 'action_' (e.g. action_index() ) cannot be defined with a Routed request The output of a controller should be passed to the body() method Requesting a Controller By default requesting a controller from a url is done by appending the controller name and the action name to the url in the following format. http://example.com/index.php/<controller>/<action>

Upload: kranthi

Post on 28-Oct-2014

64 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Kohana Documentaion

Kohana is an open source, object oriented MVC web frameworkbuilt using PHP5 

Anything can be extended using the unique filesystem design, little or no configuration is necessary, error handling helps locate the source of errors quickly, and debugging and profiling provide insight into the application

How to use Controllers and Views

How To Create and Use a ControllerA Controller is a class file that stands in between the models and the views in an application. It passes information on to the model when data needs to be changed and it requests information from the model when data needs to be loaded. Controllers then pass on the information of the model to the views where the final output can be rendered for the users.

Conventions for a controller

Must reside in a controllers (sub-)directory

Controller filename must be lowercase, e.g. articles.php

Controller class must map to filename and capitalized, and must be prefixed with Controller_,

e.g. Controller_Articles

Must have the Controller class as (grand)parent

Controller methods that are not declared public and are not preceded by 'action_' (e.g.

action_index() ) cannot be defined with a Routed request

The output of a controller should be passed to the body() methodRequesting a ControllerBy default requesting a controller from a url is done by appending the controller name and the action name to the url in the following format.

http://example.com/index.php/<controller>/<action>

For example. The following request is asking for the index action of the basic controller. http://example.com/index.php/basic/index

Creating a ControllerControllers for an application are kept in the application/classes/controller folder and for a module they are kept in module/mymodule/classes/controller folder.A Basic Controller

application/classes/controller/basic.php

Page 2: Kohana Documentaion

class Controller_Basic extends Controller

{

public function action_index()

{

$this->response->body("Hello World");

}

}

Now if you enter yoursite.com/basic/index (or yoursite.com/index.php/basic/index without URL rewritting) you should see. Hello World

Routing a URI to a ControllerKohana 3s Route Class provides you with unlimited options on how to map specifically formatted requests to specific controllers and actions.Routes should be defined in your application/bootstrap.php file or in the modules/mymodule/init.php file by calling the Route::set() method.View the Wiki section on Routing Basics to get started.

Getting Parameters From A RouteIf you have the following Route setup:

Route::set('default', '(<controller>(/<action>(/<id>)))')

->defaults(array(

'controller' => 'welcome',

'action' => 'index',

));

You can get access to the <id> parameter inside your controller:

application/classes/controller/basic.php

class Controller_Basic extends Controller

{

public function action_index()

{

$id = $this->request->param('id', NULL); // NULL is the default value

Page 3: Kohana Documentaion

$this->response->body("the ID You passed: {$id}");

}

}

How to Create and Use ViewsViews are files that contain the display information for your application. This is most commonly HTML, CSS and JavaScript but can be anything you require such as XML or Json for AJAX output. The purpose of views is to keep this information separate from your application logic for easy reusability and cleaner code.While this is true, views themselves can contain code used for displaying the data you pass into them. For example, looping through an array of product information and display each one on a new table row. Views are still PHP files so you can use any code you normally would.

Where to create your view filesView files are stored in the views folder inside your application or module application/views

modules/mymodule/views

You can create subfolders inside the views folder to better organize your files application/views/pages/about.php

application/views/products/details.php

application/views/errors/404.php

How To Use A ViewInstances of a View will typically be created inside a controller using the View::factory() method. Your view will typically be assigned to the Request->response property. public function action_index()

{

$this->response->body(View::factory('pages/about'));

}

When a View is assigned to the Request response property as in the example above it will automatically be rendered when necessary. To get the rendered result of a view you can call the Viewrender() method public function action_index()

{

Page 4: Kohana Documentaion

$rendered_view = View::factory('pages/about')->render();

$this->response->body($rendered_view);

}

A View With A ViewYou could also include a view inside another view if you wanted.

<p>This is my main view file</p>

<?php echo View::factory('pages/menu')->render(); ?>

How to Bind and Set Data in a ViewA View on it's own is just a php script. In most cases you'll want to provide your view with dynamic content that it can display. You can set and bind dynamic data to your view several different ways.

Consider the following View in /application/views/pages/about.php <h1><?php echo $title ?></h1>

<p><?php echo $date ?></p>

Assigning data to View variables public function action_index()

{

$view = View::factory('pages/about');

$view->title = "The date is";

$view->date = date('m/d/Y');

$this->response->body($view);

}

Alternatively you can set the data when creating the view

Page 5: Kohana Documentaion

public function action_index()

{

$data['title'] = "The date is";

$data['date'] = date('m/d/y');

$view = View::factory('pages/about', $data);

$this->response->body($view);

}

Binding Data to the View public function action_index()

{

$view = View::factory('pages/about')

->bind('date', $date)

->bind('title', $title);

$title = "The date is";

$date = date('m/d/Y');

$this->response->body($view);

}

Using the View set() method public function action_index()

{

$view = View::factory('pages/about')

->set('date', date('m/d/Y'))

->set('title', "The date is");

$this->response->body($view);

Page 6: Kohana Documentaion

}

Setting and Using Global Data in ViewsYour application may render several view files at once that need access to the same data. For example you may want to display a page title in both the header of your template and in the body of the page content. You can assign data to global variables using the View::set_global() and View::bind_global() methods.

Setting Global Variables View::set_global('page_title', 'This is my page title');

Binding Global VariablesBinding global variables provides some interesting ways of using data across views.

View::bind_global('page_title', $page_title );

UsageIn the following example a request for page/index would render a total of 3 views. The main template view, the page/about view and the sidebars/about view.

All three views will have access to the property $page_title and the value can be modified at any time during the request flow up until you either render a view manually or let the main request process auto render for you.

class Controller_Website extends Controller_Template

{

public $page_title;

public function before()

{

parent::before();

View::bind_global('page_title', $this->page_title);

}

}

class Controller_Page extends Controller_Website

{

Page 7: Kohana Documentaion

$this->response->body(View::factory('page/about'));

$this->page_title = 'Edit Item';

$this->template->sidebar = View::factory('sidebars/about');

}

Building a Template Driven Web Site

Template Site : Creating the TemplateStep 1 when creating a template based website with Kohana is to create the template.

By default Kohana assumes that the template file is called *template.php* and is located in the views folder.

/home/kerkness/kohana/application/views/demo/template.php

Your template file should contain the full headers and footers for your web site and echo PHP variables where dynamic content will be inserted by your controller(s). The following very basic template contains the following dynamic content.

title (string) - This is the page title

scripts (array) - An array of Javascripts required by the page

styles (array) - An array of CSS style sheets required by the template

content (string) - This is the content of the pageClick here for the source file <!doctype html>

<html lang="<?php echo I18n::$lang ?>">

<head>

<meta charset="utf-8">

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

<?php foreach ($styles as $file => $type) echo HTML::style($file, array('media' => $type)), PHP_EOL ?>

<?php foreach ($scripts as $file) echo HTML::script($file), PHP_EOL ?>

Page 8: Kohana Documentaion

</head>

<body>

<?php echo $content ?>

</body>

</html>

Your template can be as complex or as minimal as you like with as many dynamic elements as necessary.

NEXT : Extending the Template Controller

Template Site : Extending the Template ControllerStep 2 when creating a template site with Kohana should be to extend the Controller_Template class.

While this isn't absolutely necessary because you could just work with the Controller_Template directly, it

is good practice to extend the controller so that you can easily set up default values and customize output

based on request.

How our Controllers will be organized

Controller_Template extends Controller

Controller_Demo extends Controller_Template

Controller_Page extends Controller_Demo

Our custom template controller will be called demo.php and should be created in the following directory

/home/kerkness/kohana/application/classes/controller/demo.php

Here is our customized template controller

Click here for the source file

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

class Controller_Demo extends Controller_Template

{

Page 9: Kohana Documentaion

public $template = 'demo/template';

/**

* The before() method is called before your controller action.

* In our template controller we override this method so that we can

* set up default values. These variables are then available to our

* controllers if they need to be modified.

*/

public function before()

{

parent::before();

if ($this->auto_render)

{

// Initialize empty values

$this->template->title = '';

$this->template->content = '';

$this->template->styles = array();

$this->template->scripts = array();

}

}

Page 10: Kohana Documentaion

/**

* The after() method is called after your controller action.

* In our template controller we override this method so that we can

* make any last minute modifications to the template before anything

* is rendered.

*/

public function after()

{

if ($this->auto_render)

{

$styles = array(

'media/css/screen.css' => 'screen, projection',

'media/css/print.css' => 'print',

'media/css/style.css' => 'screen',

);

$scripts = array(

'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',

);

$this->template->styles = array_merge( $this->template->styles,

$styles );

$this->template->scripts = array_merge( $this->template->scripts,

$scripts );

}

Page 11: Kohana Documentaion

parent::after();

}

}

Our template controller performs two main functions.

1. Prepares default values and set up before our action is called via the before() method.

2. Modifies and verifies value after our action is called and before any response is rendered via

the after() method

In the above example the before() method sets up empty variables so that they are available for our

controllers. The after() method adds default javascript and css files which will be used by all pages of our

web site.

Next : Basic Page Controller

Template Site : Basic Page ControllerNow that we have set up a template and extended the Kohana template controller so that we can customize how our web site responds, it is now time to create an actual page controller so that we can start serving web pages.

Our page controller will be called page.php and should be created in the following directory /home/kerkness/kohana/application/classes/controller/page.php

Click here for the source fileHere is our page controller. It contains two actions, one for loading a home page and another for loading a contact page. <?php defined('SYSPATH') or die('No direct script access.');

class Controller_Page extends Controller_Demo {

public function action_home()

{

$this->template->title = __('Welcome To Acme Widgets');

Page 12: Kohana Documentaion

$this->template->content = View::factory('page/home' );

}

public function action_contact()

{

$this->template->title = __('Contact Information for Acme Widgets');

$this->template->content = View::factory('page/contact' );

}

}

Now we have to create view files for our two pages. The files will be call home.php and contact.php and should be created in the following location. /home/kerkness/kohana/application/views/page/home.php

/home/kerkness/kohana/application/views/page/contact.php

Click here for the source filesHere are two view files you can use. At the moment these are very basic but could be customized to any extent.

home.php <h1>Welcome to our homepage.</h1>

<p>We love our new Kohana web site</p>

contact.php <h1>How to contact us.</h1>

<p>We don't like to be contacted so don't bother.</p>

Routing and Request Handling

HMVC in Kohana 3.0Please note that this information is targeting version 3.0, not the current version 3.1!

Page 13: Kohana Documentaion

One of the most powerful features in Kohana 3.0 is the ability to call another request at any time during

the request flow. This layered MVC approach allows you to assemble a complex client tier and really

harness the powerful benefits of object orientation.

An optimally layered architecture:

Reduces dependencies between disparate parts of the program

Encourages reuse of code, components, and modules

Increases extensibility while easing maintainability

Some uses for HMVC design in a client-tier architecture

Modular interface elements or widgets

Application and Menu Controls

Server Interaction

Reusable Application Flows

HMVC BasicsAn easy way to think of HMVC is to think of AJAX without an extra server call. For instance, if you have

an action for AJAX that displays a list of users, you can reuse that action in other controllers, rather than

duplicating the method.

The Request FactoryHMVC comes to Kohana by way of the Request::factory() method. Using the Request factory you can

instigate and fully execute a Kohana request at any time during the request flow.

The Request::factory() method accepts a Route URI as a parameter and when combined with Kohana's

powerful Routing features brings full extensibility to any application you build.

Using the Request Factory in a ControllerThe following example shows you how to use the request factory from inside another controller. While it

doesn't fully highlight the power behind HMVC, it does show how two separate requests can be layered

together.

class Controller_Static extends Controller

{

/**

* The following action loads page.

* A sub request is called to load a dynamic menu

*/

public function action_page()

{

Page 14: Kohana Documentaion

$page_name = Request::instance()->param('page');

$this->request->response = View::factory('page/'.$page_name)

->bind('menu', $menu);

$menu = Request::factory('static/menu')->execute();

}

public function action_menu()

{

$page_name = Request::instance()->param('page');

$this->request->response = View::factory('page/menu')

->bind('links', $links);

$links = Kohana::config('menu')->$page_name;

}

}

Using the Request Factory in a ViewAnother effective way to use the Request factory is to call a request from a View. In the example below

we call a dynamic menu and a dynamic footer from a View instead of a controller.

<h1><?php echo $page_title ?></h1>

<?php echo Request::factory('page/menu')->execute()?>

Page 15: Kohana Documentaion

<div id="container">

<?php echo $content ?>

</div>

<?php echo Request::factory('page/menu')->execute() ?>

Using the Request Factory as a basis for integrating Kohana with other open source projectsIf you analyze the Kohana bootstrap.php file you'll notice that nothing magical happens until an instance

of a Request class is created when the method Request::instance() is called.

The only difference in calling Request::instance() over Request::factory() is that instance() creates a

singleton of the Request class which is intended to handle the main request and also output neccessary

response headers.

An important thing to point out is that it isn't absolutely necessary to create a singleton instance of

Request or output any headers. A Kohana request can fully execute using just the Request::factory()as

long as Kohana is initialized. This is how Kohana has been integrated with Wordpress using the Kohana-

for-Wordpress plugin.

Routing BasicsKohana 3.0s Route Class provides you with unlimited options on how to map specifically formatted requests to specific controllers and actions.Routes should be defined in your application/bootstrap.php file or in the modules/mymodule/init.php file by calling the Route::set() method.Below you can see the default Route that is predefined in the application/bootstrap.php file. Each route must have at minimum a name a uri and a set of defaults for the uri. Route::set('default', '(<controller>(/<action>(/<id>)))')

->defaults(array(

'controller' => 'welcome',

'action' => 'index',

));

This route will handle requests that are formatted in the following manner.

http://example.php/index.php/<controller>/<action>/<id>

Page 16: Kohana Documentaion

All segments of this URI request are optional. If the segment is not provided the Route will use default values.Here is the same route but with both the controller and action segments as required instead of optional. Route::set('required', '<controller>/<action>(/<id>)')

->defaults(array(

'controller' => 'welcome',

'action' => 'index',

));

A Basic Custom RouteIMPORTANT: When creating custom Routes they should always be defined before the default route. Your default route should always be defined last in your bootstrap.php.The following route will direct all requests for example.com/index.php/products/<action>/<id> to the appropriate action of an inventory controller. Route::set('products', 'products(/<action>(/<id>))')

->defaults(array(

'controller' => 'inventory',

'action' => 'index',

));

Basic Route with 2 parametersUnlike KO2, KO3 Routing default in your bootstrap does not handle 2 or more parameters like example.com/<controller>/<action>/<param1>/<param2> Route::set('default', '(<controller>(/<action>(/<id1>(/<id2>))))')

->defaults(array(

'controller' => 'welcome',

'action' => 'index',

));

A Custom Route with no optional segmentsThe following route will direct all requests for example.com/index.php/custom to the index action of the welcome controller. Route::set('custom', 'custom')

->defaults(array(

Page 17: Kohana Documentaion

'controller' => 'welcome',

'action' => 'index',

));

A Custom Route with one dynamic SegmentThe following route will direct request for example.com/index.php/about, example.com/index.php/faq and example.com/index.php/locations to the static action of the page controller.Route::set('static', '<page>', array('page' => 'about|faq|locations'))

->defaults(array(

'controller' => 'page',

'action' => 'static',

));

A Custom Route with id and slugMust be set before the 'default' routeRoute::set('idslug', '<controller>/<action>/<id>-<slug>', array('id'=>'[0-9]+', 'slug'=>'.+'))

->defaults(array('controller' => 'home','action' => 'index',

));

Ignoring Overflow In a RouteBy default a Kohana route looks like this.

controller/action/id

But what if you want your route to also support the following

controller/action/id/and/anything/else/you/want/to/add/at/random

You need to modify your default route and add a little regex in your application/bootstrap.php file. Route::set('default', '(<controller>(/<action>(/<id>(/<stuff>))))', array('stuff' => '.*'))

->defaults(array(

'controller' => 'welcome',

Page 18: Kohana Documentaion

'action' => 'index',

));

Route and Controller for Handling Static PagesKohana works extremely well for building dynamic web sites and applications. However not everything needs to be dynamic and creating a controller/action combination for every static page is a little over kill. Here is how you can create a controller and route to handle static pages and support i18n so that your site can be multilingual.

The RouteI'm going to provide two examples of Routes which will support static pages. The first one assumes that we have a set number of pages that we need to support and uses a very clean URL. The second will support any number of pages and uses a prefix 'page' in the request URI. /**

* This route supports the pages called 'about', 'faq' and 'locations'.

* Each page accessible using only its name, for example

* http://example.com/about or http://example.com/faq

*/

Route::set('static', '<page>', array('page' => 'about|faq|locations'))

->defaults(array(

'controller' => 'page',

'action' => 'static',

));

Or use a route that supports dynamic page names

/**

* This route supports any number of pages.

* Each page accessible the following URL where page_name is the

* name of the page you want to load.

* http://example.com/page/page_name

Page 19: Kohana Documentaion

*/

Route::set('static2', 'page/<page>', array('page' => '.*'))

->defaults(array(

'controller' => 'page',

'action' => 'static',

));

The ControllerThe same controller/action combination should be able to support both routes. The action will be responsible for looking at the name of the requested page and then load the appropriate view.

My example below uses the default Kohana template controller.

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

class Controller_Pages extends Controller_Template {

public function action_static()

{

// Get the name of our requested page

$page = Request::instance()->param('page');

// Assign the appropriate view file to the template content

$this->template->content = View::factory('page/'. i18n::$lang .'/'. $page );

}

}

The View TemplatesYou'll notice that in the controller that view we load uses a static property from the Kohana i18n class. i18n::$lang will return the default language for your Kohana web site and can be defined in yourapplication/bootstrap.php file.If your page name is 'about' and your default language is en-US then the controller will look for the following view file.

page/en-us/about

Page 20: Kohana Documentaion

The full path for the view file will be something like the following

/home/kerkness/kohana/application/views/page/en-us/about.php

You'll need to create view files for all the pages and languages you need to support.

Multi-language with RoutesThere are many ways to accomplish i18n functionality with Kohana. One way is to incorporate language into a Route.

For example

http://example.com/en-us/products // For English

http://example.com/fr-fr/products // For French

You can define your Route to catch the language portion of the request. The example below only allows English, French and Dutch to be requested and defaults to English.

Route::set('default', '(<lang>/)(<controller>)(/<action>(/<id>))', array('lang' => '(en-us|fr-fr|nl-nl)', 'id'=>'.+'))

->defaults(array(

'lang' => 'en-us',

'controller' => 'welcome',

'action' => 'index',

));

The language can then be set in the controller. The example below sets the language in a custom template controller.

class Controller_Website extends Controller_Template

{

public function before()

{

// Set the language

I18n::$lang = Request::instance()->param('lang');

}

Page 21: Kohana Documentaion

}

Create language files in the directory application/i18n /home/kerkness/kohana/application/i18n/fr.php

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

return array(

'Hello World' => 'Bonjour Monde',

);

Create language specific views in appropriate folders under application/views /home/kerkness/kohana/application/views/fr-fr/index.php

<p>Merci de visiter notre site Internet.</p>

<p>Voici mon contenu de homepage...

All your controllers will use the appropriate language.

class Controller_Welcome extends Controller_Website

{

public function action_index()

{

// The string 'Hello World' will be translated

$this->template->title = __('Hello World');

// Load a language specific view

$this->template->content = View::factory('page/'.I18n::$lang.'/index');

//OR use the same template for all languages

//$this->template->content = View::factory('page/index');

}

}

Page 22: Kohana Documentaion

Building a Route with Sub-directoriesWhat if you wanted to use sub-directories in your controller and dynamically support these in your routing you can use the following examples as a starting point.

Supporting a Single Sub-directoryLet's consider the following controller ( Controller_Foo_Bar )

/home/kerkness/application/classes/controller/foo/bar.php

Say you want to access this controller from the following url

http://example.com/foo/bar/action/id

You can do so with the following route.

Route::set('default', '(<directory>(/<controller>(/<action>(/<id>))))')

->defaults(array(

'directory' => 'foo',

'controller' => 'bar',

'action' => 'index',

));

Supporting Multiple Sub-directoriesWhat if you want to support multiple sub-directories with a url like the following.

http://example.com/my/sub/directory/controller/action/id

You can do so by adding a little regex to the route.

Route::set('default', '(<directory>(/<controller>(/<action>(/<id>))))', array('directory' => '.+?'))

->defaults(array(

'directory' => 'foo',

'controller' => 'bar',

Page 23: Kohana Documentaion

'action' => 'index',

));

A Little Warning !!Something to be aware of. The routes exampled above assume that you will be using sub-directories for all your controllers. If you only have a couple of controllers that are located in sub-directories it would be considered a better practice to define routes for each as in the following example.

Route::set('default', 'foo/<controller>(/<action>(/<id>))')

->defaults(array(

'directory' => 'foo',

'controller' => 'bar',

'action' => 'index',

));

Multiple Sub-directories with Listing and detail/action, & id's & slugs(I'm not the foo/bar type, so concrete examples. Delete if not allowed or change:) )

Consider the situation we want to have the following:

Browseing

url: /content/library/releases

controller: controller/content/library/browse action: action_releases

url: /content/library/labels

controller: controller/content/library/browse action: action_labels

Detail views

url: /content/library/labels/3-with+an+optional+slug

controller: controller/content/library/label action: action_index

url: /content/library/labels/3-with+an+optional+slug/edit

controller: controller/content/library/label action: action_edit

The routes

// browsing / listing

Route::set('listing', 'content/library/(<action>)',

Page 24: Kohana Documentaion

array('action' => 'releases|labels|artists|tracks|playlists'))

->defaults(array(

'directory' => 'content/library',

'controller' => 'browse',

'action' => 'tracks',

));

// single items

Route::set('items', 'content/library/(<controller>(/<id>(-<slug>)(/<action>)))',

array('id'=>'[0-9]+', 'slug'=>'.[^/]+', 'action' => 'index|edit|download'))

->defaults(array(

'directory' => 'content/library',

'controller' => 'releases',

'action' => 'index',

));

Creating a Custom 404 PageIn order to have a custom 404 page in your Kohana application you'll want to try and catch all invalid routes and direct them to a controller/action specifically setup to display a 404 message. The following example route does this.

While most custom routes should be defined before your default route, in this case the catch all should be defined after your default route. (*note: your default route will need to be more specific than the standard default route defined in the unedited application bootstrap file) (this NB is very ambiguous and gives neither example nor reference of how the default route should be edited to function properly, thereby leaving the user rather confused and unsure of where to turn.) Route::set('catch_all', '<path>', array('path' => '.+'))

->defaults(array(

'controller' => 'errors',

'action' => '404'

));

Page 25: Kohana Documentaion

Don't forget to create the controller and appropriate view file

/home/kerkness/kohana/application/classes/controller/errors.php

class Controller_Errors extends Controller

{

public function action_404()

{

$this->request->status = 404;

$this->request->response = View::factory('errors/404');

}

}

And the view file

/home/kerkness/kohana/application/views/errors/404.php

<h1>404 Not Found</h1>

Example:

// allow http://test/security/login, http://test/security/logout, http://test/security/register, http://test/security/verifyemailRoute::set('security', 'security/<action>', array('action' => 'login|logout|register|verifyemail'))

->defaults(array('controller' => 'security',

)); // allow http://test/, http://test/index, http://test/restrictedRoute::set('home', '(<action>(/<ignore>))', array('action' => 'index|restricted', 'ignore' => '.+'))

->defaults(array('controller' => 'home','action' => 'index',

)); // send everything else to a 404 pageRoute::set('catch_all', '<path>', array('path' => '.+'))

->defaults(array('controller' => 'errors','action' => '404',

));

Triggering a 404 Page Manually Todo: Add an example of throwing an exception..

Todo: Please provide details or references as to how the default route should be edited for

proper functionality.

Page 26: Kohana Documentaion

When using Kohana HMVC it is nice to differ the requests into external (the ones that come from the client) and the internal (sub-requests that are made within your application). To do so just check to see if the request is internal or external in the before() method of your template controller.<?php

class Controller_Sample extends Controller_Template {

public $internal = FALSE;

public function before()

{

parent::before();

if ($this->request != Request::instance()) {

$this->internal = TRUE;

}

}

}

Also there is a nice trick to redefine the actions so that you could have different methods for internal and externals request.

<?php

class Controller_Sample extends Controller {

public function before()

{

if ($this->internal == TRUE) {

$this->request->action = 'internal_'.$this->request->action;

}

}

public function action_index()

{

Page 27: Kohana Documentaion

// this action will be made if the request is external

}

public function action_internal_index()

{

// this action will be made if the request is internal

}

}

Pretty useful, he? You may construct the page with subrequests and you may send ajax or HTTP requests to the specific controller.

Discussion1. Won’t “$this→request === Request::instance()” suffice to test if the request is internal or not?

2. Yes. There is no need to extend the Request class. It's over kill.

How to redirect the user requestIf you want to redirect the user request to a new page or a new route you can use the redirect() method from the Request Class

Usage Request::instance()->redirect('http://kohanaphp.com');

Request::instance()->redirect('controller/action');

Request::instance()->redirect( Route::get('demo-sample')->uri(array('category'=>'books', 'id'=>5)) );

How to test the routesOften you want to test the routes you've just created. You can go to the URI, but you can also do it with a little snippet as mentioned here. The snippet looks like: // Here you define the routes

// ...

Page 28: Kohana Documentaion

Route::set('post', 'post/<id>', array('id' => '[\d]+'))

->defaults(array(

'controller' => 'post',

'action' => 'index',

));

// ...

// The URI to test

$uri = 'post/1';

// This will loop trough all the defined routes and

// tries to match them with the URI defined above

foreach (Route::all() as $r)

{

echo Kohana::debug($r->matches($uri));

}

exit;

As you can see, you place this little snippet just beneath the routes section in the bootstrap.php file and start debugging your routes. When you run this you will get something like:

array(3) (

"id" => string(1) "1"

"controller" => string(4) "post"

"action" => string(5) "index"

)

array(2) (

"controller" => string(4) "post"

"action" => string(1) "1"

)

Note: It doesn't matter which page you open, as long as the bootstrap.php is being called (which is at every page).

Page 29: Kohana Documentaion

404 Error Pages by catching ReflectionExceptionThis is just a quick guide to accurately displaying a 404 error. Using a catch-all route won't work 100% of the time, because you can have the correct Controller, but the wrong action, and it will throw a ReflectionException.

Other methods I've seen being used just catch the exception, which will also catch any errors, for example if a view file is missing.

The other benefit of this method is that you can still use class inheritance to display your page, so you can link into existing Controllers.

In my case, I have a core Controller_App which handles user Authentication, Banned users, and setting up variables in my core template.

You will first need to create your own 404 Route, it can be anything you want. 'http://mysite/error/404', 'http://mysite/controller/action/'. It's up to you, but just make sure that the page is working, functional and doesn't throw a Reflection Exception, or you will send your program into a recursive loop.404 Error Controller Exampleapplication/classes/controller/error.php

<?php defined('SYSPATH') OR die('No direct access allowed.');

class Controller_Error extends Controller_App {

public function action_404()

{

// Grab the Main Request URI

$page = $this->request->param('id', $this->request->uri());

// If your template has a title, you can set it here.

$this->template->title = '404 Page Not Found';

// Set the Request's Status to 404 (Page Not Found)

$this->request->status = 404;

Page 30: Kohana Documentaion

// Here we need to strip our error page's text from the request URI if it is there.

$pos = strpos($page, 'error/404/');

if ($pos === 0)

{

$page = substr($page, 10);

}

/* Now we're left with the normal URL, depending on how you handle your

* views, you can place this into an error page view, in my case I have

* a view which is common for displaying messages, and insert the

* message inside of it.

*/

$text = '<div class="text-center">The page you requested <strong><em>'.

$page.'</em></strong> was not found.'."<br />\n".

'<a href="/">Return Home</a></div>';

$this->template->content = View::factory('common/mainbox')

->set('content', $text);

}

}

Once again, your usage will vary. This may not be the most efficient method of doing it, but I do know that it works!

Test your error page and make sure it works. If yes you can move onto the next step.

Modifying your BootstrapThis next part means you will need to modify your bootstrap, getting this incorrect can cause problems for your whole application. I strongly suggest you create a backup.

Firstly, you will need to add a route for your errors page. For example:

// Error

Route::set('error', 'error(/<action>(/<id>))', array('id' => '.+'))

->defaults(array(

Page 31: Kohana Documentaion

'controller' => 'error',

'action' => '404',

'id' => FALSE,

));

Secondly, you can either comment this part out, or delete it, up to you.

/**

* Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].

* If no source is specified, the URI will be automatically detected.

*/

echo Request::instance()

->execute()

->send_headers()

->response;

Read over the following code to make sure you understand what is going on,

$request = Request::instance();

try

{

$request->execute();

}

catch( ReflectionException $e )

{

// URL for new route

$error_page = Route::get('error')->uri(array('action' => '404', 'id' => $request->uri()));

$new_request = Request::factory($error_page);

$new_request->execute();

$new_request->status = 404;

Page 32: Kohana Documentaion

if ( $new_request->send_headers() )

{

die( $new_request->response );

}

}

if ( $request->send_headers()->response )

{

echo $request->response;

}

I used reverse routing to generate the URL, if you want to save some CPU cycles, you can just go:$error_page = 'error/404/'.$request->uri();

or even just

$new_request = Request::factory('error/404/'.$request->uri());

Please be aware that we are using Request::factory(), not Request::instance()

Hopefully this has all worked for you as it has for me.

Using hyphen (-) in URL'sIf you prefer hyphen (-) in your project URL's, this is simple extending Kohana Request class (application/classes/request.php) to handle it:<?php defined('SYSPATH') or die('No direct script access.');

class Request extends Kohana_Request

{

public function execute()

{

$this->action(str_replace('-', '', $this->action()));

$this->controller(str_replace('-', '', $this->controller()));

return parent::execute();

Page 33: Kohana Documentaion

}

}

This will eliminate any hyphens to controllers and actions.

Allows for example a URL this-company/about-us be directed to the controller thiscompany and action aboutusHow to use the Database Module

How to enable and configure the database moduleKohana 3.0 comes with a robust module to working with databases. By default the database module supports drivers for MySQL and PHP-PDO.The database module is included with the Kohana 3.0 install but needs to be enabled before you can use it. In your application/bootstrap.php file modify the call to the Kohana::modules() method to include the database module as in the following example. Kohana::modules(array(

'userguide' => MODPATH.'userguide',

'database' => MODPATH.'database', // Database access

'pagination' => MODPATH.'pagination',

));

After the module has been enabled you will need to provide a configuration file so that the module knows how to connect to your database. An example config file can be found atmodules/database/config/database.php. Copy this config file to your application level. cp -a modules/database/config/database.php application/config/database.php

Open up the config file and make the necessary modifications for connecting to your database. The example file below shows 2 mysql connections. You can define as many database connections as necessary but you should make sure that one of the connections is named default return array

(

'default' => array

(

'type' => 'mysql',

Page 34: Kohana Documentaion

'connection' => array(

'hostname' => 'localhost',

'username' => 'dbuser',

'password' => 'mypassword',

'persistent' => FALSE,

'database' => 'my_db_name',

),

'table_prefix' => '',

'charset' => 'utf8',

'caching' => FALSE,

'profiling' => TRUE,

),

'remote' => array(

'type' => 'mysql',

'connection' => array(

'hostname' => '55.55.55.55',

'username' => 'remote_user',

'password' => 'mypassword',

'persistent' => FALSE,

'database' => 'my_remote_db_name',

),

'table_prefix' => '',

'charset' => 'utf8',

'caching' => FALSE,

'profiling' => TRUE,

),

);

A MySQL database can accept the following options for connection settings

string hostname * Ports and sockets may be appended to the hostname. eg: localhost:3306

string socket

Page 35: Kohana Documentaion

string username

string password

boolean persistent

string databaseA PDO database can accept these options for connection settings

string dsn

string username

string password

boolean persistent

string identifier

CRUD With The Query BuilderThe Kohana 3.0 Database Query Builder makes it easy to create CRUD statements for your database. The examples here use the following database structure.

CREATE TABLE `users` (

`id` int(10) unsigned NOT NULL auto_increment,

`username` varchar(30) NOT NULL,

`password` varchar(40) default NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Creating Database RecordsCreating database records requires use of the DB::insert() method. The basic format for this request is as follows. DB::insert('table_name', array('column'))->values(array('column_value'))->execute();

If the command is successful you can expect back an array containing the insert_id and the total_rows (total number of affected rows).UsageExecute the call inside a try/catch block so that you can catch any exception errors.

try

{

list($insert_id, $total_rows) = DB::insert('users', array('username','password'))

->values(array('myusername',sha1('mypassword')))

->execute();

Page 36: Kohana Documentaion

echo $insert_id .' '.$total_rows ;

}

catch ( Database_Exception $e )

{

echo $e->getMessage();

}

Reading Database RecordsReading database records requires use of the DB::select() method. The basic format for this request is as follows. // Returns a Result Object

$result = DB::select('column')->from('table_name')->execute();

// Returns an Array of results

$result = DB::select('column')->from('table_name')->execute()->as_array();

// Returns an stdClass Object of results

$result = DB::select('column')->from('table_name')->as_object()->execute();

// Returns only the first row

$result = DB::select('column')->from('table_name')->execute()->current();

You can specify the select in a number of ways like one column in the example above:

// Returns one column

$result = DB::select('column')->from('table_name')->execute()->current();

// returns 3 columns

$result = DB::select('column', 'column2', 'column3')->from('table_name')->execute()->current();

// Alias the column names

Page 37: Kohana Documentaion

$result = DB::select(array('longcolumnname1', 'col1'), array('longcolumnname2', 'aliascol2'))->from('table_name')->execute()->current();

You can select specific records by using the where() method. $result = DB::select()->from('table_name')->where('column','=','value')->execute();

There are a variety of methods available for building complex select statements. View the API documentation for more details.UsageExecute the call inside a try/catch block so that you can catch any exception errors.

public function action_select()

{

try

{

$user = DB::select()->from('users')

->where('id','=', $this->request->param('id'))

->execute()->current();

echo Kohana::debug($user);

}

catch( Database_Exception $e )

{

echo $e->getMessage();

}

}

Updating Database RecordsUpdating database records requires use of the DB::update() method. The basic format for this request is as follows. $total_rows = DB::update('table_name')->set(array('column'=>'value'))->where('column','=','value')->execute();

If the command executes successfully you will get the total number of affected rows as the result.

Page 38: Kohana Documentaion

UsageExecute the command inside a try/catch block to handle exceptions.

try

{

$total_rows = DB::update('users')->set(array('username'=>'newuser'))

->where('id','=',2)->execute();

echo Kohana::debug($total_rows);

}

catch( Database_Exception $e )

{

echo $e->getMessage();

}

Deleting Database RecordsDeleting database records requires use of the DB::delete() method. The basic format for this request is as follows. $total_rows = DB::delete('table_name')->where('column','=','value')->execute();

If the command executes successfully you will get the total number of affected rows as the result.

UsageExecute the command inside a try/catch block to handle exceptions.

try

{

$total_rows = DB::delete('users')->where('id','=',2)->execute();

echo Kohana::debug($total_rows);

}

Page 39: Kohana Documentaion

catch( Database_Exception $e )

{

echo $e->getMessage();

}

Advanced Queries with the Query BuilderThe Query Builder can make it quick and easy to build and run simple SQL queries. However some

documentation was lacking on some of the more complex queries.

Statements and ExpressionsSometimes you want to run a quick update to increase a column, such as a views or count column.

The SQL looks something like this

UPDATE `pages` SET `views` = views + 1 WHERE `id` = 1

In this case, we can use the DB::expr('') function to create the expression

DB::update('pages')

->set(array('views' => DB::expr('views + 1')))

->where('id', '=', 1)

->execute();

TransactionsWhen calling transactions, for example on an InnoDB database, our query is neither a SELECT, INSERT,

UPDATE or DELETE.

BEGIN WORK;

We can use the custom Query function to call this;

DB::query(NULL, "BEGIN WORK")->execute();

In a similar fashion, you can use the return calls from INSERT and UPDATE queries to create a

TRUE/FALSE scenario to determine if you want to COMMIT or ROLLBACK;

DB::query(NULL, "BEGIN WORK")->execute();

Page 40: Kohana Documentaion

// Array of Page Data

$page_data = array(

'id' => NULL,

'title' => 'My New Page',

);

$page = (bool) DB::insert('pages', array_keys($page_data))

->values($page_data)

->execute();

$page_cat_data = array(

'page_count' => DB::expr('page_count + 1'),

);

$page_cat = (bool) DB::update('page_categories')

->set($page_cat_data)

->where('id', '=', 1)

->execute();

if($page AND $page_cat)

{

DB::query(NULL, "COMMIT")->execute();

}

else

Page 41: Kohana Documentaion

{

DB::query(NULL, "ROLLBACK")->execute();

}

JoinsExecuting a join with the Query Builder is quite simple. In this example we've got an articles and users table, and we wish to get the user's username along with the article title.

SQL:

SELECT `articles`.`title`, `users`.`username`

FROM `articles`

JOIN `users`

ON (`users`.`id` = `articles`.`user_id`)

WHERE `articles`.`id` = 1

LIMIT 1

Query Builder:

$query = DB::select('articles.title', 'users.username')

->from('articles')

->where('articles.id', '=', 1)

->join('users')

->on('users.id', '=', 'articles.user_id')

->limit(1)

->execute();

Building Complex Select StatmentsThere are a variety of methods available for building complex select statements.

Selecting only specific columns DB::select('column1','column2')->from('table_name');

Page 42: Kohana Documentaion

SELECT `column1`, `column2` FROM `table_name`

Selecting Column AS DB::select(array('column','my_column'))->from('table_name')->compile($db);

SELECT `column` AS `my_column` FROM `table_name`

join() DB::select()->from('table_name')->join('table_2')->on('table_2.table_id', '=',

'table_name.id');

SELECT * FROM `table_name` JOIN `table_2` ON `table_2`.`table_id` = `table_name`.`id`

group_by() DB::select()->from('table_name')->group_by('column');

SELECT * FROM `table_name` GROUP BY `column`

DB::select()->from('table_name')->group_by(array('column1', 'mycol'));

SELECT * FROM `table_name` GROUP BY `column1` AS `mycol`

having() DB::select()->from('table_name')->having('column','=','value');

SELECT * FROM `table_name` HAVING `column` = 'value'

and_having() DB::select()->from('table_name')->having('column','=','value')-

>and_having('column2','=','value');

SELECT * FROM `table_name` HAVING `column` = 'value' AND `column2` = 'value'

or_having() DB::select()->from('table_name')->having('column','=','value')-

>or_having('column2','=','value');

SELECT * FROM `table_name` HAVING `column` = 'value' OR `column2` = 'value'

Page 43: Kohana Documentaion

having_open() DB::select()->from('table_name')->having_open()->having('column','=','value')

->or_having('column2','=','value')->having_close();

SELECT * FROM `table_name` HAVING (`column` = 'value' OR `column2` = 'value')

and_having_open() DB::select()->from('table_name')->where('column','=','value')->and_having_open()-

>having('column2','=','value')

->and_having('column3','=','value')->and_having_close();

SELECT * FROM `table_name` WHERE `column` = 'value' HAVING (`column2` = 'value' AND

`column3` = 'value')

or_having_open() DB::select()->from('table_name')->where('column','=','value')->or_having_open()-

>having('column2','=','value')

->or_having('column3','=','value')->or_having_close();

SELECT * FROM `table_name` WHERE `column` = 'value' HAVING (`column2` = 'value' OR

`column3` = 'value')

order_by() DB::select()->from('table_name')->order_by('column', 'ASC');

SELECT * FROM `table_name` ORDER BY `column` ASC

limit() DB::select()->from('table_name')->limit(10);

SELECT * FROM `table_name` LIMIT 10

offset() DB::select()->from('table_name')->limit(10)->offset(50);

SELECT * FROM `table_name` LIMIT 10 OFFSET 50

Page 44: Kohana Documentaion

where() DB::select()->from('table_name')->where('column','=','value');

SELECT * FROM `table_name` WHERE `column` = 'value'

and_where() DB::select()->from('table_name')->where('column','=','value')-

>and_where('column2','=','value');

SELECT * FROM `table_name` WHERE `column` = 'value' AND `column2` = 'value'

or_where() DB::select()->from('table_name')->where('column','=','value')-

>or_where('column2','=','value');

SELECT * FROM `table_name` WHERE `column` = 'value' OR `column2` = 'value'

where_open() DB::select()->from('table_name')->where_open()->where('column','=','value')

->or_where('column2','=','value')->where_close();

SELECT * FROM `table_name` WHERE (`column` = 'value' OR `column2` = 'value')

and_where_open() DB::select()->from('table_name')->where('column','=','value')->and_where_open()-

>where('column2','=','value')

->or_where('column3','=','value')->and_where_close();

SELECT * FROM `table_name` WHERE `column` = 'value' AND (`column2` = 'value' OR `column3`

= 'value')

or_where_open() DB::select()->from('table_name')->where('column','=','value')->or_where_open()-

>where('column2','=','value')

->and_where('column3','=','value')->or_where_close();

Page 45: Kohana Documentaion

SELECT * FROM `table_name` WHERE `column` = 'value' OR (`column2` = 'value' AND `column3`

= 'value')

How To Use The Pagination ModuleKohana 3.0 comes with a module to assist with the pagination of database records. Pagination refers to the process of splitting database records over numerous pages and providing the user with links to access next or previous pages.The following examples make use of the DB::select() query builder, however the Pagination module isn't tied to any type of data set. You can use the module to let users page through data regardless of the data source.

Enabling the ModuleThe Pagination module is included with the Kohana 3.0 install but needs to be enabled before you can use it. In your application/bootstrap.php file modify the call to the Kohana::modules() method to include the Pagination module as in the following example. Kohana::modules(array(

'userguide' => MODPATH.'userguide',

'database' => MODPATH.'database', // Database access

'pagination' => MODPATH.'pagination',

));

Basic UsageThe following controller loads a set of records from the database using the query builder and generates a pagination control which allows the user to browse page-by-page through the records.

public function action_page()

{

// Define our template view and bind to variables

$this->template->content = View::factory('page/list')

->bind('results', $results)

->bind('page_links', $page_links);

// Get the total count of records in the database

$count = DB::select(DB::expr('COUNT(*) AS mycount'))->from('users')->execute('alternate')->get('mycount');

Page 46: Kohana Documentaion

// Create an instance of Pagination class and set values

$pagination = Pagination::factory(array(

'total_items' => $count,

'items_per_page' => 20,

));

// Load specific results for current page

$results = DB::select()->from('users')

->order_by('id','ASC')

->limit($pagination->items_per_page)

->offset($pagination->offset)->execute();

// Render the pagination links

$page_links = $pagination->render();

}

Note: $pagination→offset is supported in v3.0.2

Advanced UsageYou can customize how the pagination class will function and render your links by modifying what configuration you define when creating an instance of the class. Consider the following example.

$pagination = Pagination::factory(array(

'current_page' => array('source' => 'query_string', 'key' => 'p'),

'total_items' => $count,

'items_per_page' => 40,

'view' => 'pagination/page_links',

'auto_hide' => FALSE,

));

Page 47: Kohana Documentaion

Using Configuration FileThe Pagination class uses a config file to determine the default setup to use. This configuration is merged with what ever config settings are defined when creating a new instance of the class.

To create your own configuration file, copy the provided config file from modules/pagination/config/pagination.php to application/config/pagination.php cp modules/pagination/config/pagination.php application/config/pagination.php

Here is an example of a customized configuration

return array(

'default' => array(

'current_page' => array('source' => 'query_string', 'key' => 'p'),

'total_items' => 0,

'items_per_page' => 40,

'view' => 'pagination/pretty',

'auto_hide' => FALSE,

),

);

Config Settings Explained

current_page array() : Expects an array that defines a source and key for the current page.

The source can be either route or query_string and the key can be any string you want.

If source = route then the Pagination class will look for the key in the current Route

If source = query_string then the Pagination class will look key in the current query

string

total_items int : Should contain the total count of all items to be paged through. This is the only

config setting which should be set each time an instance of the Pagination class is created.

items_per_page int : The number of items that should be displayed per page

view string : This is the View file which should be used to render the links for paging through the

records

auto_hide boolean : If set to true, the render() method will return nothing when the total page

page count is less than or equal to 1.

Page 48: Kohana Documentaion

How To Close a Database ConnectionIf you ever find yourself in a situation when you need to forcefully close a database connection ( perhaps

when working with php-cli ) you have a couple of options.

foreach(Database::$instances as $db)

{

$db->disconnect();

unset($db);

}

Database::$instances = array();

OR just call

Database::$instances = array();

Working with Sessions and CookiesKohana 3.0 provides a couple of classes that make it easy to work with both Cookies and Session. At a high level both Sessions and Cookies provide the same function. They allow the developer to store temporary or persistent information about a specific user's action for later retrieval.

When to use Cookies

Cookies should be used for storing non-private data that is persistent for a long period of time.

For example storing a user id or a users language preferenceWhen to use Session

Sessions should be used for storing temporary or private data.

Very sensitive data should be stored using the Session class with Kohana Database or Native

adapters. If the Cookie adapter is used it should always be encrypted.For more information on best practices with session variables view this info on The seven deadly sins of sessions

How to set Session and Cookies Data // Setting a Cookie

Page 49: Kohana Documentaion

Cookie::set('key_name', 'value');

Cookie::set('user_id', $user_id);

// Setting a Session

Session::instance()->set('key_name', 'value');

Session::instance()->set('user_id', $user_id);

How to get Session and Cookies Data // Getting Cookie Data

$value = Cookie::get('key_name', 'default value');

$value = Cookie::get('user_id', NULL);

// Getting Session Data

$value = Session::instance()->get('key_name', 'default value');

$value = Session::instance()->get('user_id', NULL);

How to Delete Session and Cookies Data // Deleting a Cookie

Cookie::delete('key_name');

Cookie::delete('user_id');

// Deleting a Session variable

Session::instance()->delete('key_name');

Session::instance()->delete('user_id');

If you're using sessions you may want to delete or destroy the entire session.

if( Session::instance()->destroy() )

{

echo "Session has been completely removed";

}

Setting Properties for your CookiesCookies use several properties which help to determine how the data is encrypted and what web sites or domains can access it. These properties are set as static properties of the Cookie class.

Page 50: Kohana Documentaion

// Set the magic salt to add to a cookie

Cookie::$salt = 'kookykookie';

// Set the number of seconds before a cookie expires

Cookie::$expiration = 43200;

// Restrict the path that the cookie is available to

Cookie::$path = '/';

// Restrict the domain that the cookie is available to

Cookie::$domain = 'www.kerkness.ca';

// Only transmit cookies over secure connections

Cookie::$secure = TRUE;

// Only transmit cookies over HTTP, disabling Javascript access

Cookie::$httponly = TRUE;

Working with Different Session AdaptersWhen creating or accessing an instance of the Session class you can decide which session adapter you wish to use. The session adapters that are available to you are

Native : Stores session data in the default location for your web server. For example if you're

running PHP on Apache2 the default is to store session data in a file at a location set in your

php.ini file.

Database : Stores session data in a database (requires the Database module)

Cookie : Stores session data in a local cookie.The default adapter is 'native' so you don't need to do anything to use native sessions. If you're using either the Database or the Cookie adapter you need to define the adapter type when callingSession::instance() // Cookie Adapter

Session::instance('cookie')->set('key_name', 'value');

$value = Session::instance('cookie')->get('key_name');

// Database Adapter

Session::instance('database')->set('key_name', 'value');

$value = Session::instance('database')->get('key_name');

Database Session Schema

Page 51: Kohana Documentaion

If you're using the session Database adapter then you need to have the following table structure defined in your database.

CREATE TABLE `sessions` (

`session_id` VARCHAR( 24 ) NOT NULL,

`last_active` INT UNSIGNED NOT NULL,

`contents` TEXT NOT NULL,

PRIMARY KEY ( `session_id` ),

INDEX ( `last_active` )

) ENGINE = MYISAM ;

Configuring Your Session AdaptersYou can apply configuration information to each of the Kohana session adapters by creating a session config file in the following location

APPPATH/config/session.php

The following configuration settings are possible for each adapter.

Cookie Sessions

name : Sets the cookie name

encrypted : Boolean to flag if cookie should be encrypted

lifetime : Number of seconds the cookie should be kept for

Native Sessions

name : Session name

encrypted : Boolean to flag if the session data should be encrypted

lifetime : Number of seconds the session should be valid for

Database Sessions

group : Database connection to use ( as defined in APPPATH/config/database.php )

table : Table name to store session data in. Default is 'sessions'Here is an example of a config file which sets all the available options for each adapter

return array(

'cookie' => array(

'name' => 'cookie_name',

'encrypted' => TRUE,

Page 52: Kohana Documentaion

'lifetime' => 43200,

),

'native' => array(

'name' => 'session_name',

'encrypted' => TRUE,

'lifetime' => 43200,

),

'database' => array(

'group' => 'default',

'table' => 'table_name',

),

);