kohana php framework

161
What is Kohana? Kohana is a PHP5 framework that uses the Model View Controller architectural pattern. It aims to be secure, lightweight, and easy to use. Features 1. Strict PHP5 OOP. Offers many benefits: visibility protection, automatic class loading, overloading, interfaces, abstracts, singletons, etc. 2. Community, not company, driven. Kohana is driven by community discussion, ideas, and code. Kohana developers are from all around the world, each with their own talents. This allows a rapid and flexible development cycle that can respond to new bugs and requests within hours. 3. GET, POST, COOKIE, and SESSION arrays all work as expected. Kohana does not limit your access to global data, but provides XSS filtering and sanity checking of all global data. 4. Cascading resources, modules, and inheritance. Controllers, models, libraries, helpers, and views can be loaded from any location within your system, application, or module paths. Configuration options are inherited and can by dynamically overwritten by each application. 5. No namespace conflicts. Class suffixes and prefixes are used to prevent namespace conflicts. 6. Auto-loading of classes. All classes in Kohana are automatically loaded by the framework, and never have to be manually included. 7. API consistency. Classes that require access to different protocols use “drivers” to keep the the visible API completely consistent, even when the back-end changes. 8. Powerful event handler. Kohana events can transparently be: added, replaced, or even removed completely. Goals To be secure means to use best practices regarding security, at all times: Kohana comes with built-in XSS protection, and can also use HTMLPurfier  as an XSS filter. All data inserted into the database is escaped using database-specific functions, like mysql_real_escape_string , to protect against SQL injection  attacks. magic quotes  are disabled by Kohana. All POST, GET, and COOKIE data is sanitized to prevent malicious behavior. To be lightweight means to provide the highest amount of flexibility in the most efficient manner: Kohana uses convention over configuration  as much as possible. Sane defaults and highly optimized environment detection routines allow Kohana to run in almost any PHP5 environment. Loose coupling    is used to always load the minimum number of files, reducing resource usage. A clean API and using native functions whenever possible makes Kohana one of the fastest PHP5 frameworks available. To be easy to use means to provide understandable API and usage documentation, based on 

Upload: anupong-hutawarakorn

Post on 28-Mar-2016

459 views

Category:

Documents


13 download

DESCRIPTION

Document basic KOHANA PHP Freamwork

TRANSCRIPT

Page 1: KOHANA PHP framework

What is Kohana?Kohana is a PHP5 framework that uses the Model View Controller architectural pattern. It aims to be secure, lightweight, and easy to use.

Features1. Strict PHP5 OOP. Offers many benefits: visibility protection, automatic class loading,

overloading, interfaces, abstracts, singletons, etc.2. Community, not company, driven. Kohana is driven by community discussion, ideas, and

code. Kohana developers are from all around the world, each with their own talents. This allows a rapid and flexible development cycle that can respond to new bugs and requests within hours.

3. GET, POST, COOKIE, and SESSION arrays all work as expected. Kohana does not limit your access to global data, but provides XSS filtering and sanity checking of all global data.

4. Cascading resources, modules, and inheritance. Controllers, models, libraries, helpers, and views can be loaded from any location within your system, application, or module paths. Configuration options are inherited and can by dynamically overwritten by each application.

5. No namespace conflicts. Class suffixes and prefixes are used to prevent namespace conflicts.

6. Auto­loading of classes. All classes in Kohana are automatically loaded by the framework, and never have to be manually included.

7. API consistency. Classes that require access to different protocols use “drivers” to keep the the visible API completely consistent, even when the back­end changes.

8. Powerful event handler. Kohana events can transparently be: added, replaced, or even removed completely.

GoalsTo be secure means to use best practices regarding security, at all times:

• Kohana comes with built­in XSS protection, and can also use HTMLPurfier as an XSS filter.• All data inserted into the database is escaped using database­specific functions, like

mysql_real_escape_string, to protect against SQL injection attacks. magic quotes are disabled by Kohana.

• All POST, GET, and COOKIE data is sanitized to prevent malicious behavior.

To be lightweight means to provide the highest amount of flexibility in the most efficient manner:

• Kohana uses convention over configuration as much as possible.• Sane defaults and highly optimized environment detection routines allow Kohana to run in

almost any PHP5 environment.• Loose coupling is used to always load the minimum number of files, reducing resource

usage.• A clean API and using native functions whenever possible makes Kohana one of the fastest

PHP5 frameworks available.

To be easy to use means to provide understandable API and usage documentation, based on

Page 2: KOHANA PHP framework

community feedback.

MVCKohana uses the Model View Controller architectural pattern. This keeps application logic separate from the presentation and allows for cleaner and easier to work with code.

In Kohana this means:

• A Model represents a data structure, usually this is a table in a database.• A View contains presentation code such as HTML, CSS and JavaScript.• A Controller contains the page logic to tie everything together and generate the page the

user sees.

Features• Highly secure• Extremely lightweight• Short learning curve• Uses the MVC pattern• 100% UTF­8 compatible• Loosely coupled architecture• Extremely easy to extend

Technology• Strict PHP5 OOP• Simple database abstraction using SQL helpers• Multiple session drivers (native, database, and cookie)• Powerful event handler allows small modifications dynamically• Originally based on CodeIgniter

CreditsMost of the Kohana source code is written by the Kohana Team. There are a few notable credits, however.

CodeIgniterKohana was originally a fork of CodeIgniter (CI), which is an open­source product of EllisLab. There are still many similarities between CI and Kohana, particularly in naming conventions and filesystem design, but all of the code is either new or completely rewritten.

CodeIgniter is © 2006 EllisLab, Inc.

phputf8All of the Kohana UTF­8 functions are ported from the phputf8 project.

Page 3: KOHANA PHP framework

phputf8 is © 2005 Harry Fuecks.

PopoonThe default XSS filter used by Kohana was originally created by Christian Stocker for the popoon framework. The original file is called externalinput.php.

popoon is © 2001­2006 Bitflux GmbH

HTML PurifierThe alternative XSS filter used by Kohana is HTML Purifier. This is an optional download.

HTML Purifier is © 2006­2007 Edward Z. Yang

SwiftMailerThe recommended way to send emails in Kohana is using SwiftMailer. This is an optional download.

SwiftMailer is © Chris Corbyn

PHP MarkdownMarkdown is a simple text­to­HTML formatting tool. Kohana includes PHP Markdown as an optional download.

PHP Markdown is © 2006 Michel Fortin

Those who cannot remember the past are condemned to repeat it. George Santayana

HistoryThe history of Kohana is told backwards, because we are looking forward.

Kohana 2.1.x• February 7, 2008 ­ Release of Kohana 2.1.1• February 5, 2008 ­ Release of Kohana 2.1

Kohana 2.0November 2007

Kohana version 2.0 is released. PHP5 based. New fully OOP framework, no legacy code, includes modules, built on the cascading resources concept.

The Good Old DaysSeptember ­ October 2007

Page 4: KOHANA PHP framework

We get a BDFL, decision to go PHP5 only, new life, new goals. Almost total rewrite undertaken by developers. (All three of them)

The Worst of TimesAugust 2007. Our Project leader goes walkabout, not much happens.

Kohana 1.0June ­ July 2007 Kohana is re­released as version 1.0, without documentation.

Lots of ideas and discussions on the way forward,

KohanaJune 2007.

A new Name, forum, Trac.

In The BeginningBlueFlame, a community fork of CodeIgniter is released.

Reactions and responses. The fork splits.

May 31 2007 BlueFlame announced

Before The BeginningUp until May 2007

The founding members of Kohana are from the Codeigniter community.

Our initial happiness, and later unhappiness, with CI.

Basic RequirementsKohana will run in almost any environment with minimal configuration. There are a few minimum server requirements:

1. Server with Unicode support2. PHP version >= 5.1.33. An HTTP server. Kohana is known to work with: Apache 1.3+, Apache 2.0+, lighttpd, and

MS IIS

Optionally, if you wish to use a database with Kohana, you will need a database server. There are database drivers for MySQL and PostgreSQL, with addition drivers planned.

Required Extensions1. PCRE must be compiled with –enable-utf8 and –enable-unicode-properties

for UTF­8 functions to work properly.

Page 5: KOHANA PHP framework

2. iconv is required for UTF­8 transliteration.3. mcrypt is required for encryption.4. SPL is required for several core libraries. 1)

Recommended Extensions1. mbstring will dramatically speed up Kohana's UTF­8 functions. However, note that the

mbstring extension must not be overloading PHP's native string functions!

Install KohanaKohana is installed in several easy steps:

1. Download a copy of Kohana.2. Unzip the package you downloaded. This should create a kohana directory.3. Upload the Kohana files to your webserver, placing index.php in the directory that you

would like Kohana accessible from.4. Edit the global configuration file application/config/config.php5. Make the application/logs directory writeable. Chmod to 666.6. Make the application/cache directory writeable if you use the cache library. Chmod

to 666.7. Test your installation by opening the URL you set as the base_url in your favorite

browser

If you see the Welcome page, your Kohana installation is complete!

Removing index.php from URL'sIf you want really clean URL's and therefore remove the index.php in each URL this is possible.

• Tutorial ­ Remove index.php for Apache webserver

Additional ConfigurationYou can provide your installation with additional configuration by copying files from the system/config directory to the application/config directory. For example if you want to configure a database connection, you can copy over system/config/database.php to application/config/database.php and edit the database connection details.

After installationAfter installation you're ready to build your first web application with Kohana. If you're new to Kohana you should first read all articles in the user guide under the 'General' section.

Experiencing Problems?If you were not able to view the Kohana Welcome page on your server after installing, please read the Troubleshooting page of the user guide, visit the Kohana Wiki, or ask for assistance in the community forums.

Page 6: KOHANA PHP framework

[moveTo: Troubleshooting] The Kohana Team tries to make sure that Kohana is as free from bugs as possible. If you have found a bug, please report it.

For Experienced UsersTo use a multi­site Kohana install, simply follow these steps.

1. Download a copy of Kohana.2. Put the system folder somewhere on your server, preferably outside of your webserver's

document root.3. Delete the system folder in your current application.4. For your application's index.php file, change the $kohana_system variable to the

relative or absolute path of where you put the system folder.5. You can now point all of your applications to this one system folder for easy upgrades. This

makes your life a whole lot easier when you have 10+ kohana sites on your server.

Moving system and application directory out of webroot'webroot' is defined as the top level directory to which a webserver will allow public access. A correctly configured server will not allow public access to files or directories above webroot in the directory tree.

It is considered a good security practice to move application, system and modules out of the webroot, to prevent potential public access, should PHP be disabled, or your webserver is compromised. Kohana enables you to place the index.php in the webroot, and all other files outside of it. Static content, such as stylesheet, image and javascript files, are typically placed within webroot.

In a few steps this can be accomplished

1. Move the directories out of the webroot but leave index.php in2. Open index.php file in an editor3. Set the variable $kohana_application to the application directory you're using (must

contain config/config.php file)4. Set the variable $kohana_system to the system directory you're using

Note that moving the system directory out of webroot, also makes it more easily accessible by multiple Kohana applications. So you can use the same system for multiple applications. This allows for easy upgrades. Simply refer to the same system in the $kohana_system in application A, B etc.

Upgrading• 2.1 to 2.2 • 2.0 to 2.1

Basic InstructionsThese instructions assume that you have not edited your system folder in any way. If you have then

Page 7: KOHANA PHP framework

you will need to apply your changes again after upgrading if you use this method.

1. Delete the contents of your system folder.2. Replace it with the system folder from the version you wish to upgrade to.3. Follow the instructions from the relevant pages for your upgrade in the list above.

2.1 to 2.2 Upgrading

Configuration• preload in config.php has been removed. You must now manually instance the

libraries you want to use.

Libraries• Loader library has been removed. Libraries and models must now be created using the

following syntax: $example = new Example(); and $example = new Example_Model();

• The Pagination create_links() method has been renamed to render()

2.0 to 2.1 UpgradingThere are a number of changes to the main 'index.php' file and the 'config.php' system file. The quickest way to upgrade is make a backup of your 'index.php' and your application 'config.php' file. Call the backups file_name_version.of.Kohana. e.g. index.php_2.0.

You could consider naming your system folder with the version number: 'system_2.1.1' rather than copying the new one over the top. You can then simply revert to a previous version if there are any issues.

Install the new 'index.php' and 'application/config.php' files, and update any values in them to reflect the changes you made in your original files. The '$kohana_system' should point to the new versioned system folder.

Then continue with the changes in other files (if needed) stated below.

This method is more reliable than making incremental changes to existing files based on a list ­ and you can simple swap back to the old version if things go wrong.

Configuration• Changes to config/config.php:

• display_errors has been added.• output_compression has been added.• include_paths has been renamed to modules.• autoload has been renamed to preload.

• Changes to config/session.php:• name should only contain alphanumeric characters with at least one letter.• gc_probability has been added.

• Changes to config/database.php:

Page 8: KOHANA PHP framework

• show_errors has been removed.

Helpers• Helpers must be renamed from helper_name to helper_name_Core if they need to

be extended.• The parameter to add index.php from the URL in html helpers now defaults to false, it

needs to be specified as TRUE if you require it.

Validation• trim, md5, sha1 Validation rules must now be preceded by = (e.g. '=trim').• Validation rule 'regex' must now specify the delimiter.

Database• join($table, $cond, $type) has changed to join($table, $key, $value, $type).

• $query→num_rows() has been removed. Use count(query) instead.

Deprecated stuff• Use http_build_query() instead of html::query_string().• Use $this→pagination→sql_offset instead of $this→pagination→sql_offset().

• Use $this→pagination→sql_limit instead of $this→pagination→sql_limit().

TroubleshootingProgramming is art? So is debugging! A few tips to keep your code bug free and how Kohana can help.

• See what you're doing. Kohana makes this one easy:• Throw variables at Kohana::debug().• Turn on the Profiler to see global variables and the executed queries.

• Eliminate possible causes of the bug. Isolate the problem.• Check the Kohana log files.• If your using MySQL turning on query logging will help you understand what queries

Kohana is running on your database.

Can't figure things out on your own?

• Post your problem in the Kohana Forum (after having searched first, of course).• Drop in at #kohana on irc.freenode.net

Deploying Kohana to Production:Here are a few items you should keep in mind before deploying your Kohana application to a

Page 9: KOHANA PHP framework

production environment.

1. Remove the various demo and example controllersKohana bundles a various demos and example controllers to help users when getting started. Here are a few that should be removed:

• application/controllers/examples.php• application/controllers/welcome.php (if it is not used)• modules/auth/controllers/auth.php (if enabled in $config['modules'])• modules/forge/controllers/forge_demo.php (if enabled in

$config['modules'])

2. Modify your configuration filesKohana provides various default configuration files in the system/config directory. Since Kohana utilizes a cascading file system, you have the option to either utilize the default configuration file versions or override these files with your own custom versions by creating a copy in the application/config directory.

Modify your application/config.php:

• change $config['site_domain'] from your development setting to the production domain.

• set $config['display_errors'] = FALSE; to disable error messages from being displayed. You can still check error messages in your log file. Check your settings in config/log.php to be sure.

You should always try to create custom versions of the following files:

• system/config/routes.php ­ set your $config['_default'] to your default controller

• system/config/encryption.php ­ change the default $config['key']• modules/auth/config/auth.php ­ change the default salt offsets in $config['salt_pattern'] (if you use the Auth module)

• system/config/cookie.php ­ set your $config['domain']• system/config/session.php ­ set or verify $config['driver'], $config['name'], $config['encryption'], $config['expiration']

You should also consider creating custom versions of the following files:

• system/config/database.php ­ configure your custom database connections (if required)

• system/config/log.php ­ set your $config['threshold'] = 1;. This sets your log threshold to a suitable level for production. Higher threshold levels will log less critical notices and information, but can slow down your application.

3. Move Kohana core directories outside of the document rootIf your host does not allow this structure, use an .htaccess file to protect the core directories.

Although this is an optional step and not required by Kohana, it is considered a good security practice to place as few files as possible in your public web server document root directory. Since most web hosts give you access to at least one level above the web server document root, this should

Page 10: KOHANA PHP framework

not be a problem.

Moving your core Kohana directories also gives you the ability to utilize one central Kohana codebase on your server that can be shared by multiple websites. You could also create a set of common modules used across all of your web sites.

To accomplish this in Kohana, do the following:

1. move your Kohana system, application, and modules directories at least one level above your document root directory (typically public_html or www).

2. modify the following lines in your index.php file: • $kohana_application = '../application';• $kohana_modules = '../modules';• $kohana_system = '../system';

Note: This example assumes one­level above public_html, however, you can use relative or absolute directories when specifying directory locations.

Your final directory structure will look similar to this:

yourdomain_root_directory +- application +- system +- modules +- public_html (web server document root) | - index.php | - .htaccess

Removing index.php From URLsRemoving the index.php from your website URLs look better, and can help with SEO.

Note: This tutorial only focuses on Apache, but can be adapted for other HTTP servers.

.htaccess

We should start out by reminding you that in programming and computing there is always more than one way to accomplish the same job. The same goes for this particular task and, as is always the case, each has its own pros and cons. Let's look at a few to help you decide which is best for your situation.

First, you will need to create a .htaccess document to enable URL rewriting:

# Turn on URL rewritingRewriteEngine On

# Put your installation directory here:# If your URL is www.example.com/, use /# If your URL is www.example.com/kohana/, use /kohana/RewriteBase /

# Do not enable rewriting for files or directories that existRewriteCond %REQUEST_FILENAME !-fRewriteCond %REQUEST_FILENAME !-d

# For reuests that are not actual files or directories,

Page 11: KOHANA PHP framework

# Rewrite to index.php/URLRewriteRule ^(.*)$ index.php/$1 [PT,L]

This example is quite dynamic in that you can add files and directories to your document root as you desire and you'll never need to modify the rewrite rules. Any files and directories that exist under your document root will be served. If a request is made for a non­existant file or directory (which is really what the index.php­less Kohana URLs are), the request is rewritten to be routed through index.php transparently. If it can be routed by Kohana, the page is served. Finally, if it wasn't a request for an existing file or directory and could not be routed by Kohana, a Kohana error page (ex: 404) is displayed. So you not only have dynamic rewrite rules, but you get consistency in your error pages site wide.

However, this approach does not protect your more sensitive an unintended PHP files against access. So someone could enter, for example, http://www.example.com/application/views/ and get a list of all your view files. Ideally, you should never have your system or application directories, or any other files you do not want accessed, under your document root. But some servers are setup such that your access to the server is restricted to document root and you have no choice. Read "Moving system and application directory out of webroot" at http://doc.kohanaphp.com/installation to learn how to move system/ and application/ out of your document root. If you find that you do not have proper access on your server to change your file system setup, continue on in this tutorial for other options.

.htaccess

Let's protect against direct access to these files:

# Turn on URL rewritingRewriteEngine On

# Put your installation directory here:# If your URL is www.example.com/kohana/, use /kohana/# If your URL is www.example.com/, use /RewriteBase /kohana/

# Protect application and system files from being viewedRewriteCond $1 ^(application|system)

# Rewrite to index.php/access_denied/URLRewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

# Do not enable rewriting for other files that existRewriteCond %REQUEST_FILENAME !-fRewriteCond %REQUEST_FILENAME !-d

# Rewrite to index.php/URLRewriteRule ^(.*)$ index.php/$1 [PT,L]

controllers/access_denied.php

Because we are rewriting the URL to index.php/access_denied/, we will need a Controller to handle these URLs. Let's create one now:

Page 12: KOHANA PHP framework

<?php

class Access_denied_Controller extends Controller

function _remap() // Attempted access path, with "access_denied/" removed $path = preg_replace('|^access_denied/|', '', $this->uri->string());

// Display an error page throw new Kohana_User_Exception ( 'Direct Access Denied', 'The file or directory you are attempting to access, <tt>'.$path.'</tt>, cannot be accessed directly. '. 'You may return to the '.html::anchor('', 'home page').' at any time.' );

Now, when a user attempts to access any file or directory inside of application/ or system/, an error page will be displayed.

Now we have a good, working solution that keeps index.php our of our URL, and prevents access to protected files. However, we can still make this more secure, by only allowing specific files to be displayed, and rewriting everything else.

.htaccess

# Turn on URL rewritingRewriteEngine On

# Put your installation directory here:# If your URL is www.example.com/kohana/, use /kohana/# If your URL is www.example.com/, use /RewriteBase /kohana/

# Protect application and system files from being viewedRewriteCond $1 ^(application|system)

# Rewrite to index.php/access_denied/URLRewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

# Allow these directories and files to be displayed directly:# - index.php (DO NOT FORGET THIS!)# - robots.txt# - favicon.ico# - Any file inside of the images/, js/, or css/ directories

Page 13: KOHANA PHP framework

RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|images|js|css)

# No rewritingRewriteRule ^(.*)$ - [PT,L]

# Rewrite all other URLs to index.php/URLRewriteRule ^(.*)$ index.php/$1 [PT,L]

Now we are really done. You can change the allowed files and directories to whatever your own, specific needs are.

Note: Don't feel like you have to use the most secure solution, or any of these solutions. Choose the .htaccess file that best suits your needs. Each of the examples here will work better for some situations than others. If you want more information about mod_rewrite, check the Apache Documentation.

MigrationUsers of Kohana version 1.x (“Blueflame”) or CodeIgniter 1.x migrating to Kohana 2.0 can follow these steps to migrate their application.

InstallationStarting with a fresh Kohana install, delete application folder, and copy your existing application folder to the same location.

ConfigurationRemove your old config folder.

1. Copy the application/config directory from Kohana 2.x to application/config

2. Edit application/config/config.php, the main configuration files for your application

3. Review the User Guide: Configuration page

LoggingThe logs directory needs to be writable by the webserver or you can turn logging off.

Class NamesRename all your controllers to NAME_Controller. For example, if your old controller was Page, make it Page_Controller.

Make your Controller contructors PHP5 if needed:

1. function __construct() instead of function Page()2. parent::__construct() instead of parent::Controller()

Page 14: KOHANA PHP framework

3. Note: This also applies to Models!

Rename all your models to NAME_Model

1. For example, if your old model was PageModel, make it Page_Model2. Change all your model loads to just model name: $this→load→model('page')3. If you add a __construct() function, be sure to call parent::__construct()

Libraries

Base ControllersIf you have a base controller for your application (in the libraries folder) your will need to:

1. Change the MY_Controller extends Controller to Controller extends Controller_Core

2. Change references to MY_Controller in your controllers to Controller3. Use the PHP5 syntax for the constructor in your base controller

URIThe CI function uri_to_assoc($offset) becomes segment_array($offset,$associative) with $associative set to TRUE.

OtherClass names need to have _Core appended to them and be capitalized. The file names should also have the same caps as the class name (without the core).

References to those classes need to be capitalized to match the library calls (without the core).

$this→load→ is deprecated. Kohana uses auto loading so you can instantiate an object (e.g. new View()) without including the class first.

HelpersChange all your helper calls to the new syntax: helper::function()

1. Example: html::anchor() instead of anchor()2. Example: url::base instead of base_url()3. Example: form::open() instead of form_open()4. The default helpers are available in system/helpers

If you have custom helpers they need to be changed. Assuming your helper file is foo.php:

1. wrap all the functions in the file in class foo 2. prepend public static in front of all the function names

Calls are now made via foo::function().

Note also that the CodeIgniter helpers and libraries typically have this line at the top of the script:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

This is not valid for Kohana so if you have copied this line for your own helpers etc you need to

Page 15: KOHANA PHP framework

change it to the following to work in Kohana:

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

ViewsViews are now treated somewhat differently. Instead of being “flat” files, views are now objects. This allows much greater flexibility, and easier “view­in­view” handling.

// Load the view and set the $title variable$view = new View('template', array('title' => 'User Details')); // Sets the $username variable in the view$view->username = 'JohnDoe'; // Sets the $visits variable to another view$view->visits = new View('user/visits', array('user_id' => 3)); // Renders the view to a string$str_view = $view->render(); // Displays the view$view->render(TRUE);

Note: Using print or echo on a View will cause it to render into a string. This is very useful in Views:

<!-- This example is the "template" view from above --><h1><?php echo $title ?> for <?php echo $username ?></h1><div id="visits"><?php echo $visits ?></div>

In the above example, a View object, $visits, was used as a string. This syntax is encouraged because it is very short and readable when mixed with HTML.

ModelsThere is a important note, in CI you can use the $this in the model and you have the same libraries as your controller, in kohana only the db library is loaded on a model. If you need more libraries you have two options:

// Create a new object with the library$uri = new Uri;$value = $uri->segment(3);// Can not use $this->uri->segment(3) as used in CI // Use the instance of your controller$value = Kohana::instance()->uri->segment(3);

Page 16: KOHANA PHP framework

Reference

Page 17: KOHANA PHP framework

General

Page 18: KOHANA PHP framework

Kohana Filesystem

File typesStrictly from Kohana's interpretation of MVC­Lh (MVC ­ Libraries helpers):

• Models are used to represent a specific piece of data, such as a database row in a specific table, or an HTML form.

• Views as used as data­to­HTML rendering layers.• Controllers are used as the “entry point”, and handle how a URI is converted into an

application.• Libraries are used for as a tool that operate on some form of pre­existing data, either in the

form of an array (e.g., Session, Validation, Input) or some other data structure, such as ORM (database table) or Archive (filesystem).

• Helpers are used for simple, repetitive tasks, such as creating HTML tags, making a URI into a URL, or validating an email address.

In addition, Kohana adds the following supporting structure:

• Configuration files, simple static arrays that are accessed by convention (file.key)• Language (i18n) files, access the same as config (file.key)• Hooks, which can be used to “hook into” Kohana during very early processes

The BasicsFirst of all you should get acquainted with the directory structure of a default Kohana installation. Once you have unpacked it you will see this (note: the contents of your modules directory will vary according to the options you select on the download page):

root +- application | +- cache | +- config | +- controllers | +- helpers | +- hooks | +- libraries | +- logs | +- models | +- views | +- modules | +- media | +- config | +- controllers | +- helpers | +- libraries | +- ..... +- system | +- config | +- controllers | +- core | +- helpers | +- i18n | +- libraries

Page 19: KOHANA PHP framework

| +- models | +- vendor | +- views | +- index.php

You will notice that a lot of the directories in the application and system directories are exactly the same. This is because Kohana has a cascading filesystem.

CascadingThe Kohana filesystem is made up of a single directory structure that is mirrored in all directories along what we call the include path, which goes as follows:

application > modules > system

Files that are in directories higher up the include path order take precedence over files of the same name lower down the order.

For example, if you have a view file called layout.php in the application/views and system/views directories, the one in application will be returned when layout.php is searched for as it is highest in the include path order. If you then delete that file from application/views, the one in system/views will be returned when searched for.

See the cascading filesystem in action.

ModularThe Kohana filesystem is also modular. This means that custom directories can be inserted along the include path to be scanned when a file is searched for.

See Modules on how to set these up.

The application and system directories can be thought of as hardcoded modules. They are treated no differently from regular modules apart from the exceptions listed below.

ExceptionsThere are 2 main exceptions in the filesystem:

config.php MUST reside in the application/config directory. It will not be read if it exists within a module or the system directory. The reason for this is that it contains the modules setting which must be read before all others so the framework knows where the rest of the config files are along the include path.

The core files as part of system/core are also not cascading. They are hardcoded into the Kohana startup procedures and will not be overridden by files higher up the include path.

Configuration and i18n FilesThese files are special as their content entries are merged when multiple files of the same name are found along the include path. Entries in files greater up the order still override those of which are in files lower down.

Page 20: KOHANA PHP framework

See Configuration and Internationalization for more information on this.

Built in directories

cacheBy default, the Cache library uses this directory to store its caches when using the File driver. It should also be where you store any custom cached data from your application.

configAll configuration files that are read by the Config class must be stored here.

controllersAll controllers to be directed to by the router must go in here.

helpersSee Helpers.

hooksSee Hooks.

i18nLanguage files read by Kohana::lang() are stored here. They are split up into sub­directories using the country code and locale as the name. See Internationalization.

librariesSee Libraries.

logsBy default, log files generated by the Log class are stored in the application/logs directory.

modelsSee Models.

vendor3rd party libraries and scripts that are not integrated into Kohana should be stored here. See Libraries for more information.

viewsSee Views.

Page 21: KOHANA PHP framework

ConfigurationInformation on retrieving and setting configuration items can be found on the config page.

Structure of config filesConfiguration files contain an array named $config. Keys of this array are the actual configuration items e.g.

Example

$config['site_domain'] = 'localhost/';

File structure of config filesThe file structure of config files follows Kohana's file structure.

application > modules > system

Meaning that configuration files in the application directory take precedence over those in modules take precedence over those in the system directory. The one exception is config.php which is hardcoded into the application/config directory and cannot be moved elsewhere.

config.phpConfig.php is hardcoded into Kohana, meaning it has to be in the application/config directory.

/* * Options: * site_domain - domain and installation directory * site_protocol - protocol used to access the site, usually HTTP * index_page - name of the front controller, can be removed with URL rewriting * url_suffix - an extension that will be added to all generated URLs * allow_config_set - enable or disable setting of Config items * global_xss_filtering - enable or disable XSS attack filtering on all user input * render_stats - render the statistics information in the final page output * extension_prefix - filename prefix for library extensions * modules - extra Kohana resource paths, see <Kohana.find_file> * autoload - libraries and models to be loaded with the controller */

Configuration files

cache.php

Sets the cache driver, cache lifetime and garbage collection. See for more information the Cache library.

Page 22: KOHANA PHP framework

cookie.php

Sets defaults for cookies. See for more information the Cookie helper.

database.php

Sets database connection settings. Multiple configurations are possbile. See the database configuration page.

hooks.php

Enable or disable hooks. See Hooks page.

locale.php

Sets the locale and timezone of an application. See Internationalization page.

log.php

Sets the logging threshold. See the Log page.

mimes.php

Sets the available mime­types. (See the validation/upload page?)

pagination.php

Sets pagination settings. See the Pagination page.

payment.php

Sets payment settings.

profiler.php

Sets the information the profiler should show. See the Profiler page.

routes.php

Sets the routes Kohana should use. Includes _default and _allowed. See Routing

session.php

Sets session settings including the session driver. See Session.

upload.php

Sets upload directory.

user_agents.php

Sets available user agents including robots and mobile browsers. See User Agent

Page 23: KOHANA PHP framework

view.php

Allowed file types (deprecated?)

Kohana URLsURLs in Kohana are composed of segments. A typical segmented URL is http://localhost/control/action/arg1/arg2

The segments correspond (in order ) to a controller, a controller method, and the method arguments.

Example

http://localhost/index.php?/articles/edit/1/my-first-article// or the same URL with url rewriting onhttp://localhost/articles/edit/1/my-first-article

When you segmentize this url it becomes

• articles (the controller)• edit (the action)• 1 (first argument)• my­first­article (second argument)

This will correspond to the controller articles found for example in application/controllers/articles.php ­ see Controllers for more information

The second segment maps to a method edit in the Articles_Controller class in application/controllers/articles.php If no second segment is set it will call the index() method. If a non­existing method is set it will try to call _default() or trigger an 404.

The third and fourth segment refer to arguments given to the edit() method. E.g. edit($id,$title)

An example of what a controller would look like when this url is used.

Example

class Articles_Controller extends Controller function __construct() parent::__construct(); function index() function edit($id,$title) //get the article from the database and edit it echo $id; $this->load->view('articles/edit');

SegmentsAs said, Kohana urls contain segments.

Page 24: KOHANA PHP framework

Example

http://localhost/articles/edit/1/my-first-article

Contains the segments

• articles• edit• 1• my­first­article

A URI class and a URL helper provide methods to make working with a url easier. You can retrieve segments, determine the current url segment, and various other operations.

URL rewritingBy default, Kohana urls contain index.php. This does not look very nice and also is not optimized for search engines. See the difference between the following urls.

http://localhost/index.php?/articles/edit/1/my-first-article// or the same URL with url rewriting onhttp://localhost/articles/edit/1/my-first-article

The latter looks nicer and is SEO proof.

The following urls might be of interest when setting up such a system:

• http://kohanaphp.com/tutorials/remove_index.html • http://forumarchive.kohanaphp.com/index.php/topic,246.0.html

They offer slightly different solutions but each should work equally good.

SuffixKohana allows you to set a suffix to your urls.

Example

http://localhost/index.php?/articles/edit/1/my-first-article.html

Setting this can be done in the application/config/config.php file under url_suffix

Allowed charactersSome characters are not allowed in urls. You can set the allowed characters in the config/routes.php file. See for more information the routing page.

Query strings and GET supportQuery strings and GET support are enabled in Kohana. You can simply append your urls with ?var=value to pass it on. The keys and values are inspected and cleansed by the Input library when global_xss is on.

Page 25: KOHANA PHP framework

RoutingTypically, a URI will map to a controller class and method on a one­to­one basis and provide arguments where necessary. For example,

http://www.example.com/class/function/arg1/arg2

The first segment refers to the controller class, the second to a method in that class and any other segments become that method's arguments.

There are cases, however, where you might want to change this behaviour. For example, you may want to use URIs like this: www.example.com/article/22. Here, the second segment of the URI is an article number, which is an argument, not a controller method. The routing feature of Kohana allows you to change how URIs are mapped to controllers and methods.

Kohana's routing configurationIn order to alter routing you have to have a copy of routes.php in your application/config directory. If it is not already there copy the one from the system/config directory.

The default routes.php will have two entries:

$config['_allowed'] = '-a-z 0-9~%.,:_';

$config['_allowed'] determines which characters are allowed in a URI. When changing this, take care not to allow characters in the URI that could compromise your application.

$config['_default'] = 'welcome';

$config['_default'] specifies the default route. It is used to indicate which controller should be used when a URI contains no segments. For example, if your web application is at www.example.com and you visit this address with a web browser, the welcome controller would be used even though it wasn't specified in the URI. The result would be the same as if the browser had gone to www.example.com/welcome.

Specifying your own routesIn addition to the default route above, you can also specify your own routes. The basic format for a routing rule is:

$config['route'] = 'class/method';

where route is the URI you want to route, and class/method would replace it.

So, for example, if your Kohana web application were installed at www.example.com and you had the following routing rule:

$config['test'] = 'foo/bar';

and you visited www.example.com/test in a web browser, you would see the page at www.example.com/foo/bar.

Page 26: KOHANA PHP framework

Using regular expressionsThe route part of a routing rule is actually a regular expression. If you are unfamiliar with regular expressions you can read more about them at the PHP website. Using regular expressions, you can be more selective about which URIs will match your routing rules, and you can make use of the sub­pattern back referencing technique to re­use parts of the URI in it's replacement.

This is best described with an example. Suppose we wanted to make the URL www.example.com/article/22 work, we might use a routing rule like this:

$config['article/([0-9]+)'] = 'news/show/$1';

which would match URIs starting with “article/” followed by some numeric digits. If the URI takes this form, we will use the news controller and call it's show() method passing in the article number as the first argument. In the www.example.com/article/22 example, it is as if the URL www.example.com/news/show/22 had been visited.

ShortcutsIn addition to being able to use regular expressions, there are also two shortcuts provided. They are:

• :any matches any non­blank string of characters• :num matches any number

These can be used in place of the sub­pattern in the regular expression, so in the previous example where www.example.com/article/22 is routed to www.example.com/news/show/22, we could have used the following routing rule:

$config['article/(:num)'] = 'news/show/$1';

which looks much neater.

Examples

Loading resourcesSince Kohana 2.1.2 $this load() is deprecated →

AutoloadingPHP has functionality to automatically load files if a certain class has not been loaded yet. Kohana employs this functionality.

Example

$user = new User_Model;$cache = new Cache();html::stylesheet();$this->layout = new View('layout');

Note: This is not the same as Kohana autoloading. Kohana's autoloading will load a certain library, model, etc. on every pageload. For example, you might want to start the Session library on every page.

Page 27: KOHANA PHP framework

Loading librariesLibraries can be loaded in general in two different ways. For example loading the session library:

$this->load->library('session');// the object can be approached with $this->session e.g.echo $this->session->id()// this is the CodeIgniter compatible approach // another possiblity using PHP5's nifty auto_load function$session = new Session;echo $session->id();

Loading databaseApart from the aforementioned methods loading the database can also be done like this

$this->load->database();

Note: in models the database is loaded automatically.

Loading helpersNote:

Loading a helper using $this→load→helper() is deprecated, it won't work and will trigger a debug error in the log.

Using a helper is fairly simple. Just call method as a static method. The class will be loaded automatically

echo url::base();

Loading viewsViews are the final output of Kohana. They can be embedded into each other so as to help you in making your site. There is more than one syntax to load a view. The actual rendering of a view is not done when you load one. More on views can be found on the views page Information on the view class can be found on the view class page.

Example

$this->layout=new View('layouts/layout'); // will load the file views/layouts/layout.php//alternate syntax$this->layout=$this->load->view('layouts/layout'); //will render the view$this->layout->render(TRUE);

Loading modelsTo load a model there is more than one method. These are the basic methods, more can be found on the Models page.

Page 28: KOHANA PHP framework

For instance your model is User_Model, the filename would be models/user.php The loading of the model happens in the controller. Example

$user = new User_Model;$name = $user->get_user_name($id); //get_user_name is a method defined in User_Model // alternative syntax$this->load->model('user');$name = $this->user->get_user_name($id);

Preloading resourcesThis functionality is deprecated and will no longer be available in Kohana 2.2. Use a base controller instead.

In the application/config/config.php you can configure which libraries or models should be automatically loaded on each page load.

$config['preload'] = array( 'libraries' => 'database, session', 'models' => 'book')

Multiple entries should be separated by commas.

Note:

Some libraries are always loaded automatically: URI, Router and Input.

ControllersControllers stand in between the models and the views in an application. They pass information on to the model when data needs to be changed and they request information from the model. For example database inserts, updates and deletes for data change and database selects for information retrieval. Controllers pass on the information of the model to the views, the views contain the final output for the users.

Controllers are called by an url, see for more information Urls for more information.

Controller naming and anatomyA controller's filename can be basically anything. The name of the controller class must correspond to the filename.

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 appended with

_Controller, e.g. Articles_Controller• must have the Controller class as (grand)parent• controller methods preceded by '_' (e.g. _do_something() ) cannot be called by the URI

mapping

Page 29: KOHANA PHP framework

A simple controllerWe start with a simple controller. It will show Hello World on the screen.

application/controllers/article.php

class Article_Controller extends Controller public function index() echo 'Hello World!';

Now if you enter www.yoursite.com/article you should see

Hello World

That's it, your first controller. You can see all conventions are applied.

More advanced controllerIn the example above the index() method is called by the www.yoursite.com/article url. If the second segment of the url is empty, the index method is called. It would also be called by the following url: www.yoursite.com/article/index

If the second segment of the url is not empty, it determines which method of the controller is called.

application/controllers/article.php

class Article_Controller extends Controller public function index() echo 'Hello World!'; public function overview() echo 'Article list goes here!';

Now if you call the url www.yoursite.com/article/overview it will display

Article list goes here!

Controller with argumentsSay we want to display a specific article, for example the article with the title being your-article-title and the id of the article is 1.

The url would look like www.yoursite.com/article/view/your­article­title/1 The last two segments of the url are passed on to the view() method.

application/controllers/article.php

class Article_Controller extends Controller public function index()

Page 30: KOHANA PHP framework

echo 'Hello World!'; public function overview() echo 'Article list goes here!'; public function view($title,$id) echo $id . ' - ' . $title; // you'd retrieve the article from the database here normally

When you call www.yoursite.com/article/view/your­article­title/1 it will display

1 - your-article-title

Controllers and subdirectoriesIf you put a controller in a subdirectory of the /controllers/ directory, Kohana will include the subdirectory in the mapping to the controller. E.g. a file in application/controllers/admin/user.php will correspond to the url http://localhost/admin/user

Routing controllers elsewhereIf for some reason the mapping from the URI to the controller and method is not right for you you can use routing to map a URI to another controller. E.g. have localhost/about/me map to http://localhost/articles/view/1

See Routing for more information on this.

Special methods

indexindex() is the method that will be called when there is no other method call. E.g. if your controller is called Welcome_Controller, and the following url is called http://example.com/welcome then the index method is called.

_remapIf you have this method in you controller, then all requests to the controller are sent to it, bypassing the default URI to method mapping.

The method is passed two parameters which can be handled as in the example below:

class Article_Controller extends Controller public function _remap( $method, $data )

Page 31: KOHANA PHP framework

// method is the first part of the uri. // it'll be index if there is no segment following the controller name // or the segment if there is // the $data param is an array of the remaining uri segments (if any) // otherwise it is an empty array

Examples www.domain.com/article

returns:

method = index

data = none

www.domain.com/article/read

returns:

method = read

data = none

www.domain.com/article/read/1

returns:

method = index

data = array( '1' );

You would not use _remap if your URI schema was this simple, but this shows how _remap works. There is also a tutorial showing the use of _remap.

_default_default() is the method called when a method of a controller is called that doesn't exist. E.g. http://example.com/welcome/sthrandom90923 , the method sthrandom90923 doesn't exist so if it exists _default() will be called. This is handy if you want to trigger a 404 for example.

Private methodsSometimes you want some methods in your controller which should not be available on your website. They are only used internally. This can be done by declaring methods private and/or prepending them with _

application/controllers/home.php

class Article_Controller extends Controller public function index() echo 'Hello World!';

Page 32: KOHANA PHP framework

private function _article_form() echo 'Article form';

When you call www.yoursite.com/article/_article_form you'll encounter a 404.

Class constructorsIf you declare a constructor in your controller, for example to load some resources for the entire controller, you have to call the parent constructor.

application/controllers/home.php

class Article_Controller extends Controller protected $db; protected $session; public function __construct() parent::__construct(); //this must be included $this->db = new Database; $this->session = new Session; public function index() $this->session->get('user_id'); public function view($article_id) $article_id = (int) $article_id; $article = $this->db->getwhere('articles', array('id' => $article_id));

This example also shows how you can retrieve an article from the database using URL segments. If you call www.yoursite.com/article/view/5 , it will retrieve the article whose id is 5.

Special Controllers

Using a base controller for your applicationUsing a base controller for your application can be very helpful. You can execute code on every page for example, useful for authenticating and authorizing users for example or doing session magic.

Example MY_Controller.php

<?php class Controller extends Controller_Core

Page 33: KOHANA PHP framework

public function __construct() parent::__construct(); // authentication goes here for example public function do_something() // method available in all controllers

The file should be named MY_Controller.php It should then be placed in application/libraries This class has all the methods of the original Controller plus your own.

Note: The prefix MY_ can be configured in application/config/config.php by changing the $config['extension_prefix']

LibrariesThe following Kohana libraries are loaded automatically by the framework and should always be available to you:

• Loader• URI• Input

Other libraries can be loaded automatically by Kohana when they are used. For example, to load and use the Profiler library, you can just add the following line to your controller's constructor:

$this->profiler = new Profiler;

Alternatively, if you wish to load libraries manually, you can do the following:

$this->load->library('some_library');

Note: using the above “manual” method of loading libraries is deprecated since Kohana 2.1.2.

For more information, see the page on Loading.

Adding your own librariesWhen creating your own libraries, these are the conventions that are suggested:

• Library files should be put in application/libraries (or if you're creating a module, in modules/libraries)

• Library files must be named the same as the library class (but without any ”_Core” suffix).• Library class names must be all capitalized (I.e., the first letter must be a upper­case)• For a new library, the class name can have ”_Core” appended to the end to enable you to

extend it in the same way you can with Kohana's built­in libraries.

For example, lets suppose that you wanted to create a new “book” library. You might create the following file:

Page 34: KOHANA PHP framework

File: application/libraries/Book.php

<?php defined('SYSPATH') or die('No direct script access.'); class Book_Core // add constructor/methods/properties here ?>

Extending librariesKohana also allows you to extended it's built­in libraries so that you can add your own functionality to them, or change the way they work. You should never change the files in system/libraries. Instead you can create a new library that extends a built­in library.

You can also extend your own libraries, so long as you have added ”_Core” to the end of their class names.

When extending a library, the conventions are the same as for when you are creating a new library, with a couple of exceptions:

• The filename must be prefixed with ”MY_”. This prefix is configurable; see the configuration page.

• The class name must be the same as the class name you are extending and must not have ”_Core” appended to it.

Lets say, for example, that you want to extend Kohana's controller class. You might do the following:

File: application/libraries/MY_Controller.php

<?php defined('SYSPATH') or die('No direct script access.'); class Controller extends Controller_Core public function __construct() // don't for get to call the parent constructor! parent::__construct(); ?>

Extending the core classes is not only allowed in Kohana, but is expected. If you wish to implement behaviour that should apply to a kohana class, such as site­wide behaviour, this is the preferred way to achieve it.

Here are some examples of why you might want to extend Kohana's Controller class in particular:

• You may wish to implement site­wide page caching.• You may wish to implement an authentication mechanism.• You might want to provide layout, or templating methods to a controller. These could be

implemented in your extended controller and would be accessible to every controller in the

Page 35: KOHANA PHP framework

application.

The deprecated preload configuration option (which pre­loads libraries and models) has been replaced by this method. The same behaviour can be achieved by extending the core Controller class and loading any libraries and models from the constructor.

Replacing Kohana's built­in librariesIt is also possible (although probably less often required) to replacing one of Kohana's built­in libraries entirely. The conventions are the same as when you are adding your own library, with one exception:

• Appending ”_Core” to the class name is not optional ­ you must do it!

If, for example, you want to replace the Profiler library, you might create the following file:

File: application/libraries/Profiler.php

<?php defined('SYSPATH') or die('No direct script access.'); class Profiler_Core // define your own profiler here ?>

3rd­party librariesIf you should require 3rd­party libraries (such as Simplepie, Zend Framework, or Pear libraries) you can place these in the application/vendors directory. Loading them from Kohana is simple. You might do the following:

Kohana::find_file('vendors','some_class')

For more information, see the Kohana class page.

Note that some 3rd party libraries can be adjusted to be Kohana libraries without much effort, sometimes renaming the file and the class name is all that is necessary. If so, you can use an alternative method of loading. You might do the following:

$this->load->library('some_lib');

Zend Framework

Zend Framework's files may struggle to load it's dependencies which will be loaded incorrectly without further configuration. If the zend folder is in applications/vendor/zend the following code can be used.

// make sure you put this somewhere before loading a Zend Framework componentini_set('include_path',ini_get('include_path').PATH_SEPARATOR.APPPATH.'vendor/zend/library/');

To include a Zend Framework component, you might do the following:

// example

Page 36: KOHANA PHP framework

require_once 'Zend/Service/Flickr.php'; // or another examplerequire_once 'Zend/Acl.php';$acl = new Zend_Acl();

Note that it also can be placed in the SYSPATH folder but it then might be overwritten by a new version of Kohana. Module folders will do as well. In this case use

ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.SYSPATH.'vendor/zend/library/');

HelpersHelpers are simply “handy” functions that help you with development.

Helpers are similar to library methods, but there is a subtle difference. With a library, you have to create an instance of the library's class to use its methods. Helpers are declared as static methods of a class, so there is no need to instantiate the class. You can think of them as “global functions”.

As with libraries, the helper classes are automatically loaded by the framework when they are used, so there is no need to load them yourself.

Here is an example call to a helper:

// show the location of this Kohana installationecho url::base();

As with most of Kohana, you can add your own helpers and replace or extend Kohana's built­in ones.

Adding your own helpersWhen creating your own helpers, these are the conventions that are suggested:

• Helper files should be put in application/helpers (or if you're creating a module, in modules/helpers)

• Helper files must be named the same as the helper class (but without any ”_Core” suffix).• Helper class names must be all lowercase.• For a new helper, the class name can have ”_Core” appended to the end to enable you to

extend it in the same way you can with Kohana's built­in helpers.

For example, suppose that you wanted to create a helper to help with JavaScript, you might create the following file:

File: application/helpers/javascript.php

<?php defined('SYSPATH') or die('No direct script access.'); class javascript_Core public static function alert($message) return "alert('$message');\n";

Page 37: KOHANA PHP framework

?>

and then to use your helper, you would do the following:

javascript::alert("Oh no!");

Extending helpersKohana also allows you to extended its built­in helpers so that you can add your own functionality to them. You should never change the files in system/helpers! Instead, you can create a new helper that extends a built­in helper.

You can also extend your own helpers, so long as you have added ”_Core” to the end of their class names.

When extending a helper, the conventions are the same as for when you are creating a new helper, with a couple of exceptions:

• The filename must be the same as the helper you're extending, except it must have ”MY_” prefixed to it. This prefix is configurable; see the configuration page.

• The class name must be the same as the class name you are extending and must not have ”_Core” appended to it.

For example, lets suppose that you want to extend Kohana's HTML helper. You might do the following:

File: application/helpers/MY_html.php

<?php defined('SYSPATH') or die('No direct script access.'); class html extends html_Core public static function your_custom_method() ?>

Extending the core classes is not only allowed in Kohana, but is expected.

Replacing Kohana's built­in helpersIt is also possible (although probably less often required) to replacing one of Kohana's built­in helpers entirely. The conventions are the same as when you are adding your own helper, with one exception:

• Appending ”_Core” to the class name is not optional ­ you must do it!

If, for example, you want to replace the url helper, you might do something like:

File: application/helpers/url.php

<?php defined('SYSPATH') or die('No direct script access.'); class url_Core // define your own url helper here

Page 38: KOHANA PHP framework

?>

ViewsSee View class for more in depth information on using views in your code.

OverviewViews 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. Views are executed in the Controller namespace so you have access to all resources you have loaded into $this →

When this view is rendered it is executed just as any PHP script would and the output from it is returned (or sent to the browser if you so wish).

Creating viewsViews need to be placed in the views directory. The filename minus the extension becomes the view's name. Views can be arranged in sub­directories if needed but the path must be specified when loading them.

Examples

// Filename home.php$view = new View('home'); // Filename list.php in sub-directory 'products'$view = new View('products/list');

Loading viewsThere are 3 ways to load a view. It is important to note that this simply creates an instance of the View class, at this point the view file has not been read and no output is created. This only happens when it is rendered.

New objectCreate a new instance of the class.

$view = new View('welcome');

Page 39: KOHANA PHP framework

FactoryUse the factory() static method. This is essentially the same as creating a new object except it is immediately returned so method chaining is possible.

$view = View::factory('welcome');

LoaderSince Kohana 2.1.2 loader is deprecated.

Use the built in loader. Using the factory method is preferred over this as it does the exact same thing but factory is shorter and clearer. The loader method is mainly provided for easier migration from CodeIgniter.

$view = $this->load->view('welcome');

Passing data into your viewsData is passed from the controller to the view by way of an an object.

Let's look at the Controller: class Welcome_Controller extends Controller function index() // Load the view as an object $view = new View('yourview'); // Adding variables to the object that will be displayed in the view $view->title = "Welcome to Kohana !"; $view->heading = "My Heading"; $view->content = "My content here."; // Render the view $view->render(TRUE);

Now open your view file and add variables: <html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $heading;?></h1> <p><?php echo $content;?></p> </body></html>

Note:

Use of arrays (CodeIgniter style) is still possible in Kohana, see more examples below

Note:

You cannot use $view data = $data;→

Page 40: KOHANA PHP framework

Views within viewsTo load views within other views:

// Example of code inside your Controller$view = new View('template'); $view->header = new View('header');$view->content = new View('content');$view->footer = new View('footer'); $view->header->title = 'Title of page'; // string for variable $title in view header.php$view->content->heading = 'Heading of your page'; // string for variable $heading in view content.php$view->footer->copyright = 'Copyright'; // string for variable $heading in view footer.php $view->render(TRUE);

View: template.php

<?php echo $header; ?><?php echo $content; ?><?php echo $footer; ?>

View: header.php

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

View: content.php

<body> <h1><?php echo $heading; ?></h1>

View: footer.php

<?php echo $copyright; ?> </body></html>

Output: <html> <head> <title>Title of page</title> </head> <body> <h1>Heading of your page</h1> Copyright </body></html>

Of course, using stylesheets and applying them to divs within your layout would give the exact design you want. You may also need custom helpers to generate navigation, breadcrumbs and dynamic content (banners, customized ads) to add a professional touch.

Note: Please also consider using the Template_Controller, this can merge the header.php and

Page 41: KOHANA PHP framework

footer.php into one file.

Data scope

RenderingExecute the render method on the view instance.

Examples

Ex 1: Render on View instance

$view = new View('sample');$view->render(TRUE);

Ex 2: Render on View::factory

View::factory('sample')->render(TRUE);

Complete ExampleController: products.php

$products = array( array( 'name' => 'Product1', 'quantity' => '3' ), array( 'name' => 'Product2', 'quantity' => '7' )); $view = new View('products/list');$view->title = 'Products';$view->set('products', $products);$view->render(TRUE);

An array of product data is defined. The products list view is loaded and the variables title and products are set. The view is rendered and outputted straight to the browser.

View: products/list.php

<html><head> <title><?= $title ?></title></head><body> <h1><?= $title ?></h1> <table> <?php foreach ($products as $product) echo '<tr><td>'; echo $product['name']; echo '</td><td>'

Page 42: KOHANA PHP framework

echo $product['quantity']; echo '</td></tr>'; ?> </table></body></html>

The title variable is echo'd. The products array is iterated over and each product is echo'd within table row and column tags.

Output: <html><head> <title>Products</title></head><body> <h1>Products</h1> <table> <tr> <td> Product1</td><td>3</td></tr> <tr> <td> Product2</td><td>7</td></tr> </table></body></html>

Models

What are models?Models are classes designed to work with information given by or asked for by the controller. For example, you have a guestbook, the controller will ask the model to retrieve the last ten entries, the model returns those entries to the controller who passes them on to a view. The controller might also send new entries to the model, update existing ones or even delete some.

Note that Kohana doesn't force you to use models. If you choose not to use them, you are free to do so.

Naming modelsKohana uses specific rules for the naming of models. These are:

• Models go into the application/models/ directory.• Model filenames are lowercase, do not have _model appended to them and should be the

singular form of the name.• The model class name is capitalized, does have _Model appended to it and should be the

singular form of the name.• For models that use ORM, there are other, more specific, conventions.

Example

Suppose that you have a table in the database called users (which is a plural name). The model

, 06/18/08
wikipage stop
, 06/18/08
End Body
Page 43: KOHANA PHP framework

that represents the users table would reside in the file application/models/user.php and the class would be called User_Model (which are both singular names).

The file would initially look something like this:

<?php defined('SYSPATH') or die('No direct script access.'); class User_Model extends Model public function __construct() // load database library into $this->db (can be omitted if not required) parent::__construct();

Loading modelsThe generally accepted way of loading a Model in Kohana is to do so within your Controller.

For instance, to load the user model (above) from application/models/user.php add the following to your controller:

$user = new User_Model;$name = $user->get_user_name($id); // get_user_name is a method defined in User_Model

Inheriting

If, for example, you use the Kohana Template_Controller and need access to your model from all descendant controllers, you can add the following to the Template_Controller constructor:

$this->user = new User_Model;

You can then access the user model from any controller that extends the Template_Controller, like this:

$name = $user->get_user_name($id); // get_user_name is a method defined in User_Model

Deprecated

The following alternative method using the Loader library is deprecated in Kohana 2.1 and will no longer be supported in Kohana 2.2.

// Model name is called without _Model, case doesn't matter// Deprecated as of Kohana 2.1$this->load->model('user');$name = $this->user->get_user_name($id);

UsageA model might look something like this:

class User_Model extends Model

Page 44: KOHANA PHP framework

public function __construct($id = NULL) // load database library into $this->db (can be omitted if not required) parent::__construct($id); /** * Get information about a user, given their user_id * @param integer the user_id * @return the result object */ public function get_user($user_id) $this->db->where('user_id', $user_id); return $this->db->get('users'); /** * Add a new user. Assumes an auto incrementing user_id in the database. * @param array user data. E.g., * array( 'name' => 'test', 'email' => '[email protected]' ) * @return void */ public function insert_user($data) $this->db->insert('users', $data); /** * Replace user details. * @param array user data. E.g., * array( 'name' => 'test', 'email' => '[email protected]' ) * @return void */ public function update_user($user_id, $data) $this->db->where('user_id', $user_id); $this->db->update('users', $data);

Note: When utilizing data from a form always use $this→input→post('var_name', TRUE) to ensure data is sanitized before using. Learn more about the Input library.

Using a database in your modelIf your model's constructor contains the line parent::__construct();, the default database functionality will be loaded into $this→db. You can use all of the database's functions with the $this→db object.

Using a model in your controllerUsing the example model above, you can integrate this model into your controller as follows:

1. Create an instance of the model in your controller to make it accessible. This can be done

Page 45: KOHANA PHP framework

directly in a controller method as $user = new User_Model. If you want the model accessible from all of your controller methods, create an instance of the model in your controller constructor: $this→user = new User_Model.

2. If you used the constructor method above, you can now retrieve user information from your database within any of your controller methods with: $user = $this→user→get_user(1). The $user variable now contains a database result set object (for the user with id = 1) that can be passed to your View.

3. If you passed the entire $user variable to your View, you can access specific user data elements within your View in the form $user→name. See Database Library for more information.

ORMSee for more information

• ORM

ORM is a special kind of model. Based on its name it will derive for example the table it is a model for, it will also have some basic functions (find($id), find_all_by_lastname) commonly used in a model as well as support for relationships between tables. Another aspect of ORM is that it turns a record from a database into an object.

EventsSee Event for information on adding, running, removing and using custom events.

Kohana events consist of a name and callback. Names usually include a prefix with the name 1), but are not required to. All of the core events are prefixed as system.name.

System EventsThe following events are defined in the Kohana core files. The pre­defined actions for these events are added in Kohana::setup.

system.ready

Called immediately after hooks are loaded. This is the earliest attachable event. Nothing is attached to this event by default. Hooks are loaded before this point.

system.routing

Processes the URL and does routing. Calls Router::find_uri and Router::setup by default.

system.execute

Controller locating and initialization. A controller object will be created, as an instance of Kohana. Calls Kohana::instance by default.

system.post_routing

Kohana 2.2 Triggered after all routing is done so interventions in routing can be done here. If

Page 46: KOHANA PHP framework

Router::$controller is empty after this event a 404 is triggered.

system.404

Called when a page cannot be found. Calls Kohana::show_404 by default.

system.pre_controller

Called within system.execute, after the controller file is loaded, but before an object is created.

system.post_controller_constructor

Called within system.execute, after the controller constructor has been called. Kohana::instance will return the controller at this point, and views can be loaded. Controller methods have not been called yet.

system.post_controller

Called within system.execute, after the controller object is created. Kohana::instance will return the controller at this point, and views can be loaded.

system.send_headers

Called just before the global output buffer is closed, before any content is displayed. Writing cookies is not possible after this point, and Session data will not be saved.

system.display

Displays the output that Kohana has generated. Views can be loaded, but headers have already been sent. The rendered output can be manipulated as Event::$data.

system.shutdown

Last event to run, just before PHP starts to shut down. Runs the Kohana::shutdown method by default.

HooksHooks are included early in Kohana and can be used to execute code before e.g. controllers are loaded so you can check for for example authentication early in Kohana. Events and hooks go hand in hand since in hooks you can attach code to events. See for more information the Hooks page.

1) An example of a “prefix” is prefix.name

HooksHooks are basically files included at the start of Kohana, to be more specific they are loaded in the Kohana::setup() method. At this time these files are loaded, so their methods can be used

• index.php• core/Bootstrap.php• core/Benchmark.php

Page 47: KOHANA PHP framework

• core/utf8.php • core/Config.php • core/Log.php • core/Event.php • core/Kohana.php

No event has been started yet, the first to be started is system.ready

Hook files should be put in application/hooks or similarly in a module folder.

Configuring hooksTo configure hooks edit 'hooks.php in your application/config directory. If the file is not there copy the one from system/config.

It will look something like this:

File: hooks.php

$config['enable'] = FALSE;

Set $config['enable'] to TRUE and all files in the hooks directory (application/hooks) will be included and the code will be executed.

Set $config['enable'] to an array with filenames and those and only those files will be included.

Example hooks.php

//To include all files in application/hooks$config['enable'] = TRUE; //or to load page_cache.php$config['enable'] = array('page_cache');

Hooks and eventsThe power of hooks mainly comes from the Events class. Hooks are loaded before any of the events are started so you can attach a hook to an event. For example you load the following file as a hook

Example hooks/power.php

class Power public function Kohana() Event::$data=Event::$data.'<!-- Powered by Kohana-->'; Event::add('system.display', array('Power', 'Kohana'));

This will add a small notice to the bottom of each page (<!– Powered by Kohana–>). It utilizes the Event::$data to manipulate the final output.

ConstantsWhen using hooks you might need to get under the hood of Kohana. When the hooks are loaded

Page 48: KOHANA PHP framework

these constants are set in index.php

• EXT ­ contains the default file extension used for files in Kohana. Defaults to '.php'• KOHANA ­ basename• DOCROOT ­ dirname• APPPATH ­ path to the application directory• SYSPATH ­ path to the system directory• MODPATH ­ path to the modules directory

Error HandlingSee for more information

• Log class explanation of the log class.

Config.display_errorsIn the index.php file there is a setting display_errors. This determines whether errors should be outputted to the screen or not. During development you'd want to set this to TRUE, but in production set this to FALSE so as to prevent users from seeing errors. This won't affect logging of errors.

ExceptionsExceptions in Kohana are handled by the Kohana Exception classes. There are three types of exceptions: Kohana_Exception, Kohana_User_Exception and Kohana_404_Exception.

Kohana_ExceptionKohana_Exception extends Exception. To throw a Kohana_Exception an i18n language file must exist.

Syntax/** * @param string i18n language key for the message * @param array addition line parameters */throw new Kohana_Exception(string $i18_lang_key [, string $message]);

Example//...if($x == 0) throw new Kohana_Exception('math.division_by_zero'); // Throw a $lang['division_by_zero'] exception in ./i18n/en_US/math.php // "Cannot divide by zero."else if($x < 0) throw new Kohana_Exception('general.math.negative_number', $x); // Throw a $lang['math']['negative_number'] exception in ./i18n/en_US/general.php and pass the message $x // "The number passed was negative: -5"//...

Page 49: KOHANA PHP framework

Kohana_User_ExceptionKohana_User_Exception extends the Kohana_Exception. This is similar to Kohana_Exception except that the exception messages do not have to be in the i18n structure.

Syntax/** * @param string exception title string * @param string exception message string * @param string custom error template */throw new Kohana_User_Exception(string $title, string $message [, string $template]);

Example//...if($x == 0) throw new Kohana_User_Exception('Cannot divide by zero', 'You passed a zero');else if($x < 0) throw new Kohana_User_Exception('Number Type Exception', "Cannot use a negative number $x");//...

Kohana_404_ExceptionKohana_404_Exception extends Kohana_Exception. This exception will display a 404 error message to the user.

Syntax/** * @param string URL of page * @param string custom error template */throw new Kohana_404_Exception([string $page [, string $template]]);

Example//...if($x == 0) throw new Kohana_404_Exception('divide by zero'); // "The page you requested, Cannot divide by zero, could not be found."//...

Triggering errors

Custom error pagesThe system/views/kohana_error_page.php is the default error page. You can overload this one by having a kohana_error_page.php in your application/views directory or in a similar modules directory.

Page 50: KOHANA PHP framework

The default error page will show you the error as well as a stack trace if available.

LoggingKohana can log errors, debug messages and informational messages. The setting can be found in application/config/log.php See for more information on logging the Log class.

ModulesKohana is easily extendable using modules. Modules are reusable collections of related files that together add a particular functionality to an application. You may want to re­use some helpers or add authentication across multiple applications. Place it in a module folder and you can copy it with ease or have multiple applications use the same module directory.

The Filesystem page should be read before this one to understand it properly.

Setting upIt is most common to have a directory called modules in the same directory as the application and system directories. For instance, we created a module for ACL (access control lists) and authentication (auth) since we want to reuse it across applications.

root +- application +- system +- modules | +- acl | | +- helpers | | +- i18n | | +- libraries | | +- models | | +- vendor | | +- views | | | +- auth | +- helpers | +- i18n | +- libraries | +- models | +- vendor | +- views | +- index.php

ConfiguringOnly placing modules in the modules directory won't load them, they must be configured for Kohana to use them. This can be done in the application/config/config.php file using the 'modules' setting.

Example

// Paths are relative to the docroot, but absolute paths are also possible $config['modules'] => array

Page 51: KOHANA PHP framework

( 'modules/acl', 'modules/auth',)

In the cascading filesystem, files in modules that are higher up the list take precedence over those lower down just as files in the application directory do over those in modules and the system directory.

InternationalizationInternationalization files can be found in the i18n directories. These directories can be found in system, application or modules directories. Kohana's own internationalization files can be found in the system directory.

In the i18n directories the directories with the language files can be found. English files are in en_US, Dutch in nl_NL, German in de_DE etc.

Locale settingThe configuration file locale.php sets which locale will be used. The file can be found in the application/config directory, if it's not there copy the one from the system/config directory.

The file will look somewhat like this

$config['language'] = 'en_US'; $config['timezone'] = '';

$config['language'] sets the language that should be used. It maps to the directories in the i18n directory. $config['timezone'] sets the timezone, see for more information http://php.net/timezones

File structureroot +- application | +- i18n | +- en_US | | +- coffee.php | | | +- de_DE | | +- coffee.php | | | +- zh_CN | | +- coffee.php | +- system | +- i18n | +- en_US | | +- cache.php | | | +- de_DE | | +- cache.php | | | +- zh_CN | | +- cache.php

Page 52: KOHANA PHP framework

Retrieving language stringsUsing Kohana::lang() languages strings can be retrieved. Example echo Kohana::lang('cache.resources'); //outputs is locale is set to en_US // Caching of resources is impossible, because resources cannot be serialized. //If locale is set to de_DE // Das Cachen von Ressourcen ist nicht möglich, da diese nicht serialisiert werden können.

In the case of en_US, Kohana::lang('cache.resources') maps to i18n/en_US/cache.php and within this file to $lang['resources']

Kohana also allows to give extra arguments to Kohana::lang()

Setting your own language stringsIt is possible to have your own language strings in your application/module. Simply add a directory i18n, add the directory of the locale and add the file with the language strings. For example, you want to have language strings for coffee and stuff related to coffee. Name the file coffee.php and place it in application/i18n/en_US/

Format of the file

$lang = array( 'cup' => 'Coffee goes in here', 'beans' => 'Coffee is created from beans.', 'java' => 'Place where coffee comes from, not the programming language',);

These language strings can now be called from your application

Example

echo Kohana::lang('coffee.cup');echo Kohana::lang('coffee.beans');echo Kohana::lang('coffee.java');

Page 53: KOHANA PHP framework

Core

Page 54: KOHANA PHP framework

Benchmark ClassThe benchmark class allows you to time your code. By default several benchmarks are run:

• Kohana Loading • Environment Setup • System Initialization • Controller Setup • Controller Execution • Total Execution

The results of the benchmarks will be outputted by the Profiler.

If a view is rendered execution_time and memory_usage can be used in the view to be replaced by the actual execution time and memory usage.

Note:

Benchmark does not have to be loaded nor instanced. It is automatically loaded during the system setup and all its methods are static.

Methods

start()Benchmark::start($name) is used to start a new benchmark. Supply an unique name. Returns void.

Benchmark::start('benchmark1');

stop()Benchmark::stop($name) is used to stop a benchmark. Supply the name given when the benchmark was started. Returns void.

Benchmark::stop('benchmark1');

get()Benchmark::get($name, $decimals) is used to retrieve the results of a benchmark. Returns an array with the results: time is expressed in seconds, memory in bytes.

print_r(Benchmark::get('benchmark1'));// Output: Array ( [time] => 0.0078 [memory] => 472 )

The $decimal parameter is optional. Its default value is 4.

print_r(Benchmark::get('benchmark1', 6));// Output: Array ( [time] => 0.007802 [memory] => 472 )

If you set the $name parameter to TRUE, all benchmarks will be returned.

print_r(Benchmark::get(TRUE, 3));// Output: Array ( [477f51931a33e_total_execution] => Array ( [time] => 0.023

Page 55: KOHANA PHP framework

[memory] => 618940 ) [477f51931a33e_kohana_loading] => Array ( [time] => 0.012 [memory] => 369104 ) [477f51931a33e_environment_setup] => Array ( [time] => 0.002 [memory] => 54300 ) [477f51931a33e_system_initialization] => Array ( [time] => 0.003 [memory] => 65884 ) [477f51931a33e_controller_setup] => Array ( [time] => 0.008 [memory] => 177688 ) [477f51931a33e_controller_execution] => Array ( [time] => 0.000 [memory] => 4236 ) [benchmark1] => Array ( [time] => 0.008 [memory] => 472 ) )

Note:

If for some reason the memory_get_usage() function is not available on your system, memory will be set to 0.

Config ClassProvides methods for working with configuration items.

Where to put the configuration?Configuration files must be placed in a folder named config, this folder can reside in system, application or a module. Application is more important than system and will override it. Modules override system files but are overridden by application files.

The config file must be in this format:

$config = array( 'language' => 'en_US', 'timezone' => '');

Methods

Retrieving configuration itemsConfig::item($key, $slash = FALSE, $required = TRUE) retrieves a configuration item, can return a string, array or boolean. $slash will force a forward slash at the end of the item. $required determines whether an item is required or not.

config::item('locale.language'); //returns the language from the **locale.php** file and returns the config['language'] item.

Setting a configuration itemFor setting configuration items in realtime you must enable this setting in the config.php file. (core.allow_config_set)

Config::set($key, $value) sets a configuration item, returns TRUE on success or FALSE when it didn't succeed.

config::set('locale.language','nl_NL');

Note:

Page 56: KOHANA PHP framework

If you want to set a configuration in realtime make sure the config.allow_config_set is set to TRUE in application/config.php

Getting the include pathsConfig::include_paths($process= FALSE) gets the include paths and returns an array. First in the array is the application path, last will be the system path, other items will be include paths set in the configuration item 'core.include_paths'. $process, if true, will reprocess the include_paths.

config::include_paths();

Load a configuration fileConfig::load($name, $required = TRUE) loads a configuration file. Config::item() loads them as well if they're not already loaded and retrieves the items straightaway.

config::load('locale');

Event ClassFor an overview for a programming overview of events, please see Event_handler and Event_loop. Kohana stores events in queues, as opposed to stacks. This simply means that, by default, new events will be processed after existing events.

What is an Event?Kohana events consist of a unique name and a callback. By default, there are several events defined by Kohana. Names are completely freeform, but the convention is to use a prefix.name to make event names more unique. All pre­defined events are prefixed as system.name, eg: system.post_controller.

MethodsAll Event methods are static, and Event should never be instanced.

addUsed to add a new callback to an event. If the event does not already exist, it will be created.

// Calls the function "foo" after the controller method is executedEvent::add('system.post_controller', 'foo'); // Calls the static method "Foo::bar" after the controller method is executedEvent::add('system.post_controller', array('foo', 'bar')); // Calls the "bar" method in the "$foo" object when the output is renderedEvent::add('system.display', array($foo, 'bar'));

You can also create entirely new events this way:

, 06/18/08
End Body
, 06/18/08
wikipage stop
Page 57: KOHANA PHP framework

// Creates a custom user.login eventEvent::add('user.login', array($user, 'login'));

add_beforeUsed to add a callback immediately before another callback in an event.

// Add the function "faa" to be executed before "foo"Event::add_before('system.post_controller', 'foo', 'faa');

If the event you are inserting before does not exist, add_before will functional exactly the same as add.

add_afterUsed to add a callback immediately after another callback in an event.

// Add the function "fzz" to be after "foo"Event::add_after('system.post_controller', 'foo', 'fzz');

If the event you are inserting after does not exist, add_after will functional exactly the same as add.

replaceUsed to replace a callback with another callback in an event.

// Replace the "foo" function with the "oof" functionEvent::replace('system.post_controller', 'foo', 'oof');

If the event you are replacing does not exist, no event will be added.

getReturns of the callbacks as a simple array.

// Returns of the callbacks for system.post_controller$events = Event::get('system.post_controller'); // Loop through each event and call itforeach ($events as $event) $return_value = call_user_func($event);

If no events exist, and empty array will be returned. It is recommended to use empty if you need to validate that events exist.

clearClear one or all callbacks from an event.

// Clears the "oof" function from system.post_controllerEvent::clear('system.post_controller', 'oof');

If this method is called without a second argument, it will clear the entire queue for the given event.

Page 58: KOHANA PHP framework

runExecute all of the callbacks attached to an event.

// Run the system.post_controller eventEvent::run('system.post_controller');

has_runChecks if an event has already been run. This can is useful to make an event run only once.

// Test if the event has already runif (Event::has_run('system.post_controller')) echo 'post_controller has been run.'; // Run the post controller event if it has not already been runEvent::has_run('system.post_controller') or Event::run('system.post_controller');

DataEvent::data is a special variable that can be set when using Event::run. The data is assigned by reference, and can be manipulated by all of the callbacks.

// Debug the dataecho Kohana::debug($data); // Run the post_controller event with dataEvent::run('system.post_controller', $data); // Display the changed dataecho Kohana::debug($data);

Event data is cleared immediately after all of the callbacks are run, and can only be accessed during callback execution.

Kohana ClassThe Kohana class is at the center of Kohana. It loads up the Router, dispatches to the controller and does the final output.

Character setThe class also sets a utf­8 header. If you want a different charset you can override it by placing this in for example your controller. The browser will interpret the page with the new charset.

header('Content-type: text/html; charset=iso-8859-1');

Page 59: KOHANA PHP framework

Methods

debug()Returns HTML formatted strings of variables that can be echo to screen nicely.

echo Kohana::debug($this->input->post());

Prints out the POST variable

backtrace()Will be called when an error occurs. It displays an overview of files and functions called so you can spot the source of the error. Very useful for debugging.

lang()Using Kohana::lang() languages strings can be retrieved.

Example echo Kohana::lang('cache.resources'); //outputs is locale is set to en_US // Caching of resources is impossible, because resources cannot be serialized. //If locale is set to de_DE // Das Cachen von Ressourcen ist nicht möglich, da diese nicht serialisiert werden können.

In the case of en_US, Kohana::lang('cache.resources') maps to i18n/en_US/cache.php and within this file to $lang['resources']

Kohana also allows to give extra arguments to Kohana::lang()

key_string()Searches for given key in a nested array. It takes:

• [string] Key to search for. Should be in form of 'rootnode.childnode.anothernode'• [array] Array to search in. Should be an array of values and/or another arrays to represent

nodes

Example

$a = array( 'levelone1' => array ( 'leveltwo1' => array ( 'a' => 'aaa', 'b' => 'aab', 'c' => 'aac' ), 'leveltwo2' => array

Page 60: KOHANA PHP framework

( 'a' => 'aba', 'b' => 'abb', 'c' => 'abc' ) ), 'levelone2' => array ( 'a' => 'ba', 'b' => 'bb', 'foo' => 'bar' )); Kohana::key_string('levelone1.leveltwo1.b', $a);//Returns 'aab'Kohana::key_string('levelone1.leveltwo2.c', $a);//Returns 'abc'Kohana::key_string('levelone2.foo', $a);//Returns 'bar'

list_files()Iterates through all directories of a given name and returns found files. It takes two parameters:

• [string] In which directory to search in• [bool] Should find_files be recursive? (TRUE or FALSE, defaults to FALSE)

It returns array of file paths to found files.

Example

$controllers = Kohana::list_files('controllers', TRUE);// Now $controllers is an array containing paths to all controllers in your Kohana installation

find_file()Find a resource file in a given directory using Kohana's cascading filesystem.

• [string] Directory to search in• [string] Filename to look for (including extension if 4th parameter is TRUE)• [bool] Is the file required, throws an error if this is true and the file cannot be found• [bool] Use a custom file extension, TRUE or FALSE (defaults to FALSE)

Returns an array if the type is i18n or a configuration file. When file is found it returns a string with the path to the file. It will return FALSE if the file is not found.

This method uses the cascading filesystem of Kohana, this means it will first look in the application directory to see if a file exists, then any module that exists in order they are supplied in the config.php file and then the system directory. Exception to this is the i18n files and the config files. They are loaded from the system directory upwards. Result is that you can copy half a language file from the system directory and place it in the application directory, variables declared in the system directory will be supplanted by the one in the application directory.

Example

// find a file named 'article.php' in the 'controllers' directory.include (Kohana::find_file('controllers','article'));

Page 61: KOHANA PHP framework

Example

// find a file named 'database.php' in the 'config' directory.include (Kohana::find_file('config','database'));

Log ClassProvides methods to work with logging.

ConfigurationThe configuration file Log.php can be found in the application/config directory. If it's not there it can be copied from the system/config directory. See for more information on the Config page.

There are three settings for the Log class:

$config['threshold'] = 0; $config['directory'] = 'logs'; $config['format'] = 'Y-m-d H:i:s';

$config['threshold'] can be set at four levels:

• 0 ­ Logging is disabled• 1 ­ Error messages including PHP errors• 2 ­ Debug messages• 3 ­ Informational messages

When set to 3 it will also log 2 and 1. Same goes for 2.

Level 1 is recommended in production use as it will only log errors. Level 2 is useful while debugging, it will log all libraries loaded and any errors. Nothing is logged to level 3 by Kohana by default, but can be used for custom logging by applications.

Important setting the level to 2 or 3 can slow down your application significantly.

$config['directory'] log file directory, relative to application/, or absolute.

$config['format'] format for the timestamps according to date()

Kohana 2.2 makes a small change to the logging threshold order. levels 2 and 3 can be used without the overhead of debug. By default nothing is logged to level 2 or 3 by Kohana.

• 0 ­ Logging is disabled• 1 ­ Error messages including PHP errors• 2 ­ Application Alert messages (changed level)• 3 ­ Application Information messages (changed level)• 4 ­ Debug messages (new level)

Page 62: KOHANA PHP framework

Methods

Adding entries to the log fileLog::add($type, $message) logs the message according to the type given (error,debug,info), the item will be preceded by a timestamp formatted according to $config['format'].

Log::add('error', 'Query went wrong'); // returns voidLog::add('debug', 'Custom library X loaded'); // returns void

Writing the log entries to the fileLog::write() is called by default on the shutdown event (event.shutdown). See for more information on events the Event page. There is typically no need to call it manually.

Log::write(); // returns void

Unicode FunctionsProvides static methods to work with UTF­8 strings as PHP is not yet natively capable of doing that.

Requirements:

• PCRE needs to be compiled with UTF­8 support.• The iconv extension needs to be loaded.• The mbstring extension is highly recommended. However, it must not be overloading string

functions.

Methods

cleanutf8::clean() recursively cleans arrays, objects, and strings. It removes ASCII control characters (strip_ascii_ctrl) and converts to UTF­8 while silently discarding incompatible UTF­8 characters.

Note:

The clean() method is automatically applied to the GET, POST, COOKIE and SERVER globals.

from_unicode

is_asciiutf8::is_ascii() checks whether a string contains only 7bit ASCII bytes. It returns TRUE if it does so, FALSE otherwise. This method is also used internally in the utf8 class to determine when to use native functions or UTF­8 functions.

Example: var_dump(utf8::is_ascii("a\0b".chr(127).'c')); // bool(true)

Page 63: KOHANA PHP framework

var_dump(utf8::is_ascii("a\0b".chr(128).'c')); // bool(false)

ltrim

ord

rtrim

str_ireplace

str_pad

str_split

strcasecmp

strcspn

strip_ascii_ctrlutf8::strip_ascii_ctrl() removes all ASCII control characters from a string.

Example: echo utf8::strip_ascii_ctrl("a\0b".chr(7).'c');// Output: abc

strip_non_asciiutf8::strip_non_ascii() removes all non­ASCII characters from a string.

Example: echo utf8::strip_non_ascii('Clichés');// Output: Clichs

Page 64: KOHANA PHP framework

stristr

strlen

strpos

strrev

strrpos

strspn

strtolower

strtoupper

substr

substr_replace

to_unicode

transliterate_to_asciiutf8::transliterate_to_ascii() replaces many (not all) special/accented characters by their ASCII equivalents. Special characters that are unknown to this method are left untouched. You can remove them afterwards with the strip_non_ascii method.

Example: echo utf8::transliterate_to_ascii('Jérôme est un garçon.');// Output: Jerome est un garcon.

Further reading: Wikipedia on transliteration

trim

ucfirst

ucwords

View ClassFor a more in depth overview of views see General/Views.

Page 65: KOHANA PHP framework

Creating an instanceCreating an instance of the view class.

$view = new View('welcome');

Setting data

Methods

set()set() can be used to set a variable in a view. You can also supply an array and the keys and values will be treated as variables. $this view your_variable can be used to accomplish the same. → →

$view = new View('welcome'); $view->set('title', 'Elvis lives');

bind()bind() is like set only the variable is assigned by reference.

$view = new View('welcome'); $var='Some value'; $view->bind('title', $var); $var='Another value'; $view->render(true); //The 'title' variable will contain 'Another value'

set_global()set_global() is like set only that the variables set are available throughout all views. This means you can use it with views in views for example.

// loading views$view = new View('page');$view->header = new View('header'); // setting variables in all views$view->set_global('title', 'Title of page'); // set variable $title for example in view header.php $view->render(TRUE);

render()render() renders the output of the View.

// render and store, default, no browser output$this->template->content = $this->session->get_once('message').$content-

Page 66: KOHANA PHP framework

>render(); // render output of view to browser$this->template->render(TRUE);

factory()This method is static. Parameters are the same as creating a new instance.

It creates a View instance and immediately returns it so method chaining is possible.

public function _add_breadcrumb() $crumbs = View::factory('admin/breadcrumb') ->set('crumbs', html::breadcrumb()) ->render(); $this->template->content = $crumbs.$this->template->content;

set_filename()This method only exists in version 2.2

set_filename() sets the name of the file used for the view.

$view=new View; if(request::is_ajax()) //request helper also exists in 2.2 $view->set_filename('ajax_view');else $view->set_filename('html_view'); $view->render(TRUE);

Page 67: KOHANA PHP framework

Addons

Page 68: KOHANA PHP framework

Auth ModuleThe Auth module is a simple module to enable authentication on your site. It supports users, multiple roles per user and auto­logins. It employs ORM and Forge. If you're new to Kohana the code of Auth might help you to get started. Take a look at the controller and the models to see how simple applications work.

Methods

auto_login()

login()$this→auth→login($user, $password, $remember) validates a user's authentication credentials and logs a user in.

logout()$this→auth→logout($destroy) logs a user out by removing the appropriate session variables.

• [boolean] If true, completely destroy the session; if false, do not delete the session, but only remove the authentication information from the session.

hash_password()

Forge Module (Form Generation)The Forge module is a module to easily create and manage forms. You can create forms with built­in validation in one go. Forge coexists with the Form helpers, it doesn't replace it. Forge provides help with rendering, validating and filtering forms, the form helper provides methods to create forms.

Creating a formCreating a form is done by instantiating the Forge class

$form = new Forge('', 'Add article', 'POST', array('id' => 'article_form'));

This is the start of each form. The Forge class will accept up to four arguments, all of which are optional. The first argument is the form action, the second is the form title, the third argument is the form submittal method, and the last argument is an array of attributes.

Here you see only three arguments being used, the last of which is obviously the attribute array. You can also set any of these attributes after the fact or on the fly by using the method below.

Say we want to change the class and method attribute of the form.

$form->set_attr('class', 'form_class')->set_attr('method', 'post');

Page 69: KOHANA PHP framework

Adding elementsNext step is adding elements.

$form->input('title');

This is the basis of adding elements. Now we set a label and add rules.

$form->input('title')->label(true)->rules('required|length[3,40]|valid_alpha_numeric')->value('title');

A complete form$form = new Forge('', 'Add article','POST',array('id' => 'article_form'));$form->set_attr('class', 'form_class')->set_attr('method', 'post');$form->input('title')->label(true)->rules('required|length[3,40]|valid_alpha_numeric');$form->input('article')->label('Article text')->rules('required||valid_alpha_numeric');$form->submit('submit'); if($form->validate()) echo $form->title->value; echo $form->article->value;else echo $form->html();

Form methods

set_attr()

set_attr() set an attribute of the <form> element. There are two parameters:

• [array]/[string] Either the attribute name or an array of attribute names and values• [string] Attribute value (Default NULL)

$form = new Forge('', 'Add article', 'post',array('id', 'article_form'));$form->set_attr('class', 'form_class'); $form->set_attr(array('class' => 'form_class','id' => 'article_form'));

validate()

validate() validates a form, takes no arguments. Returns boolean.

as_array()

as_array() returns an array with input names and values. Useful for putting your form values into the database.

Page 70: KOHANA PHP framework

error_format()

html()

Returns a rendered form as a string.

In Kohana 2.2 changed to render()

Form ElementsNote that all elements except for Form_Group inherit from Form_Input so methods below apply to all of them.

Form_Input

Create input

Create an input. Method is chainable.

$form->input('input_name');

Input label

Show the field label or not. If the argument is boolean the input label will be based on the input name. Also you can pass the custom label name. Method is chainable.

->label(TRUE);

or

->label('Custom input name');

Input validation

Set the validation rules for the field. Method is chainable.

->rules('list|of|validation|rules')

Input validation using Kohana Validation helper

You can utlize rules from Validation helper by prefixing the rule with valid_. Thus, a rule normally accessible by calling valid::ip would be utilized as:

->rules('valid_ip')

Input value

Set the default value for the element. Method is chainable.

->value('input_value')

Page 71: KOHANA PHP framework

Extra Attributes

You can add extra attributes to input and all other form elements by using attribute name.

example

$form->input('title')->label(TRUE)->class('input_size');

Example$form->input('title')->label(TRUE)->rules('required|length[0,255]')->value($this->page->title);

Form_CheckboxBy default a checkbox checked status is off to turn on just call the checked method and set to true.

Example$form->checkbox('test')->label(TRUE)->value('1')->checked(TRUE);

Form_Checklist

Example$form->checklist('blocks')->label('Blocks available')->options($option)->rules('required');

* $option should be sent as an array with each value in the format 'value' = array('label', true|false) where 'value' will be the value of the checkbox, 'label' will be used as the label and the true|false indicates if the item is checked by default.

Form_Dateselect

Example$form->dateselect('date')->label(TRUE)->years(date('Y')-3, date('Y')+5)->value(strtotime($your_date_var));

* In the above example we are instructing Forge to generate years ranging from 3 years prior and 5 years after the current year.

* Dateselect uses Unix timestamp format internally to calculate dates. To pass a MySQL date field to the value() method, wrap it in the PHP strtotime function.

Form_DropdownYou can set dropdown with single array or with two­dimensional array. The key will be the option value and the value will be the option text.

Example$form->dropdown('pizzas')->label(TRUE)->options(array('Hawaiian', 'Margarita'))-

Page 72: KOHANA PHP framework

>selected('1');

$form->dropdown('pizzas')->label(TRUE)->options(array('HA'=>'Hawaiian', 'MA'=>'Margarita'))->selected('1');

Form_GroupIs an instance of the Forge class so you can have groups in your forms. All methods of the Forge class are available save html().

Example$group = $form->group('pizzas')->label(TRUE);$group->dropdown('pizzas')->label(TRUE)->options(array('Hawaiian', 'Margarita'))->selected('1');$group->dropdown('bases')->label(TRUE)->options(array('Thin', 'Pan', 'Stuffed'))->selected('2');

In the view groups get special attention and are rendered differently. You can use groups for example when you need to group some form elements within a `<fieldset>` tag.

Form_HiddenIn the default template hidden forms are added straight after the <form> tag.

Example$form->hidden('id')->value(1);

Form_PasswordThe method 'matches' matches a form field with another form field.

Example$form->input('password')->label(TRUE);$form->input('passconf')->label('Password Confirmation')->rules('required|length[5,32]')->matches($form->password);

Form_Submit

Example$form->submit('Submit Button Name');

Form_Textarea

Example$form->textarea('description')->label(TRUE)->rules('length[0,255]')->value($this->page->description);

Page 73: KOHANA PHP framework

Form_Upload

Example

If the file exists and the second argument of upload() method is TRUE, it will overwrite this file. Otherwise it will create an unique name.

$form->upload('file', TRUE)->label(TRUE)->rules('required|size[200KB]|allow[jpg,png,gif]');

The default upload path is configured your upload.php config file (system/config/upload.php).

Using Custom Form TemplatesIf you need more control over your form, but still want to take advantage of the automated validation and field re­population provided by the Forge library, you can utilize a custom form template. This allows you to design the form however you want using HTML.

from: http://forumarchive.kohanaphp.com/index.php/topic,616.msg3841.html#msg3841

Example

Controller: application/controllers/your_controller.php

$form = new Forge();$form->input('username')->label(TRUE)->rules('required');$form->password('password')->label(TRUE)->rules('required'); if ($form->validate()) // Do stuff echo $form->html('login_form', TRUE); // Only this is different, specifies to use a custom form

View: application/views/login_form.php

<form method="post" action="<?= url::site('login') ?>"> <?= $username->label() ?> <br /> <?= $username->html() ?> <br /> <?= $username_errors ?> <br /><br /> <?= $password->label() ?> <br /> <?= $password->html() ?> <br /> <?= $password_errors ?> <br /> <input type="submit" value="Login" /></form>

Note: You don't have to use →label(). You can write the HTML for label or form input fields directly into your form view (e.g. <label for=”…”>). Use $username→value to fill in the values for input fields.

Page 74: KOHANA PHP framework

Saving forms as a libraryUsing Forge you can save forms as a library and thus have access to your form throughout your application. See http://learn.kohanaphp.com/2008/03/13/saving­forms­as­libraries/ for a short tutorial.

Media ModuleThe Media Module is used to reduce the number and bandwidth of queries for CSS and JavaScript files. It does not support images at the current time.

Once the module has been enabled in the standard way, it will intercept requests for /media/css/… and /media/js/… transforming the results as specified in the config file media.php.

Configurationread the config for now

UsagePlace all CSS files into the directory /application/views/media/css/ and all JavaScript files into /application/views/media/js/.

You then use the helpers to include them from your view pages like this:

<?=media::stylesheet(array('sheet1', 'sheet2', 'sheet3'))?><?=media::script(array('jquery', 'dojo'))?>

Not to confuse matters the above is simply a helper for writing the following:

<link rel="stylesheet" href="/media/css/sheet1,sheet2,sheet3.css" type="text/css" /><script type="text/javascript" src="/media/js/jquery,dojo.js"></script>

Template Controller

Template ControllerUsing the template controller you can set a template for your site. It's workings are simple.

Example: application/controllers/home.php

class Home_Controller extends Template_Controller public $template = 'template'; //defaults to template but you can set your own view file public $auto_render = TRUE; //defaults to true, renders the template after the controller method is done public function __construct()

Page 75: KOHANA PHP framework

parent::__construct(); //necessarypublic function index() $this->template->content= 'index page in a template';

The example illustrates a file application/controllers/home.php which extends the template controller. The template controller can be found in system/controllers/template.php. You set the template file in $template. It defaults to 'template' which is found in views/template.php. Auto­render renders the template during the post_controller event which is executed after the controller. This all means you can change the template and auto­render all in realtime.

For a more detailed discussion of Template Learning Kohana: Template

Example 1This is a simple example that shows the magic of the Template class.

Save this as /application/controllers/test.php

class Test_Controller extends Template_Controller public $template = 'base_page'; public function __construct() parent::__construct(); // the template page 'base_page' is loaded by // default, this is the same as uncommenting // the following line: // $this->template = new View('base_page'); // All pages have some things in common such as // the page title: $this->template->title = "Welcome to Kohana!"; $this->template->copyright = "&#169; Me, 2008"; function index() // // don't forget that the __construct() is run // before this method, so the template // is set up and ready for this pages content. // // Load this page (Test) view $test = new View('test'); // now create this page (Test) $test->heading = "Test :: Index Heading"; $test->content = "Test :: Index :: content here."; $test->content .= '<br><a href="test_2">page 2</a>'; // add our content to the template view: $this->template->content = $test;

Page 76: KOHANA PHP framework

// the view is auto-render by default function test_2() // Load this page (Test) view $test = new View('test'); // now create this page (Test) $test->heading = "Test :: test_2 :: Heading"; $test->content = "Test :: test_2 :: content here."; $test->content .= '<br><a href="index">page 1</a>'; // add our content to the base view: $this->template->content = $test; // the view is auto-render by default

This uses the following 2 views:

Save this as /application/views/base_page.php

<html> <head> <title><?php echo $title; ?></title> </head> <body> <?php echo $content ?> <?php echo $copyright; ?> </body></html>

Save this as /application/views/test.php

<h1><?php echo $heading; ?></h1><p><?= $content ?></p>

To test this browse to http://127.0.0.1/Kohana/test/ and http://127.0.0.1/Kohana/test/test_2

The Template class is nice because it removes the need to split a template into two files, header and footer. Think of base_page as your base object, which views/test.php inherits from.

Example 2It is easy to add more interesting things in the construct() such as custom navigation menus for this 'test section' of your website. For example, alter the method:

public function __construct() parent::__construct(); $this->template->title = "Welcome to Kohana!"; $this->template->copyright = "&#169; Me, 2008"; // Look: $this->template->menu = new View('test_menu');

Save this as /application/views/test_menu.php

Page 77: KOHANA PHP framework

<div style="width: 100px; float: right; border: 1px solid lightgreen;"><ul> <li>menu 1</li> <li>menu 1</li></ul></div>

Alter /application/views/base_page.php to display the menu:

<html> <head> <title><?php echo $title; ?></title> </head> <body> <?php echo $menu ?> <?php echo $content ?> <?php echo $copyright; ?> </body></html>

Obviously you'll need to add some meaningful content to the views

Page 78: KOHANA PHP framework

Libraries

Page 79: KOHANA PHP framework

Archive Library

OverviewThe Archive Library is a convenient way of constructing Archives (Zip Files, Tar Files, etc) dynamically. It can persist them to the file system, or it can send the binary file directly to the user without saving to the hard drive.

Currently it only supports Zip Archives.

Loading the archive libraryThe Archive class is loaded into your controller using $this load library : → →

//load the archive class with the Zip driver to create Zip archives$this->archive=new Archive('zip');

Access to the library is available through $this archive →

The second argument of the load­library function contains the name of the archive driver you want to use. Currently only a driver for Zip archives is available.

Methods

add()add() adds files and directories to your archive. It accepts the following parameter:

• [string] path to file or dir. Relative paths must be relative to the root website dir. • [boolean] whether to scan the dir recursively – default = TRUE

This will result in file.txt being added to the archive:

$this->archive->add("files/uploads/file.txt");

save()save() saves the archive you've been creating to the disk.

• [string] path to save the archive file. Relative paths must be relative to the root website dir.

$this->archive->save("myarchive.zip");

download()download() offers the archive as a download to the user.

• [string] name to be given to the archive file

$this->archive->download("myarchive.zip");

Page 80: KOHANA PHP framework

Cache LibraryKohana's cache library can currently store caches in a file or SQlite. This is configurable by setting the driver. It utilizes tags and id's to identify caches.

For the API documentation:

• not available yet

View the page caching screencast from Woody Gilk (Shadowhand).

ConfigurationConfiguration is done in the application/config/cache.php file, if it's not there take the one from system/config and copy it.

$config['driver'] = 'file'; $config['params'] = APPPATH . 'cache'; $config['lifetime'] = 1800; $config['requests'] = 1000;

config['driver'] sets the driver. Currently only file and SQlite are available. $config['params'] driver specific parameters (in above example ­ path to server writable cache dir) $config['lifetime'] sets the lifetime of the cache. Specific lifetime can be set when creating a new cache. 0 means it will never be deleted automatically $config['requests'] average number of requests before automatic garbage collection begins. Set to a negative number will disable automatic garbage collection

Available drivers

• APC ­ Alternative Php Cache• Eaccelerator• File• Memcache• SQlite• Xcache

Methods

Loading the library $this->cache= new Cache;

Setting caches

set

$this→cache→set($id,$data,$tags = NULL, $lifetime = NULL) is used to set

Page 81: KOHANA PHP framework

caches.

• $id The id should be unique• $data If $data is not a string it will be serialized for storage. • $tagsdefaults to none, an array should be supplied. This is useful when grouping caches

together.• $lifetime specific lifetime can be set. If none given the default lifetime from the

configuration file will be used.

$data=array('Jean Paul Sartre', 'Albert Camus', 'Simone de Beauvoir'); $tags=array('existentialism','philosophy','french');$this->cache->set('existentialists',$data,$tags);

Finding and getting caches

get

$this→cache→get($id) retrieves a cache with the given $id, returns the data or NULL

print_r($this->cache->get('existentialists'));//returns:// Array ( [0] => Jean Paul Sartre [1] => Albert Camus [2] => Simone de Beauvoir )

find

$this→cache→find($tag) supply with a string, retrieves all caches with the given tag.

$food=array('French bread','French wine','French cheese'); $this->cache->set('food',$food,array('french')); print_r($this->cache->find('french'));//returns//Array ( [existentialists] => Array ( [0] => Jean Paul Sartre [1] => Albert Camus [2] => Simone de Beauvoir ) [food] => Array ( [0] => French bread [1] => French wine [2] => French cheese) )

Deleting cachesThere are several methods to delete caches

delete

$this→cache→delete($id) deletes a cache item by id, returns a boolean

$this->cache->delete('food');

delete_tag

$this→cache→delete_tag($tag) deletes all cache items with a given tag, returns a boolean

$this->cache->delete_tag('french');

Page 82: KOHANA PHP framework

delete_all

$this→cache→delete_all() deletes all cache items, returns a boolean

$this->cache->delete_all();

SQLite Driver SchemaIf you use the SQlite driver to store the caches the table can be constructed with this query.

CREATE TABLE caches( id varchar(127), hash char(40), tags varchar(255), expiration int, cache blob);

Calendar Library

OverviewProvides methods for generating and working with a calendar. The library outputs a calendar month in HTML, for use in the system view system/views/kohana_calendar.php

Loading the calendar libraryThe Calendar class is loaded into your controller using:

$this->calendar = new Calendar();

Access to the library is available through $this calendar →

The parameters of this constructor are:

• [integer] month• [integer] year• [boolean] put this argument on TRUE if you want weeks to start on monday (depends of

your localization)

Example$cal = new Calendar(1,2008); // January, 2008. The default is current month and yearecho $cal->render(); // the view is automatically rendered from the library

Produces an HTML calendar

January 2008Sun Mon Tue Wed Thu Fri Sat28 29 1 2 3 4 56 7 8 9 10 11 1213 14 15 16 17 18 19

Page 83: KOHANA PHP framework

20 21 22 23 24 25 2627 28 29 30 31 1 2

Adjusting the calendarThe layout of the calendar can be adjusted by creating the following file: application/views/kohana_calendar.php The native Kohana calendar file can be copied from system/views/kohana_calendar.php to have template to start working from.

Database LibraryThe database library provides database access to your application using drivers.

Currently we have the following drivers available:

1. MySQL2. MySQLi3. PostgreSQL4. PDOSqlite (available in SVN)

Table of Contents• Configuration • Connecting • Querying • Query Builder • Query Result • Metadata • Query Caching

Quick ExamplesThe following is example code for using common database functionality. For more in depth help please read the individual topics linked above.

Initializing the database$db = new Database(); // or $db = new Database('groupname'); // "default" is assumed if groupname is not given

Simple Query$result = $db->query('SELECT username,password,email FROM users'); foreach ($result as $row) echo $row->username; echo $row->password;

Page 84: KOHANA PHP framework

echo $row->email;

Quick Example 2This demonstrates using the query results in a template.

Queryclass Clients_Controller extends Controller public function index() $db = new Database; $result = $db->query('SELECT name, code FROM clients'); $v = new View('clients'); $v->result = $result; $v->render(TRUE);

Template<html><head><style>/* * Zebra rows: When CSS3 is done we could simply use: * tr :nth-child(odd) background-color: #D0D0D0; * but for now we use PHP and CSS */ table.db tr background-color: #F0F0F0; table.db tr.odd background-color: #D0D0D0; table.db th color: #f0f0f0; background-color: #303030; </style></head><body> <h2>Client List</h2><hr/> <table class="db"><tr> <th>Client</th> <th>ID</th></tr><?php foreach( $result as $row ):?><tr <?= text::alternate( '', ' class="odd"' ) ?>> <td><?= $row->name ?> </td> <td><?= $row->code ?> </td></tr><?php endforeach; ?></table> </body>

Page 85: KOHANA PHP framework

Encrypt Library

OverviewThe Encrypt Library provides an easy way to encrypt and decrypt data using symmetric keys.

You can choose what cypher you'd like the algorithm to use and you can specify your own key for the encryption.

Loading the encryption libraryThe Encryption class is loaded into your controller using $this load library : → →

$this->encrypt=new Encrypt;

Access to the library is available through $this encrypt →

ConfigurationConfiguration is done in application/config/encryption.php if it's not there take the one from system/config and copy it.

$config['key'] = 'YOUR CYPHER KEY'; $config['mode'] = MCRYPT_MODE_NOFB; $config['cipher'] = MCRYPT_RIJNDAEL_128;

config['key'] sets the key used for encryption. It should be at least 16 characters long and contain letters, numbers, and symbols. $config['mode'] the MCrypt encryption mode to use. See http://php.net/mcrypt for more information, but you probably won't need to change this. $config['cipher'] sets the cipher to be used for encryption.

Methods

encode($data)$this→encrypt→encode($data) returns an encrypted version of $data using the cipher and key specified in the configuration file.

$encrypted_text = $this->encrypt->encode('The Answer is 42'); echo $encrypted_text;

decode($encrypted)$this→encrypt→decode($encrypted) returns a decrypted version of $encrypted using the cipher and key specified in the configuration file.

$encrypted_text = $this->encrypt->encode('The Answer is 42'); echo $this->encrypt->decode($encrypted_text);

Page 86: KOHANA PHP framework

Image LibraryProvides methods for the dynamic manipulation of images. Various image formats such as JPEG, PNG, and GIF can be resized, cropped, rotated and sharpened.

All image manipulations are applied to a temporary image. Only the save() method is permanent, the temporary image being written to a specified image file.

Image manipulation methods can be chained efficiently. Recommended order: resize, crop, sharpen, quality and rotate or flip

Loading the Image libraryUses a driver, configured in config/image.php. The default driver uses the GD2 library, bundled with PHP. ImageMagick may be used if available.

When loading the library, a path to the image file, (relative or absolute) must be passed as a parameter.

Load the Image Library in your controller using the new keyword:

$this->image = new Image('./photo.jpg');

Access to the library is available through $this→image Some methods are chainable.

Methods

resize()resize() is used to resize an image. This method is chainable. By default, the aspect ratio will be maintained automatically.

• [integer] Width in pixels of the resized image.• [integer] Height in pixels of the resized image.• [integer] Master dimension, default is Auto. Options : Image::NONE, Image::AUTO,

Image::HEIGHT, Image::WIDTH

Example: // Resize original image to Height of 200 pixels, using height to maintain aspect ratio.$this->image->resize(400, 200, Image::HEIGHT)// Note: Passing width = 400 has no effect on the resized width, which is controlled by the 3rd argument, maintain aspect ratio on height $this->image->resize(400, 200, Image::NONE)//Note: The output image is resized to width of 400 and height of 200, without maintaining the aspect ratio

crop()crop() is used to crop an image to a specific width and height. This method is chainable.

The top and left offsets may be specified. By default 'top' and 'left' use the 'center' offset.

Page 87: KOHANA PHP framework

• [integer] Width in pixels of the cropped image.• [integer] Height in pixels of the cropped image.• [integer] Top offset of input image, pixel value or one of 'top', 'center', 'bottom'.• [integer] Left offset of input image, pixel value or one of 'left', 'center', 'right'.

Example: // Crop from the original image, starting from the 'center' of the image from the 'top' and the 'center' of the image from the 'left'// to a width of 400 and height of 350.$this->image->crop(400, 350)

rotate()rotate() is used to rotate an image by a specified number of degrees. This method is chainable. The image may be rotated clockwise or anti­clockwise, by a maximum of 180 degrees.

• [integer] Degrees to rotate. (negative rotates anti­clockwise) There is no default.

Example: // Rotate the image by 45 degrees to the 'left' or anti-clockwise.$this->image->rotate(-45)

flip()flip() is used to rotate an image along the horizontal or vertical axis. The method is chainable.

• [integer] Direction. Horizontal = 5, Vertical = 6

Example: // Rotate the image along the vertical access.$this->image->flip(6);

sharpen()sharpen() Is used to sharpen an image by a specified amount. This method is chainable.

• [integer] Sharpen amount to apply to image. Range is between 1 and 100. Optimal amount is about 20. There is no default.

Example: // Sharpen the image by an amount of 15.$this->image->sharpen(15);

quality()quality() Is used to adjust the image quality by a specified percentage. This method is chainable.

Note: The method is for reducing the quality of an image, in order to reduce the file size of the image, saving bandwidth and load time. It cannot be used to actually improve the quality of an input image.

• [integer] Percentage amount to adjust quality. Range is between 1 and 100. Optimal

Page 88: KOHANA PHP framework

percentage is from 75 to 85. There is no default.

Example: // Reduce image quality to 75 percent of original$this->image->quality(75);

save()save() Is used to save the image to a file on disk. This method is NOT chainable. The default is to overwrite the input image file. Accepts a relative or absolute file path.

• [string] The file path and output image file name. Default is to overwrite input file.

Example: // Save image and overwrite the input image file$this->image->save();//$this->image->save('./new-image.jpg'); // Save image to a new file.

Full ExamplePlace this code into a controller

// The original image is located in folder /application/upload.$dir = str_replace('\\', '/', realpath(dirname(__FILE__).'/../upload')).'/'; $image = new Image($dir.'moo.jpg'); // Instantiate the library $image->resize(400, NULL)->crop(400, 350, 'top')->sharpen(20)->quality(75); // apply image manipulations $image->save($dir.'super-cow-crop.jpg'); // Write the changed image to a new file in the original input folder echo Kohana::debug($image); // Display some useful info about the operation **for debugging only**.

Input LibraryThe input library is useful for two things: ­ pre­process global input for security ­ provide some useful functions for retrieving input data

Note:

• The $_REQUEST and $_GLOBAL variables are not available within Kohana. • $_POST, $_GET, $_COOKIE and $_SERVER are all converted to utf­8.• Global GET, POST and COOKIE data are sanitized when the Input library is loaded

Loading the libraryThis library is automatically loaded by the controller so you don't need to load it yourself. It is accessed by $this→input in the controller scope.

Page 89: KOHANA PHP framework

Methods

get()allows you to retrieve GET variables. if global XSS filtering is on (config) then data returned by this function will be filtered.

• [string] variable to retrieve – default = empty array (returns all variables)

//URL is http://www.example.com/index.php?articleId=123&file=text.txt//Note that print statements are for documentation purpose only print Kohana::debug($this->input->get());print Kohana::debug($this->input->get('file'));

It will result in HTML as:

Array( [articleId] => 123 [file] => text.txt) text.txt

You can also manually XSS clean the request by passing TRUE as the second parameter.

post()allows you to retrieve POST variables. if global XSS filtering is on (config) then data returned by this function will be filtered.

• [string] variable to retrieve – default = empty array (returns all variables)

//POST variables are articleId=123 and file=text.txt//Note that print statements are for documentation purpose only print Kohana::debug($this->input->post());print Kohana::debug($this->input->post('file'));

It will result in HTML as:

Array( [articleId] => 123 [file] => text.txt) text.txt

You can also manually XSS clean the request by passing TRUE as the second parameter.

cookie()allows you to retrieve COOKIE variables. if global XSS filtering is on (config) then data returned by this function will be filtered.

• [string] variable to retrieve – default = empty array (returns all variables)

Page 90: KOHANA PHP framework

//COOKIE name is "username" and the contents of this cookie is "aart-jan".//Note that print statements are for documentation purpose only print Kohana::debug($this->input->cookie());print Kohana::debug($this->input->cookie('username'));

It will result in HTML as:

Array( [username] => aart-jan)aart-jan

You can also manually XSS clean the request by passing TRUE as the second parameter.

server()allows you to retrieve SERVER variables. if global XSS filtering is on (config) then data returned by this function will be filtered.

• [string] variable to retrieve – default = empty array (returns all variables)

//Note that print statements are for documentation purpose onlyprint Kohana::debug($this->input->server('HTTP_HOST')); //this example ran on a local server

It will result in HTML as:

localhost

You can also manually XSS clean the request by passing TRUE as the second parameter.

ip_address()'ip_address' returns the IP­address of the user visiting using your webapplication. It returns '0.0.0.0' if there's no IP.

print $this->input->ip_address(); //this example ran on a local server

It will result in HTML as:

127.0.0.1

valid_ip()'valid_ip' will check whether the specified IP is a valid IPV4 ip­address according to the RFC specifications.

• [string] IP address to be validated

This function is identical to the IP address validation helper.

user_agent()'user_agent' returns the user agent of the current request. Be careful! Even if global XSS filtering is on, the data returned by this function will not be filtered!

Page 91: KOHANA PHP framework

print $this->input->user_agent();

This could result in HTML as:

Mozilla/5.0 (Windows; U; Windows NT 6.0; nl; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11

xss_clean()allows you to clean a string to make sure it is safe.

• [string/array] The string or the array of strings to clean

echo $this->input->xss_clean($suspect_input);

ORM LibraryThe ORM library is the Object­Relational mapper for Kohana. It provides ways to handle records in your database as if they were objects and it manages relationships between your tables. It is not loaded like other libraries but works in the model. For example, if you have a table users (plural) you would have a model User_Model (singular) in your application/models directory as follows:

user.php

class User_Model extends ORM

If you plan to override the constructor of the ORM model you need this code:

class User_Model extends ORM public function __construct($id=FALSE) parent::__construct($id);

Without passing the $id to the parent, ORM won't work. You do not need to put a construct method in every model!

Tutorial: Learn the Basics of the Kohana ORM Library

Important: The ORM library is a complete replacement of the Kohana Model library (it does not extend the Model class) and creates a “static” connection to the database object. Therefore, if you create a custom method in a Model that extends ORM, you need to access the Kohana database library methods as “self::$db ___”. For example: →

public function username_exists($name) return (bool) self::$db->where('username', $name)->count_records('users');

ORM conventionsIn order for ORM to work properly there are some conventions that must be upheld.

Page 92: KOHANA PHP framework

• Table names are plural, e.g. users• Model names are the singular of the table name (e.g. user) with _Model appended to the

model name, e.g. User_Model• Each table has a primary key id (except for join tables)• Foreign keys in a table are in the form of related_id, e.g. user_id, book_id• Join tables are in the form parent_child, e.g. if tracks belongs_to_many albums, then the table is albums_tracks.

RelationshipsRelationships are declared in the model.

protected $has_one = array(); protected $has_many = array(); protected $belongs_to = array(); protected $belongs_to_many = array(); protected $has_and_belongs_to_many = array();

It is vital you use pluralization and singularization correctly. E.g

Class Dorm_Model protected $has_many=array('students');//plural - a dorm has many studentsclass Student_Model protected $belongs_to=array('dorm'); //singular, - a student belongs to (one) dorm

These tutorials can help you with relationships in ORM.

• A tutorial on the has_one/belongs_to relationship• A tutorial on the has_many/belongs_to relationship

A note about ORM relationships in Kohana:In ORM, when a relationship starts with “has_” it shows “ownership”, or if you want to think of it another way, “parent” and “child”. So, when you have users and roles, the users has_and_belong_to_many roles, but roles just belong_to_many users. The primary reason for this is to enable the ORM library to choosewhich table name comes first in a joining/pivot table. In the example of users and roles, because users “own” roles, the table is called users_roles.

In theory, you could flip the relationship, but ORM restricts finding to objects that “own” other objects. For instance, if you used roles as the “owner” object, you would not be able to do $user find_related_roles(), but you would be able to do $role find_related_users(). In reality, it→ → makes sense that the user can find the roles they own. ORM does not yet support this from both directions.

ORM Factory methodYou can also use the factory method to make chaining of methods easier.

$users=ORM::factory('user')->find_all_by_email('[email protected]');//equivalent to$user=new User_Model;$users=$user->find_all_by_email('[email protected]');

Page 93: KOHANA PHP framework

It gets the user model, finds all records with a certain email address. You can also use the second argument to quickly find a record.

$user=ORM::factory('user',1);$user->delete();//equivalent to$user=new User_Model(1);$user->delete();

Get the user with id=1 and delete it in the second line.

Methods

find()find() is used to find a single record in a table if you supply the id of the record. Can also return all records if you supply the constant ALL

Example

$user=new User_Model();$user->find(1);echo $user->email; //outputs the field email of table users of record with id = 1 $user->find(ALL); // see find_all();

find_allfind_all is equal to find(ALL)

foreach($user->find_all() as $person)echo $person->email;//output emails of all users

find_byfind_by sets the model to the first record that matches the criterion. This method is chainable.

$user=new User_Model;$user->find_by_email('[email protected]');

A variation is you can use multiple values, eg:

$user->find_by_email_and_password('[email protected]', 'secret');

or

$user->find_by_email_or_username('[email protected]', 'example');

You can use any number of values, but you can only use either _and_ or _or_, not both.

find_all_byfind_all_by returns an array of all records that match the criterion

Page 94: KOHANA PHP framework

$user=new User_Model;$users = $user->find_all_by_email('[email protected]');

You can use _and_ or _or_, just like find_by (see above).

find_related_find_related_ returns the all related records. You must set a relationship in the model for this to work.

$user=new User_Model;$user->find(1);$user->find_related_pages(); //finds all related pages to user with id = 1

hasTest for existence of relationship.

For example if $has_many = array('dogs') then you can test for a relationship

if($pet_enthusiast->has_dog($dog)) echo 'He has a dog!';

addUsed with the relationships defined in the model to provide handy relationship methods.

For example if $has_many = array('dogs') then you may $pet_enthusiast→add_dog($dog).

Syntax/** * @param mixed $var Can be an object, an array of strings which associate to object models, or a string which will be found using $model->find($var) * @return bool Can also return the boolean result from $model->save() */$object->add_$model(mixed $var);

removeRemoves the $dog from the $pet_enthusiast.

Syntax/** * @param mixed $var Can be an object, an array of strings which associate to object models, or a string which will be found using $model->find($var) * @return bool Can also return the boolean result from $model->save() */$object->remove_$model(mixed $var);

Page 95: KOHANA PHP framework

Example

// For the pet enthusiast, to remove a dog$pet_enthusiast->remove_dog( $dog );

savesave saves an object to the database. If it doesn't exist it uses an INSERT statement, if it does it uses an UPDATE statement.

Insert example

$user=new User_Model;$user->email='[email protected]';$user->save(); //will insert a new user into the table with email being '[email protected]'

Update example

$user=new User_Model;$user->find_by_email('[email protected]');$user->email('[email protected]');$user->save(); //will update a the [email protected] user with a new email [email protected]

deletedelete deletes the current object.

$user=new User_Model;$user->find(1);$user->delete();

delete_alldelete_all deletes all records in the table.

$user=new User_Model;$user->delete_all(); //alternate syntax$user->delete(ALL);

loaded

clearEmpties an object setting its properties to ' '. Also resets select and where

as_arrayReturns the object as an array with key/value pairs.

Page 96: KOHANA PHP framework

Properties

whereWhich criteria should the query use.

$user=new User_Model;$user->where('role','admin');$user->find_by_email('[email protected]');

Will add extra criterion, role should be admin.

selectWhich fields to fetch

$user=new User_Model;$user->select('email');$user->find_by_email('[email protected]');

Will only select the email field.

auto_saveIf set to TRUE execute save() on the destruction of the object. You then don't have to call save() manually. If it's set to FALSE and you don't call save() means losing changes made to the object.

• Defaults to FALSE

$user=new User_Model;$user->auto_save=TRUE;

Using DB Builder methodsIn Kohana's ORM you can still use some of the methods of the DB builder

Example

//Fetch the latest 10 articles$articles=new Article_Model(); $articles=$articles->orderby('id','desc')->limit(10)->find_all();

The following db builder methods cannot be used

• query• get• list_fields• field_data

Note: when chaining methods like this, find_all() or find(), find_by() etc. needs to be last since it will execute the actual query.

Page 97: KOHANA PHP framework

Changing the where keyBe default the find() method will use the 'id' field as a criterion for selecting records. I.e. find(1) will return the record with id=1. The same goes for new User_Model(1) syntax. In your model you can override the where_key() method so you can change the default criterion field.

user.php

class User_Model extends ORM protected function where_key($id = NULL) return 'name';

Now find('your_username') as well as new User_Model('your_username') will work.

You can expand this method for some extra tricks.

user.php

protected function where_key($id = NULL) if ( ! empty($id) AND is_string($id) AND ! ctype_digit($id)) return valid::email($id) ? 'email' : 'username'; return parent::where_key($id);

Now the method will check if the argument is a string. If so, it will check for email validity and if true will say the where_key is 'email' if not it is 'username'. If the argument is not a string it is taken to be an digit and therefore an id and therefore the parent will return the where_key as being 'id'.

Pagination LibraryThe Pagination library automatically generates styled links like, « First < 1 2 3 4 5 > Last » for navigating through pages in a website.

The links refer to the Page number and Not the offset of the data.

The library is easily configurable. Default Pagination Settings are located in system/config/pagination.php. You can override the system settings by creating a pagination config file in your application/config or by passing configuration settings to the library at run time.

Please note that the library does not interact with your data in any way, it generates links. The developer must write the code that fetches the data referred to by the links. A method is provided to help calculate SQL offsets.

The page links are generated using a View file located in system/views/pagination. Four styles are provided. You may edit these to suit your needs, or you can create a new, custom pagination view. You may also override the system styles by copying the views to your application/views/pagination directory.

Page 98: KOHANA PHP framework

Loading the Pagination libraryLoad the Pagination class in your controller using the new keyword

Configuration settings are obtained from config/pagination.php Settings may also be passed dynamically to the class as an array.

$this->pagination = new Pagination($config);

Access to the library is available through $this→pagination

Methods

initialize()$this→pagination→initialize() is used to dynamically set pagination configuration. It is automatically called by the library constructor, so there is no need to call this method explicitly, unless you wish to overwrite a config setting dynamically.

// Will overwrite only the existing setting for this config item$this->pagination->initialize(array('uri_segment' => 'pages'));

create_links()In Kohana 2.2 create_links() has been renamed to render().

$this→pagination→create_links() is used to generate the link output for display. Allows you to select the pagination style dynamically. Please note: The links may also be output by simply echoing $this→pagination

// Will overwrite the default 'classic' style with 'digg' style$this->pagination->create_links('digg'));

sql_offset()Note: this method is deprecated in version 2.1 – use $this→pagination→sql_offset property instead.

$this→pagination→sql_offset() is used to calculate the offset of the row to fetch, for the selected link page number. The generated pagination links refer to a logical page number, not an SQL row number. This method will automatically calculate the required row offset for you, from the current page number and the configured items­per­page setting.

$this->pagination->sql_offset(); // returns sql row offset as an integer

sql_limit()Note: this method is deprecated in version 2.1 – use $this→pagination→sql_limit property instead.

$this→pagination→sql_limit() is used to automatically generate SQL code, with the correct LIMIT and OFFSET clause for the selected page number.

echo $this->pagination->sql_limit(); // outputs the SQL below

Page 99: KOHANA PHP framework

LIMIT 3 OFFSET 6

Pagination class propertiesThe following pagination class properties are available for use in your controller:

• url• current_page• total_pages • current_first_item • current_last_item • first_page • last_page • previous_page • next_page• sql_offset • sql_limit

Example One$this->pagination = new Pagination(array( // 'base_url' => 'welcome/pagination_example/page/', // base_url will default to current uri 'uri_segment' => 'page', // pass a string as uri_segment to trigger former 'label' functionality 'total_items' => 254, // use db count query here of course 'items_per_page' => 10, // it may be handy to set defaults for stuff like this in config/pagination.php 'style' => 'classic' // pick one from: classic (default), digg, extended, punbb, or add your own!)); // Just echoing it is enough to display the links (__toString() rocks!)echo 'Classic style: '.$this->pagination; // You can also use the create_links() method and pick a style on the fly if you wantecho '<hr />Digg style: '.$this->pagination->create_links('digg'); echo '<hr />Extended style: '.$this->pagination->create_links('extended'); echo '<hr />PunBB style: '.$this->pagination->create_links('punbb'); echo 'done in execution_time seconds';

This will output:

Classic style:

1 2 3 4 5 6 7 8 9 10 11 13 14 15 16 17 18 19 20 21 22 23 24 25 26 > last ›

Digg style:

« previous 1 2 3 4 5 6 7 8 9 10 … 25 26 next »

Page 100: KOHANA PHP framework

Extended style:

« previous | page 1 of 26 | items 1–10 of 254 | next »

PunBB style:

pages: 1 2 3 … 26

If you are seeing “pagination.next”, this is because Pagination uses Kohana::lang to look up the text from your locale. Pagination locale text is stored in “system/i18n/[your_locale]/pagination.php”

Example TwoExcerpt from the controller method

public function page($page_no) $content = new View('pages/items'); $items = new Items_Model; $content->items = $items->get_items($page_no, 10); // page to get starting at offset, number of items to get $this->pagination = new Pagination(array( 'base_url' => 'items/page/', // Set our base URL to controller 'items' and method 'page' 'uri_segment' => 'page', // Our URI will look something like http://domain/items/page/19 'total_items' => count($items->get_item_count()) // Total number of items. // Note that other config items are obtained from the pagination config file. )); $this->template->set(array( 'title' => 'Items', 'content' => $content ));

Excerpt from the View, showing how to display the links.

<h3>Items</h3><?php echo $this->pagination->create_links() ?>

Creating Customized Pagination StylesThe default Kohana pagination styles are located in the system/views/pagination directory. To customize an existing style or create a new pagination style, do the following:

1. Create a new directory called application/views/pagination2. Copy one of the existing pagination styles from system/views/pagination (e.g

classic.php) to application/views/pagination3. You have the option to either rename the existing pagination style to create a completely new

style (e.g. custom.php) or keep the same name to override one of the default styles.

Page 101: KOHANA PHP framework

Note: If you create a new pagination style (by renaming the file), you must reference the new custom filename when creating your pagination links (e.g. $this→pagination→create_links('custom'))

Payment Library

OverviewThe payment library allows you to easily process e­commerce transactions without having to worry about all the backend details of connecting and setting up the cURL options. It has many features:

1. An extremely easy API (only one method required to process a transaction!)2. Detailed error reporting3. Extensible with backend drivers to connect to many different payment gateways4. Support for credit card gateways as well as PayPal­like gateways

Using the library is very simple. Just set the fields required by your driver, and process().

$payment = new Payment();$payment->card_num = '1234567890123456';$payment->exp_date = '0510'; if ($status = $payment->process() === TRUE) // Report successful transactionelse // $status has the error message, so display an error page based on it

ConfigurationIn system/config/payment.php there is a sample config for each payment gateway we support. Simply copy this file to your application directory, and remove the drivers you are not using. The library can support using more than one driver per application by passing the driver name to the constructor:

$paypal_payment = new Payment('Paypal');$authorize_payment = new Payment('Authorize');

After you remove the non­required config lines, modify your driver config as needed. Usually this will include some sort of API username/password combination, but it differs for each driver.

AttributesThe payment library has a set of default attributes it uses to send payments to the gateway. These attributes are fairly self explanatory and are listed below.

• card_num• exp_date• cvv• description

Page 102: KOHANA PHP framework

• amount• tax• shipping• first_name• last_name• company• address• city• state• zip• email• phone• fax • ship_to_first_name• ship_to_last_name• ship_to_company• ship_to_address• ship_to_city• ship_to_state• ship_to_zip

Specific drivers may require some or all of these fields. They may also have driver specific fields that are noted in the Driver section.

MethodsThe payment library has a minimal set of methods to use:

set_fields()This method allows you to set bulk payment attributes with an array.

$payment = new Payment(); $attributes = array( 'card_num' = '1234567890123456', 'exp_date' = '0510'; $payment->set_fields($attributes);

process()This method does the magic. After you set your attributes, simply call this method in an if test. The method returns TRUE on successful payment transaction or an error string on failure. It is up to you how to handle the failure.

DriversThe payment library uses drivers much like the Database library does in order to keep the API consistent between payment gateways. It currently supports the following gateways:

Page 103: KOHANA PHP framework

1. Authorize.net2. Trident Gateway3. TrustCommerce4. YourPay.net5. PayPal

Authorize.net

Required Fields

1. card_num2. exp_date3. amount

Trident Gateway

Required Fields

1. card_num2. exp_date3. amount

TrustCommerce

Required Fields

1. card_num2. exp_date3. amount

YourPay.net

Required Fields

1. card_num2. exp_date3. amount4. tax5. shipping6. cvv

Driver Specific Details

The amount above is the subtotal. Tax and Shipping get added to the amount to form the grand total inside the driver.

Page 104: KOHANA PHP framework

PayPal

Required Fields

1. amount2. payerid (after paypal authentication)

Driver Specific Details

Using the PayPal driver is a little different than a normal credit card transaction. It requires two process() commands to be run. The first one will send the user to PayPal to authenticate, and the second one will actually run the transaction. Below is an example of this.

class Paypal_Controller extends Controller // This will demo a simple paypal transaction. It really only comes down to two steps. function __construct() parent::__construct(); $this->paypal = new Payment(); // This will set up the transaction and redirect the user to paypal to login function index() $this->paypal->amount = 5; $this->paypal->process(); // Once the user logs in, paypal redirects them here (set in the config file), which processes the payment function return_test() $this->paypal->amount = 5; $this->paypal->payerid = $this->input->get('payerid'); echo ($this->paypal->process()) ? "WORKED" : "FAILED"; // This is the cancel URL (set from the config file) function cancel_test() echo 'cancelled'; // Just some utility functions. function reset_session() $this->session->destroy(); url::redirect('paypal/index'); function session_status() echo '<pre>'.print_r($this->session->get(), true);

Page 105: KOHANA PHP framework

Writing Your Own DriverThere are many more payment gateways than there are drivers provided by Kohana. We encourage you to write your own when you encounter a gateway not supported by the library. An easy way to do it is like so:

1. Add a new entry in config/payment.php with your driver details. Use the previous entries as an example.

2. Copy the Trident Gateway driver and rename it to *Gateway Name*.php3. Alter the required fields array as instructed in the gateway's API manual (You have this,

right? ;)4. Modify the fields array to include all the available relevant fields for the gateway5. Modify the constructor to set default values from the config file (API username/password for

example)6. Modify the set_fields() method to do variable translation (for example if your gateway names

cc_num something different. Look in your API manual for details.)7. Modify the $post_url ternary statement to include the correct test and live mode API URLs8. Modify how the return statement handles success and error based on what the specific

gateway status message is (Look in you API manual)

Profiler LibraryThe Profiler adds useful information to the bottom of the current page for debugging and optimization purposes.

• Benchmarks: The times and memory usage of benchmarks run by the Benchmark library.

• Database Queries: The raw SQL of queries executed through the Database library as well as the time taken and number of affected rows.

• POST Data: The names and values of any POST data submitted to the current page.

• Session Data: All data stored in the current session if using the Session library.

• Cookie Data: The names and values of any cookies found for the current domain.

How to useTo enable the profiler output on your pages simply load the library:

$this->profiler = new Profiler;

When loaded the profiler will add itself to the system.display event, calling the render() method when the page is being displayed and attaching the output to the bottom of the page.

The profiler can also be added to the library autoload list in config.php and it will automatically be run on every page of your site.

How to disableThe automatic rendering of the output can be disabled with the following code:

$this->profiler->disable()

Page 106: KOHANA PHP framework

This is mostly useful when autoloading the profiler to disable the output for certain pages.

Getting the outputThe rendered output may be returned as a string at any time during the page execution by passing TRUE as the first parameter in render():

$output = $this->profiler->render(TRUE)

Note: This will stop any benchmarks currently being run. Only benchmarks and queries that have been run up until this call will be shown in the output.

Configure the profilerEdit config/profiler.php to configure which items (post, cookie, session, database, benchmarks) the profiler will show.

This change is made to application/config/profiler.php so as to apply only to the specific application.

/** * Show everything except database queries. (Other entries are default TRUE, read from system profiler config. */$config['database'] = FALSE;

A complete profiler.php would look like this

<?php defined('SYSPATH') or die('No direct script access.'); $config['post'] = FALSE;$config['cookie'] = FALSE;$config['session'] = FALSE;$config['database'] = FALSE;$config['benchmarks'] = TRUE;

Remember to set at least one of the items to TRUE otherwise the profiler will die in a trace error.

Session LibraryEnables applications to persist user state across pages.

What are sessions?Sessions enable you to store and retrieve data between requests on a per­user basis. Typically, since each web page (or AJAX request, etc) is an individual request, there is no way to set a variable in one request and get it's value in another. Sessions are one of several mechanisms that exist to overcome this limitation.

Sessions are useful where a small amount of data needs to be persisted across most pages and that data is specific to the particular browser session. For example, if your website has a “login” page, you may wish to remember, for one specific web browser only, that a particular user has logged­in.

If you want to store more general data between requests and it is less of an issue that the data be

Page 107: KOHANA PHP framework

associated with only one browser session, other mechanisms may be more appropriate:

• Kohana's Cache library • PHP's shared memory facility

Starting a SessionTo load the Session library, add the following code to your controller constructor, or to a particular controller method: Add the code:

$this->session = new Session;

The above line of code has two effects:

• The Session library will be available via $this→session.• If any current session data exists, it will become available. If no session data exists, a new

session is automatically started.

Working with sessionsThe following methods are available in the Session library:

create()$this→session→create() can be called to create a new session. It will destroy any current session data.

Note that you do not need to call this method to enable sessions. Simply loading the Session library is enough to create a new session, or retrieve data from an existing session.

id()$this→session→id() retrieves the ID of the current session.

For example,

echo 'Current session ID: ' . $this->session->id();

regenerate()$this→session→regenerate() causes the session ID to be regenerated whilst keeping all the current session data intact.

Note, this is done automatically by the framework after a number of requests for security purposes (set by the session.regenerate config value).

destroy()$this→session→destroy() destroys all session data, including the browser cookie that is used to identify it.

Page 108: KOHANA PHP framework

Working with session dataThe Session library arranges for PHP's inbuilt sessions array, $_SESSION, to use the session libraries driver. This means that accessing session data can be done in the normal way.

For example,

// get some session data$data = $_SESSION['fish']; // set some session data$_SESSION['fish'] = 5;

In addition to this, the Session library also provides it's own methods to deal with session data. These are:

get()$this→session→get($key = FALSE, $default = FALSE) retrieves a named value from the session data.

• [mixed] $key specifies the name of the data to retrieve from the session. If $key is FALSE, get() returns an array containing all of the data in the current session.

• [mixed] $default specifies a default value to be returned if the named data does not exist in the session.

For example,

// returns value of foo. If it doesn't exist, returns the string 'bar' instead.$value = $this->session->get('foo','bar');

get_once()$this→session→get_once($key) works the same as get() except that it also deletes the data from the current session afterwards.

For example,

// returns value of foo and deletes foo from the session.$value = $this->session->get_once('foo');

set()$this→session→set($keys, $val = FALSE) is used to set data in the current session.

• [mixed] $keys can either specify the name of the data to set in the session, or it can be an array of “key value” pairs (in which case the ⇒ $val argument is ignored).

• [mixed] if $keys is the name of the data to set in the session, $val specifies the value of that data.

For example,

// set some_var to some_val$this->session->set('some_var', 'some_value'); // set several pieces of session data at once by passing an array to set()$this->session->set(array('fish' => 5, 'foo' => 'bar'));

Page 109: KOHANA PHP framework

del()In Kohana 2.2 del() has been renamed to delete().

$this→session→del($keys) is used to delete a piece of data from the current session.

• [mixed] $keys specifies the name of the piece of data to delete from the session. It can also be an array of several keys to be deleted.

For example,

// delete foo$this->session->del('foo'); // delete several pieces of data from the session by passing an array$this->session->del(array('bar', 'bas'));

"Flash" session Data“Flash” session data is data that persists only until the next request. It could, for example, be used to show a message to a user only once.

As with other session data, you retrieve flash data using $this→session→get().

set_flash()$this→session→set_flash($keys, $val = FALSE) sets flash data in the current session.

• [mixed] $keys can either specify the name of the data to set in the session, or it can be an array of “key value” pairs (in which case the ⇒ $val argument is ignored).

• [mixed] if $keys is the name of the data to set in the session, $val specifies the value of that data.

For example,

// set user_message flash session data$this->session->set_flash('user_message', 'Hello, how are you?'); // set several pieces of flash session data at once by passing an array$this->session->set_flash(array('user_message' => 'How are you?', 'fish' => 5));

keep_flash()Usually, flash data is automatically deleted after the next request. Sometimes this behaviour is not desired, though. For example, the next request might be an AJAX request for some data. In this case, you wouldn't want to delete your user_message in the example above because it wouldn't have been shown to the user by the AJAX request.

$this→session→keep_flash($keys) can be used to keep flash session data for one more request (aka “freshening” flash data).

• [string] $keys specifies the name(s) of the flash session variables to keep.

// Don't delete the user_message this request$this->session->keep_flash('user_message'); // Don't delete messages 1-3

Page 110: KOHANA PHP framework

$this->session->keep_flash('message1', 'message2', 'message3');

If you don't supply any arguments to the function all current flash session variables will be freshened.

// Don't delete any flash variable$this->session->keep_flash();

Freshening multiple or all flash session variables is Kohana 2.2 functionality.

Configuring a SessionEdit the config file application/config/session.php

/* * File: Session * * Options: * driver - Session driver name: 'cookie','database' or 'native' * storage - Session storage parameter, used by drivers * name - Default session name * validate - Session parameters to validate * encryption - Encryption key, set to FALSE to disable session encryption * expiration - Number of seconds that each session will last (set to 0 for session which expires on browser exit) * regenerate - Number of page loads before the session is regenerated (set to 0 for NO automatic regeneration) * gc_probability - Percentage probability that garbage collection will be executed */$config = array( 'driver' => 'cookie', 'storage' => '', 'name' => 'kohanasession', 'validate' => array('user_agent'), 'encryption' => FALSE, 'expiration' => 7200, 'regenerate' => 3, 'gc_probability' => 2);

Session StorageBy default session data is stored in a cookie. You can change this in the file config/session.php. The driver can be set to 'cookie', 'database' or 'native'. Session name and other configuration options can also be set here.

Using a Database

The storage setting in config/session.php must be set to the name of the database table. Optionally you can add a group in config/database.php using the same name, if this is not found it will use the default.

Table schema

CREATE TABLE `kohana_session` ( `session_id` varchar(40) NOT NULL,

Page 111: KOHANA PHP framework

`last_activity` int(10) UNSIGNED NOT NULL, `data` text NOT NULL, PRIMARY KEY (`session_id`))

Using a Cache

The storage setting in config/session.php must be set to

Cache config

$config['driver'] = 'cache'; $config['storage'] = array( 'driver' => 'apc', 'requests' => 10000 );

Lifetime does not need to be set as it is overridden by the session expiration setting.

InstanceTo retrieve the instantiated session library you can use the instance() method. If no instance is available one will be created.

$session=Session::instance();$var = $session->get('session_item);

Session instance methods can be called directly.

$var = Session::instance()->get('session_item');Session::instance()->set('session_item', 'item value');

URI LibraryThe URI class provides the methods for working with URI's and URI segments. If you use routing it also has methods to work with rerouted URI's.

Note:

This library is initialized automatically by Kohana. No need to do it yourself

Methods

segment()segment($index = 1, $default = FALSE) retrieves a specific URI segment. Returns $default when the segment does not exist.

//url: http://www.example.com/index.php/article/paris/hilton/

The segments would be:

1. article2. paris

Page 112: KOHANA PHP framework

3. hilton

echo $this->uri->segment(3); // Returns 'hilton'echo $this->uri->segment(4, 'spears'); // Returns 'spears'

Note: this method also accepts strings. When a string is given as first argument, it will return the segment following the string.

echo $this->uri->segment('article'); // Returns 'paris'echo $this->uri->segment('paris'); // Returns 'hilton'echo $this->uri->segment('hilton'); // Returns FALSE

rsegment()Identical to segment() except that it uses the rerouted URI to retrieve the segments from.

segment_array()segment_array($offset,$associative) returns an array of all the URI segments

total_segments()total_segments() returns the number of segments

echo $this->uri->total_segments(); //returns 3

string()string() returns the entire URI as a string

echo $this->uri->string(); // returns: article/paris/hilton/

last_segment()last_segment() returns the last segment of an URI

echo $this->uri->last_segment(); // returns: hilton

argument()argument() returns the requested arguments. This differs from segments as it will only look at the arguments given and skip the controller and method segment.

echo $this->uri->argument(1); // returns: hilton

argument_array()argument_array() returns an array containing all arguments

echo $this->uri->argument_array(); // returns: array( 'hilton' )

Page 113: KOHANA PHP framework

total_arguments()total_arguments() returns the total number of arguments.

echo $this->uri->total_arguments(); // returns: 1

build_array()This method only exists in version 2.2

User Agent LibraryThis library is deprecated and will no longer be available in Kohana 2.2. It's functionality will move to the Kohana core class.

Loading the library$this->user_agent = new User_agent;

It can then be accessed through $this user_agent. All methods in this library rely on data provided→ by the visitor's webbrowser, so it could be faked.

Methods

is_browser()Checks if the current request is being made by a webbrowser, and returns TRUE if this is the case.

if ($this->User_agent->is_browser() == TRUE) echo 'Hello browser!';

is_robot()Checks if the current request is begin made by a robot(e.g. a search engine spider), and returns TRUE if this is the case.

if ($this->User_agent->is_robot() == TRUE) echo 'Hello robot!';

is_mobile()Checks if the current request is begin made by a mobile browser(e.g. Pocket IE or Opera mini), and returns TRUE if this is the case.

if ($this->User_agent->is_mobile() == TRUE) echo 'Hello mobile!';

Page 114: KOHANA PHP framework

accept_lang()The Accept­Language header specifies in which language the visitor would like his request to be returned. The accept_lang checks the Accept­Language header for the specified language, and returns TRUE if this language is in the Accept­Language Header, anf alse if this is not the case.

• [string] Language to check for – default = 'en'

if ($this->User_agent->accept_lang('nl') == TRUE) // Send result in Dutch if accepted echo 'Hallo wereld!';else // Send result in English echo 'Hello world!';

accept_charset()The Accept­Charset header specifies the visitor's accepted charsets. The accept_charset function checks if the specified charset is found in this header, and returns TRUE if it is, and FALSE if it isn't.

• [string] Charset to check for – default = “utf­8”

if ($this->User_agent->accept_charset('utf-8') == TRUE) echo 'I\'m glad you accept UTF-8 charset!';else echo 'Please start supporting UTF-8';

Properties

browserContains the name of the browser.

// Prints name of the browser on screen (e.g. 'Firefox' or 'Internet Explorer')print Kohana::debug($this->User_agent->browser);

agentContains the complete user agent string.

print Kohana::debug($this->User_agent->agent);

It could result in HTML as:

Mozilla/5.0 (Windows; U; Windows NT 6.0; nl; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11

Page 115: KOHANA PHP framework

mobileContains the name of the mobile browser, if the request has been made by a mobile device.

print Kohana::debug($this->User_agent->mobile);

It could result in HTML as:

Opera Mini

versionContains the browser version.

print Kohana::debug($this->User_agent->version);

It could result in HTML as:

2.0.0.11

referrerContains the referer string.

print Kohana::debug($this->User_agent->referer);

Validation LibraryIf you're searching for some pre­made validation functions, check the validation helper.

This library will see significant API changes in Kohana 2.2

A new validation library will be released in Kohana 2.2. It is available in the subversion repository and is a complete rewrite of the current library.

Information on its syntax:http://learn.kohanaphp.com/2008/02/23/a­peek­at­kohanas­new­validation­library/

Getting started

Load the LibraryIn the code below, $somearray is an array passed to the validation class for approval. It can simply be $_POST if you desire, but you'll probably want to handle this differently. That's up to you.

$validation = new Validation($somearray);

Setup the RulesThe rules are setup as an associative array of arrays. The associative array has several keys given the name of a field assigned in the HTML of the form. The associated value is an array with 2 records. The friendly name, the first record, is the name you'd like to be used in the error message. This probably should be the same one you called it when telling the user what to put in that field. The

Page 116: KOHANA PHP framework

second part is the validation rules. Rules are a pipe delimited series of methods that are applied to the string.

$validation->set_rules(array( // Format: // key friendly name, validation rules 'FirstName' => array('First Name', '=trim|required[2,30]'), 'LastName' => array('Last Name','=trim|required[2,30]'), 'Email' => array('Email Address','=trim|required[5,50]|valid_email_rfc'),));

Validating Input

Run the validationUse

$validation->run();

to run the comparison of your $array that you passed when you initialized the validation. This will return true if the array had no validation errors in it. It will return false if there was an issue.

Report the ErrorsUse the code

$validation->error_string;

to return the error in validation. These are returned in a format that you can show to your users, but you may want to format this a bit more closely, such as putting them in a list. If this is desired, you can run this code before displaying the error string,

$validation->error_format("<li>message</li>");

Notice that the string message is replaced by the actual error message. If you wanted to simply add a horizontal rule after each one you could code that like this:

$validation->error_format("message<hr/>");

Complete Example Code$validation = new Validation($_POST); if ( ! empty($_POST)) $validation->set_rules(array ( // Format: // key friendly name, validation rules 'FirstName' => array('First Name', '=trim|required[2,30]'), 'LastName' => array('Last Name', '=trim|required[2,30]'), 'Email' => array('Email Address', '=trim|required[5,50]|valid_email_rfc'), )); if ($validation->run())

Page 117: KOHANA PHP framework

print("Your form successfully validated."); else $validation->error_format("<li>message</li>"); ?> <p>Your form failed validation. Please review the following issues with your form and resubmit it.</p> <ul> <?php echo $validation->error_string ?> </ul> <?php

set_message()Allows customization of the error message that is displayed upon failed validation for a specific function. Note: The key name has to match the function name that it corresponds to. This is very useful when utilizing custom callback validation functions.

public function _tester($value) $this->validation->set_message(__FUNCTION__, 'omg callback error'); $this->validation->add_error(__FUNCTION__, 'one');

Using PHP functions on fieldsPrecede the rule with =.

E.g.

array('First Name', '=trim|required[2,30]');

Using your own custom callbacksPrecede the rule with callback_

Example

array('First Name', 'callback_valid_password|required[2,30]'); //will effectively call $this->validation->valid_password($data);

RulesRule Parameter Description Example

required Yes Return FALSE if form field is empty, or length value is out of range parameters

required[1,30] ­ same as required|min_length[1]|max_length[30] or required[30] ­ same as required|exact_length[30]

Page 118: KOHANA PHP framework

min_length Yes Return FALSE if length field value is less than parameter

max_length Yes Return FALSE if length field value is greater than parameter

exact_length Yes Return FALSE if length field value is not same as parameter

valid_email_rfc

No Return FALSE if email is not rfc822 valid

valid_email No Return FALSE if email is not valid

valid_url Yes Return FALSE if url is not valid valid_ip No Return FALSE if ip is not valid

alpha Yes Return FALSE if form field does not consist only of alphabetical characters

utf8_alpha

alpha_numeric

Return FALSE if form field does not consist only of alphabetical or numeric characters

utf8_alpha_numeric alpha_dash utf8_alpha_dash digit utf8_digit numeric No regex No

depends_on Yes Returns FALSE if form fields defined in parameter is not filled in

depends_on[field_name]

range No

Variable preppingName Parameter Description

prep_for_form prep_for_url strip_image_tags xss_clean encode_php_tags

Page 119: KOHANA PHP framework

Helpers

Page 120: KOHANA PHP framework

Array HelperThe Array helper assists in transforming arrays via the rotate() and remove() methods.

Methods

rotate()'rotate' rotates an array (two­dimensional) matrix. The two arguments are:

• [array] The array you want to rotate• [boolean] Do you want to keep the same keys in the rotated array? – TRUE by default

Example: // Please note that the print() statements are for display only$optical_discs = array ( 'CD' => array('700', '780'), 'DVD' => array('4700','650'), 'BD' => array('25000','405') );print Kohana::debug($optical_discs);$optical_discs = arr::rotate($optical_discs, FALSE);print ('<br /><br />');print Kohana::debug($optical_discs);

It will result in HTML as:

Array( [CD] => Array ( [0] => 700 [1] => 780 ) [DVD] => Array ( [0] => 4700 [1] => 650 ) [BD] => Array ( [0] => 25000 [1] => 405 ) ) Array( [0] => Array ( [CD] => 700 [DVD] => 4700

Page 121: KOHANA PHP framework

[BD] => 25000 ) [1] => Array ( [CD] => 780 [DVD] => 650 [BD] => 405 ) )

remove()'remove' removes a key from an array and returns it.

The two arguments are:

• [string] The key you want removed from an array• [array] The array you want the key to be removed from

Example: // Please note that the print() statements are for display only$optical_discs = array ( 'CD' => array('700', '780'), 'DVD' => array('4700','650'), 'BD' => array('25000','405') );print Kohana::debug($optical_discs);$cd = arr::remove('CD', $optical_discs);print ('<br />');print Kohana::debug($cd);print ('<br />');print Kohana::debug($optical_discs);

It will result in HTML as:

Array( [CD] => Array ( [0] => 700 [1] => 780 ) [DVD] => Array ( [0] => 4700 [1] => 650 ) [BD] => Array ( [0] => 25000 [1] => 405 ) )

Page 122: KOHANA PHP framework

Array( [0] => 700 [1] => 780) Array( [DVD] => Array ( [0] => 4700 [1] => 650 ) [BD] => Array ( [0] => 25000 [1] => 405 ) )

binary_search()'binary_search' performs a basic binary search on an array. By default, it returns the key of the array value it finds. The four arguments are:

• [mixed] The value you want to find.• [array] The sorted array you want to search in• [boolean] Return the nearest value, or simply return FALSE (the default)• [boolean] Sort the array before searching

Example: $my_array = array('10', '20', '30', '50', '80');echo arr::binary_search('50', $my_array);// 3 echo arr::binary_search('45', $my_array);// FALSE (not found) echo arr::binary_search('45', $my_array, TRUE);// 3 echo arr::binary_search('35', $my_array, TRUE);// 2

range()

Cookie HelperProvides methods for working with COOKIE data.

Page 123: KOHANA PHP framework

ConfigurationDefault settings for cookies are specified in application/config/cookie.php. You may override these settings by passing parameters to the helper.

1. prefix: A prefix may be set to avoid name collisions. Default is ''.2. domain: A valid domain, for which the cookie may be written. Default is '' (Use on localhost). For site­wide cookies, prefix your domain with a period .example.com

3. path: A valid path for which the cookie may be written. Default is the root directory '/'4. expire: The cookie lifetime. Set the number of seconds the cookie should persist, until

expired by the browser, starting from when the cookie is set. Note: Set to 0 (zero) seconds for a cookie which expires when the browser is closed.

5. secure: The cookie will only be allowed over a secure transfer protocol (HTTPS). Default is FALSE.

6. httponly: The cookie can be accessed via HTTP only, and not via client scripts. Default is FALSE. Note: Requires at least PHP version 5.2.0

Methods

set()cookie::set() accepts multiple parameters, only the cookie name and value are required. You may pass parameters to this method as discrete values:

cookie::set($name, $value, $expire, $path, $domain, $secure, $httponly, $prefix);

Or you may pass an associative array of values as a parameter:

$cookie_params = array( 'name' => 'Very_Important_Cookie', 'value' => 'Choclate Flavoured Mint Delight', 'expire' => '86500', 'domain' => '.example.com', 'path' => '/', 'prefix' => 'one_', );cookie::set($cookie_params);

get()cookie::get() accepts multiple parameters, Only the cookie name is required.

$cookie_value = cookie::get($cookie_name, $prefix, $xss_clean = FALSE);

Setting the third parameter to TRUE will filter the cookie for unsafe data.

Returns FALSE if the cookie item does not exist.

delete()cookie::delete() accepts multiple parameters, Only the cookie name is required. This method is identical cookie::set() but sets the cookie value to '' effectively deleting it.

Page 124: KOHANA PHP framework

cookie::delete('stale_cookie');

Date HelperThe Date helper assists in formating dates and times allowing for addition and conversion between different formats.

Methods

unix2dos()'unix2dos' converts UNIX time into DOS time The one arguments is:

• [int] UNIX timestamp

Example: // Please note that the print() statements are for display purposes only$time = mktime(0, 0, 0, 31, 10, 1987);print ($time);$time = date::unix2dos($time);print ($time);

It will result in HTML as:

616046400317325312

dos2unix()'dos2unix' converts DOS time into UNIX time The one arguments is:

• [int] DOS timestamp

Example: // Please note that the print() statements are for display purposes only$time = 317325312;print ($time);$time = date::dos2unix($time);print ($time);

It will result in HTML as:

317325312616046400

offset()'offset' calculates the seconds between two timezones The two arguments are:

• [int] remote timezone• [mixed] use local time? – default is TRUE – else enter your own

Example:

Page 125: KOHANA PHP framework

// Please note that the print() statements are for display purposes only// This example was executed in the EST timezoneprint (date::offset('CST').'<br />');print (date::offset('CST', 'MST').'<br />');print (date::offset('UTC', 'GMT').'<br />');

It will result in HTML as:

-360036000

seconds()'seconds' creates an array of numbers based on your input The three arguments are:

• [int] step (count by) – default = 1• [int] start number – default = 0• [int] end number – default = 60

Example: // Please note that the print() statements are for display purposes onlyprint Kohana::debug(date::seconds());print Kohana::debug(date::seconds(2,1,7));print Kohana::debug(date::seconds(100,200,400));

It will result in HTML as:

Array( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 [18] => 18 [19] => 19 [20] => 20 [21] => 21 [22] => 22 [23] => 23 [24] => 24 [25] => 25 [26] => 26 [27] => 27 [28] => 28 [29] => 29

Page 126: KOHANA PHP framework

[30] => 30 [31] => 31 [32] => 32 [33] => 33 [34] => 34 [35] => 35 [36] => 36 [37] => 37 [38] => 38 [39] => 39 [40] => 40 [41] => 41 [42] => 42 [43] => 43 [44] => 44 [45] => 45 [46] => 46 [47] => 47 [48] => 48 [49] => 49 [50] => 50 [51] => 51 [52] => 52 [53] => 53 [54] => 54 [55] => 55 [56] => 56 [57] => 57 [58] => 58 [59] => 59) Array( [1] => 1 [3] => 3 [5] => 5) Array( [200] => 200 [300] => 300)

minutes()Please see seconds.

hours()'hours' counts the number of hours there are left in a day or from a specific start point The three arguments are:

• [int] step (count by) – default = 1• [boolean] 24­hour time? – default = FALSE• [int] start hour – default = 1

Example:

Page 127: KOHANA PHP framework

// Please note that the print() statements are for display purposes only// This example ran at 6:10PM ESTprint Kohana::debug(date::hours());print Kohana::debug(date::hours(1, TRUE, 9));print Kohana::debug(date::hours(1, TRUE, 22));print Kohana::debug(date::hours(1, TRUE, date('g'))); // 24-hour format of an hour without leading zeros

It will result in HTML as:

Array( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12) Array( [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 [18] => 18 [19] => 19 [20] => 20 [21] => 21 [22] => 22 [23] => 23) Array( [22] => 22 [23] => 23) Array( [18] => 18 [19] => 19 [20] => 20 [21] => 21 [22] => 22 [23] => 23)

Page 128: KOHANA PHP framework

ampm()'ampm' calculates whether the supplied integer makes the hour AM or PM The one argument is:

• [int] hour to calculate

Example: // Please note that the print() statements are for display only// This example ran at 5:45PM ESTprint Kohana::debug(date::ampm(1));print Kohana::debug(date::ampm(13));print Kohana::debug(date::ampm(date('G'))); // 24-hour format of an hour without leading zeros

It will result in HTML as:

AMPMPM

days()'days' counts the number of days there are in a specific month of a specific year The two arguments are:

• [int] month (1­12)• [int] year – default: current year

Example: // Please note that the print() statement is for display purposes onlyprint Kohana::debug(date::days(5,2007));

It will result in HTML as:

Array( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 [18] => 18 [19] => 19 [20] => 20 [21] => 21 [22] => 22 [23] => 23

Page 129: KOHANA PHP framework

[24] => 24 [25] => 25 [26] => 26 [27] => 27 [28] => 28 [29] => 29 [30] => 30 [31] => 31)

months()'months' returns an mirrored array with the month­numbers of the year.

Example: // Please note that the print() statement is for display purposes onlyprint Kohana::debug(date::months());

It will result in HTML as:

Array( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12)

years()'years' returns an array with the years between the specified years. The two arguments are:

• [int] start year– default = current year ­ 5• [int] end year – default = current year + 5

Example: // Please note that the print() statements are for display purposes only// This example ran in 2007print Kohana::debug(date::years());print Kohana::debug(date::years(1998,2002));

It will result in HTML as:

Array( [2002] => 2002 [2003] => 2003 [2004] => 2004 [2005] => 2005 [2006] => 2006

Page 130: KOHANA PHP framework

[2007] => 2007 [2008] => 2008 [2009] => 2009 [2010] => 2010 [2011] => 2011 [2012] => 2012) Array( [1998] => 1998 [1999] => 1999 [2000] => 2000 [2001] => 2001 [2002] => 2002)

timespan()'timespan' returns the time between two timestamps in a human readable format The arguments are:

• [int] timestamp 1 • [int] timestamp 2 – default: current timestamp• [string] format – default: 'years,months,weeks,days,hours,minutes,seconds'

Example: // Please note that the print() statements are for display purposes only// This example ran in 2007$timestamp = time() - (60*60*24*7*31*3); // timestamp of 651 days ago$timestamp2 = time() - (60*60*24*7*50); // timestamp of 350 days agoprint Kohana::debug(date::timespan($timestamp));print Kohana::debug(date::timespan($timestamp, time(), 'years,days'));print Kohana::debug(date::timespan($timestamp, $timestamp2));print 'minutes: '.Kohana::debug(date::timespan($timestamp, time(), 'minutes'));

It will result in HTML as:

Array( [years] => 1 [months] => 9 [weeks] => 2 [days] => 2 [hours] => 0 [minutes] => 0 [seconds] => 0) Array( [years] => 1 [days] => 286) Array( [years] => 0 [months] => 10 [weeks] => 0 [days] => 1

Page 131: KOHANA PHP framework

[hours] => 0 [minutes] => 0 [seconds] => 0) minutes: 937440

adjust()'adjust' converts an hour integer into 24­hour format from a non­24­hour format. The two arguments are:

• [int] hour in non­24­hour format• [string] AM or PM

Example: // Please note that the print() statements are for display onlyprint Kohana::debug(date::adjust(11, 'PM'));

It will result in HTML as:

23

Download HelperThe download helper assists in forcing downloading of files by presenting users with the “save as” dialog.

Methods

force()'force' forces a download of a file to the user's browser. This function is binary­safe and will work with any MIME type that Kohana is aware of.

• $filename ­ [string] filename of the file to be downloaded – default = ””• $data ­ [string] data to be sent if the filename does not exists – default = ””

Example: // File path is relative to the front controllerdownload::force("file.txt"); // For a file located in application/downloads // Use relative pathdownload::force('./application/downloads/file.txt'); // OR use the defined application pathdownload::force(APPPATH.'downloads/file.txt');

Page 132: KOHANA PHP framework

Email HelperAn Email helper to work with the Swift email library.

ConfigurationThe swiftmailer configuration for this helper is found in config/email.php

Inside the config/email.php file you can select the driver type which are native, sendmail, smtp

Example: using smtp

$config['driver'] = 'smtp'; $config['options'] = array('hostname'=>'yourhostname', 'username'=>'yourusername', 'password'=>'yourpassword', 'port'=>'25');

Methods

connect()

send ()'send' sends an e­mail using the specified information. The parameters are:

• [string] address to send email to• [string] address to send email from• [string] subject of the email• [string] body of the email• [boolean] send email as HTML (defaults to false)

Example: $to = '[email protected]'; // Address can also be array('[email protected]', 'Name')$from = '[email protected]';$subject = 'This is an example subject';$message = 'This is an <strong>example</strong> message'; email::send($to, $from, $subject, $message, TRUE);

Expires HelperProvides methods for managing browser aware page caching. More information on client­side page caching can be found at caching­php­performance

Allows setting a page cache time by sending Last­Modified and Expires headers for the page.

Allows checking if the page is older than the page cache time. If so, the page is expired and a new page must be ouput. If not, a 304 not­modified status header and NO data is sent. The page is retrieved by the browser from it's own cache.

Page 133: KOHANA PHP framework

Methods

set()expires::set() Sets an expiry time for a local, browser page cache. The single parameter is:

• [integer] The time, in seconds, until page expires. Default is 60 seconds.

Example

expires::set(300);

check()expires::check() Determines if a cached page needs to be refreshed. The single parameter is.

* [integer] The time in seconds, to add to the last modified time. Default is 60 seconds.

Example

if (expires::check(300) === FALSE)

check_headers()expires::check_headers() Has no parameters. Called internally by expires::set() Returns boolean TRUE if a Last­Modified or Expires header has NOT been sent.

Example

if (expires::check_headers()) echo 'Safe to send Expires header';

prevent_output()expires::prevent_output() Has no parameters. Called internally by expires::check() You would not normally call this function directly, as it clears the Kohana output buffer.

Example

expires::prevent_output() // will set Kohana::$output = '';

Full ExampleThe controller outputs a page from a single method. The objective is to cache the page for ten seconds. If the page is reloaded within ten seconds, the cached page data should be displayed.

Controller: <?php defined('SYSPATH') or die('No direct script access.');/** * Default Kohana controller. */class Welcome_Controller extends Controller public function index()

Page 134: KOHANA PHP framework

if (expires::check(10) === FALSE) expires::set(10); $welcome = new View('welcome'); // We should only see the time updated in the view after 10 seconds // note, it is not this data that is cached, but the browser that fetches a locally cached page $welcome->now = date(DATE_RFC822); $welcome->render(TRUE);

View: <h2>Welcome!</h2><p>It is now <?php echo $now ?></p><hr/>

Feed HelperThe Feed helper assist in the parsing of remote RSS feeds.

Methods

parse()'parse' parses a RSS feed and returns the parsed feed as an array.

• [string] remote feed url, or local file path• [int] maximum amount of items to parse – default = 0 (infinite)

$feed = "feed.xml";print Kohana::debug(feed::parse($feed));

Use the code above on this RSS feed:

<?xml version="1.0" encoding="UTF-8"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><item> <title>Some feed item</title> <link>http://www.example.com/article34</link> <description>This article is really cool!</description> <author>Aart-Jan Boor</author> <pubDate>Sat, 08 Dec 2007 13:28:11 GMT</pubDate></item><item> <title>Some feed item2</title> <link>http://www.example.com/article546</link> <description>This article is really cool too!</description> <author>Aart-Jan Boor</author> <pubDate>Sat, 08 Dec 2007 12:57:56 GMT</pubDate></item>

Page 135: KOHANA PHP framework

<item> <title>Some feed item3</title> <link>http://www.example.com/article4523</link> <description>This article is the best!</description> <author>Aart-Jan Boor</author> <pubDate>Sat, 08 Dec 2007 12:39:42 GMT</pubDate></item></channel></rss>

It will result in HTML as:

Array( [0] => Array ( [title] => Some feed item [link] => http://www.example.com/article34 [description] => This article is really cool! [author] => Aart-Jan Boor [pubDate] => Sat, 08 Dec 2007 13:28:11 GMT ) [1] => Array ( [title] => Some feed item2 [link] => http://www.example.com/article546 [description] => This article is really cool too! [author] => Aart-Jan Boor [pubDate] => Sat, 08 Dec 2007 12:57:56 GMT ) [2] => Array ( [title] => Some feed item3 [link] => http://www.example.com/article4523 [description] => This article is the best! [author] => Aart-Jan Boor [pubDate] => Sat, 08 Dec 2007 12:39:42 GMT ) )

File HelperA helper designed to manipulate files and filenames.

Methods

extension()'extension' runs a regular expression check, returning the entire string after the last period (.) – also known as the file extension The parameters are:

• param: [string] filename to check extension of• return: [string] entire string after last period (.)

Page 136: KOHANA PHP framework

Example: echo file::extension('/etc/apache2/apache2.conf');

conf

mime()'mime' finds the MIME­type of a file first by using PHP's built­in database and then Kohana's MIME configuration file (system/config/mimes.php). The parameters are:

• param: [string] filename to check MIME­type of• return: [mixed] string if found, FALSE if not found

Example: $file = 'my_movie.ogg'echo $file.' ('.file::mime($file).')';

my_movie.ogg (application/ogg)

split()'split' splits a file into pieces matching a specific size indicated in megabytes. The parameters are:

• param: [string] file to be split• param: [string] directory to output to, defaults to the same directory as the file• param: [integar] size, in MB, for each chunk to be• return: [integar] The number of pieces that were created.

Example: $file = 'humpty_dumpty.mp3'; // pretend it is 7.8 MB largeecho (file_exists($file)) ? file::split($file,FALSE,2) : 'can not find file!' ;

4

Directory listing:

-rwxrwxrwx 1 www-data www-data 8186302 2008-05-06 20:11 humpty_dumpty.mp3-rw-r--r-- 1 www-data www-data 2097152 2008-05-06 20:15 humpty_dumpty.mp3.001-rw-r--r-- 1 www-data www-data 2097152 2008-05-06 20:15 humpty_dumpty.mp3.002-rw-r--r-- 1 www-data www-data 2097152 2008-05-06 20:15 humpty_dumpty.mp3.003-rw-r--r-- 1 www-data www-data 1894846 2008-05-06 20:15 humpty_dumpty.mp3.004

join()'join' joins splited files (possibly by file::split()), assuming a .### extension. The parameters are:

• param: [string] split filename, without .000 extension• param: [string] output filename, if different then an the filename• return: [integar] The number of pieces that were joined.

Example: $file_in = 'humpty_dumpty.mp3'; // from our last example$file_out = 'humpty_dumpty-back_together_again.mp3'; // output nameecho file::join($file_in,$file_out);

Page 137: KOHANA PHP framework

4

Directory listing:

-rwxrwxrwx 1 www-data www-data 8186302 2008-05-06 20:11 humpty_dumpty.mp3-rw-r--r-- 1 www-data www-data 2097152 2008-05-06 20:15 humpty_dumpty.mp3.001-rw-r--r-- 1 www-data www-data 2097152 2008-05-06 20:15 humpty_dumpty.mp3.002-rw-r--r-- 1 www-data www-data 2097152 2008-05-06 20:15 humpty_dumpty.mp3.003-rw-r--r-- 1 www-data www-data 1894846 2008-05-06 20:15 humpty_dumpty.mp3.004-rw-r--r-- 1 www-data www-data 8186302 2008-05-06 20:17 humpty_dumpty-back_together_again.mp3

Form HelperThe Form helper provides methods to assist you in creating forms. It does not do validation or filtering. If you want to generate your forms with validation and filtering you can do so with the Forge library

Getting StartedYou'll need to use a line like this to begin the form.

print form::open(string $submit, array $attr, array $hidden );

Where $submit is a relative URL like '/class/method' and $attr is an array with attributes, like array('id' 'forumid', 'class' 'login_form'). All three can be left blank. If you leave the first blank,⇒ ⇒ the submission URL will be assumed to be the page being submitted from. $hidden is an array of hidden form fields.

Adding FieldsYou may add form fields as you would in straight HTML, but the option exists to create them using php. Here are some examples.

print form::dropdown($data, $options, $selected)print form::textarea($data)print form::input($data)

Methods

open()In order to open the form, you simply need to: This uses the default values, using POST to submit the form to the current page.

print form::open()

To add attributes:

// Submits the page to: domain.tld/products/search.html// CSS class 'search_form' is appliedprint form::open('products/search', array('class'=>'search_form'));

Page 138: KOHANA PHP framework

// Stay on the current page, and add a hidden input field named 'type' with value: 'product'print form::open('', array(), array('type'=>'product')); // Sending a form to the current page using GETprint form::open('', array('method'=>'get'));

open_multipart()Opens a form for submitting binary data via POST. You must specify an encoding type attribute of 'multipart/form­data'.

Examples: // Submits multipart form data to the current pageprint form::open('', array('enctype' => 'multipart/form-data'));

Results in HTML

<form action="http://localhost/index.php/welcome" enctype="multipart/form-data" method="post">

input()Creates an HTML form input tag. Defaults to a text type. The parameters are:

• [string]/[array] data input name and id or an array of HTML attributes• [string] input value, when using a name• [string] extra string attached to the end of the attributes

Example: print form::input('field_name', 'field_value', ' style="text-align: right;"');

Result in HTML:

<input type="text" id="field_name" name="field_name" value="field_value" style="text-align: right;" />

It's not necessary to use all parameters.

Example: print form::input(); // don't use parametersprint form::input('field_name'); // use only 1 parametr - for name and idprint form::input('field_name', 'field_value'); // use only 2 parameters - for name, id and value

Result in HTML:

<input type="text" id="" name="" value="" /><input type="text" id="field_name" name="field_name" value="" /><input type="text" id="field_name" name="field_name" value="field_value" />

hidden()'hidden' generates a hidden form field. The parameters are:

• [string]/[array] data for key attributes

Page 139: KOHANA PHP framework

• [string] value of the field – default = ””

Example: // Please note that the print() statements are for display purposes onlyprint Kohana::debug(form::hidden("fieldName","fieldValue"));$array=array('field1'=>'value1','field2'=>'value2');print Kohana::debug(form::hidden($array));

It will result in HTML as:

<input type="hidden" id="fieldName" name="fieldName" value="fieldValue" /> <input type="hidden" id="field1" name="field1" value="value1" /><input type="hidden" id="field2" name="field2" value="value2" />

password()'password' generates a password form field. The parameters are:

• [string]/[array] data for key attributes• [string] value of the field – default = ””• [string] extra string to be added to the end of the attributes – default = ””

Example: // Please note that the print() statements are for display purposes onlyprint Kohana::debug(form::password("fieldName","fieldValue"));print Kohana::debug(form::password("fieldName","fieldValue",' id="fieldId"'));$array=array('name'=>'fieldName','value'=>'fieldValue','id'=>'fieldId','class'=>'formField');print Kohana::debug(form::password($array));

It will result in HTML as:

<input type="password" id="fieldName" name="fieldName" value="fieldValue" /> <input type="password" id="fieldName" name="fieldName" value="fieldValue"id="fieldId" /> <input type="password" id="fieldId" name="fieldName" value="fieldValue" class="formField" />

upload()Generate HTML form input tag type “file” for upload files:

The parameters are:

• [string]/[array] ­ attribute name or array of attributes• [string] ­ attribute value [optional]• [string] ­ extra additional [optional]

Example

$attributes = array('name' => 'file_1', 'class' => 'your-class');echo form::upload($attributes, 'path/to/local/file')

Result in HTML:

Page 140: KOHANA PHP framework

<input type="file" name="file_1" value="path/to/local/file" class="your-class" />

textarea()Creates an HTML form textarea tag.

print form::textarea(string/array $data, string $value)

The parameters are:

• [string]/[array] textarea name or an array of HTML attributes • [string] textarea value, when using a name

Example

print form::textarea('field_name', 'field_value');

Result in HTML:

<textarea name="field_name">field_value</textarea>

We can also use array for the first parameter. Look at this example:

print form::textarea(array('name' => 'field_name', 'value' => 'field_value', 'class' => 'our_class'));

Result in HTML:

<textarea name="field_name" class="our_class">field_value</textarea>

dropdown()Creates a drop down selection box. The parameters are:

• [string]/[array] input name or array of HTML attributes• [array] the select options, when using input name• [string] the option to be selected by default• [string] extra string to be added to the end of the attributes – default = ””

Example: $selection = array('basic' =>'Basic', 'standard' => 'Standard', 'custom' => 'Custom');// The 'standard' option will be the default selectionprint form::dropdown('input_dropdown',$selection,'standard');

Results in HTML

<select id="input_dropdown" name="input_dropdown"><option value="basic">Basic</option><option value="standard" selected="selected">Standard</option><option value="custom">Custom</option></select>

checkbox()Creates a 'tick box' type selection box.

Page 141: KOHANA PHP framework

The parameters are:

• [string/array] input name or an array of HTML attributes• [string] input value, when using a name• [boolean] make the checkbox checked by default• [string] a string to be attached to the end of the attributes

Example: print form::label('check_spam_box', 'Always send me Spam (Opt in): ');print form::checkbox('check_spam_box', 'send_spam');print form::label('check_money_box', 'Never send me Money (Opt out): ');print form::checkbox('check_money_box', 'send_no_money', TRUE);

Results in HTML

<label for="check_spam_box">Always send me Spam (Opt in): </label><input type="checkbox" id="check_spam_box" name="check_spam_box" value="send_spam" /><label for="check_money_box">Never send me Money (Opt out): </label><input type="checkbox" id="check_money_box" name="check_money_box" value="send_no_money" checked="checked" />

Browser output:

Always send me Spam (Opt in): Never send me Money (Opt out):

radio()Generates a 'radio' type selection box, similar to checkbox, but allows for easier multiple selections.

The parameters are:

• [string/array] input name or an array of HTML attributes• [string] input value, when using a name• [boolean] make the radio selected by default• [string] a string to be attached to the end of the attributes

Example: print form::label('radio_cute_box', 'I am cute: ');print form::radio('radio_cute_box', 'is_cute').'<br />';print form::label('radio_single_box', 'I am single: ');print form::radio('radio_single_box', 'is_single', TRUE).'<br />';print form::label('radio_rich_box', 'I am rich: ');print form::radio('radio_rich_box', 'is_rich').'<br />';

Results in HTML

<label for="radio_cute_box">I am cute: </label><input type="radio" id="radio_cute_box" name="radio_cute_box" value="is_cute" /><br /><label for="radio_single_box">I am single: </label><input type="radio" id="radio_single_box" name="radio_single_box" value="is_single" checked="checked" /><br /><label for="radio_rich_box">I am rich: </label><input type="radio" id="radio_rich_box" name="radio_rich_box" value="is_rich" /><br />

Browser output

Page 142: KOHANA PHP framework

I am cute: I am single: I am rich:

submit()Creates a 'submit' type button for the form.

The parameters are:

• [string/array] input name or an array of HTML attributes• [string] input value, when using a name• [string] a string to be attached to the end of the attributes

Example: print form::submit('submit', 'Send');

Results in HTML

<input type="submit" id="submit" name="submit" value="Send" />

button()Creates a button for the form. Note this is not the same as the button associated with input type 'submit' or 'reset'.

The parameters are:

• [string/array] input name or an array of HTML attributes• [string] input value, when using a name• [string] a string to be attached to the end of the attributes

Example: print form::button('button', 'Does not do Much');

Results in HTML

<button type="button" id="button" name="button">Does not do Much</button>

label()Creates a label for a form entry field.

The parameters are:

• [string/array] label “for” name or an array of HTML attributes• [string] label text or HTML• [string] a string to be attached to the end of the attributes

Example: print form::label('imageup', 'Image Uploads');

Results in HTML

<label for="imageup">Image Uploads</label>

Page 143: KOHANA PHP framework

attributes()Returns an attribute string, from an array of HTML attributes in key/value format, sorted by form attributes first.

The parameters are:

• [array] HTML attributes array

Example: print form::attributes(array('id' => 'input_name', 'class' => 'submission'));

Outputs

id="input_name" class="submission"

open_fieldset()Creates a fieldset opening tag

The parameters are:

• [array] an array of HTML attributes• [string] a string to be attached to the end of the attributes

Example: print form::open_fieldset(array('class' => 'important'));

Results in HTML

<fieldset class="important">

close_fieldset()Generates a fieldset closing tag

Example: print form::close_fieldset();

Results in HTML

</fieldset>

legend()Creates a legend for describing a fieldset.

The parameters are:

• [string] legend text or HTML• [array] an array of HTML attributes• [string] a string to be attached to the end of the attributes

Example: print form::legend('More about you', array('id' => 'more_infos'));

Page 144: KOHANA PHP framework

Results in HTML

<legend id="more_infos">More about you</legend>

close()In order to close the form, you simply need to:

print form::close()

Or you can set parameter:

print form::close('</div>')

Result in HTML:

</form></div>

HTML HelperThe HTML helper assists in calling various elements such as stylesheet, javascript, image links and anchor links into position.

Methods

specialchars()'specialchars' is similar to PHP's htmlspecialchars() function. However, there are some small differences:

• It will automatically use the UTF­8 character set in conversion (instead of ISO­8859­1).• It will automatically translate both single and double quotes to HTML entities (instead of

only double quotes).• It provides built­in fallback functionality for not double encoding existing HTML entities

(for PHP versions older than 5.2.3).

The two arguments are:

• [string] The string you want to encode• [boolean] Do you want to encode existing HTML entities? – TRUE by default

Example: $string = '<p>"I\'m hungry"&mdash;Cookie Monster said.</p>';echo html::specialchars($string);

It will result in the following HTML:

&lt;p&gt;&quot;I&#039;m hungry&quot;&amp;mdash;Cookie Monster said.&lt;/p&gt;

When setting the second parameter to FALSE, existing HTML entities are preserved. Look closely at &mdash;.

echo html::specialchars($string, FALSE);

Page 145: KOHANA PHP framework

&lt;p&gt;&quot;I&#39;m hungry&quot;&mdash;Cookie Monster said.&lt;/p&gt;

query_string()This method is deprecated and will not be available in Kohana 2.2. Use PHP function http_build_query() instead

'query_string' creates a HTML query string from an array. The one argument is:

• [array] The string you want to encode

Example: echo html::query_string(array( 'id' => 12, 'page' => 'home'));

It will result in HTML as:

id=12&page=home

anchor()'anchor' creates a HTML anchor (<a href=””></a>), linking an internal page or external site automatically The four arguments are:

• [string] An internal or external page that you would like to link to• [string] The title you would like to have show up as the hyperlink• [string] Attributes to add to your anchor• [string] The protocol your link will use: 'ftp', 'irc', etc. – This is only necessary if it's an

internal page with a non­absolute link for the first argument and you need to change the protocol from 'http'

Example 1: echo html::anchor('home/news', 'Go to our news section!');

It will result in HTML as:

<a href="http://localhost/home/news">Go to our news section!</a>

Example 2: echo html::anchor('irc://irc.freenode.net/kohana', 'Join us on IRC!', 'style="font-size: 20px;"');

It will result in HTML as:

<a href="irc://irc.freenode.net/kohana" style="font-size: 20px;">Join us on IRC!</a>

file_anchor()Similar to 'anchor', 'file_anchor' creates a HTML anchor (<a href=””></a>) linking to non­Kohana resources. Therefore, it will always prefix the site's URL to the path of your file The four arguments

Page 146: KOHANA PHP framework

are:

• [string] An internal file that you would like to link to• [string] The title you would like to have show up as the hyperlink• [string] Attributes to add to your anchor• [string] The protocol your link will use: 'ftp', 'irc', etc. – This is only necessary if you need to

change the protocol from 'http'

Example 1: echo html::file_anchor('media/files/2007-12-magazine.pdf', 'Check out our latest magazine!');

It will result in HTML as:

<a href="http://localhost/media/files/2007-12-magazine.pdf">Check out our latest magazine!</a>

Example 2: echo html::file_anchor('pub/index.html', 'The Public Linux Archive', 'id="id432"', 'ftp');

It will result in HTML as:

<a href="ftp://localhost/pub/index.html" id="id432">The Public Linux Archive</a>

panchor()Similar to 'anchor', but accepts the protocol attribute first instead of last The four arguments are:

• [string] The protocol your link will use: ''ftp', 'irc', etc. – This is only necessary if it's an internal page with a non­absolute link for the first argument and you need to change the protocol from 'http'

• [string] An internal or external page that you would like to link to• [string] The title you would like to have show up as the hyperlink• [string] Attributes to add to your anchor

Example: echo html::panchor('irc', '/kohana', 'Join us on our custom IRC!');

It will result in HTML as:

<a href="irc://localhost/kohana">Join us on our custom IRC!</a>

mailto()'mailto' prints a <a href=“mailto:”></a> tag but escapes all characters of the e­mail address into HTML, hex or raw randomly to help prevent spam and e­mail harvesting. The three arguments are:

• [string] E­mail address• [string] The title you would like to have show up as the hyperlink• [string] Attributes to add to your anchor

Example: echo html::mailto('[email protected]');

Page 147: KOHANA PHP framework

It will result in HTML as:

<a href="&#109;&#097;&#105;&#108;&#116;&#111;&#058;i&#x6e;fo&#x40;&#101;&#x78;&#x61;mp&#108;e&#x2e;&#x63;&#x6f;&#109;">i&#x6e;fo&#x40;&#101;&#x78;&#x61;mp&#108;e&#x2e;&#x63;&#x6f;&#109;</a>

stylesheet()'stylesheet' calls CSS files internally and will suffix .css if it is not already present The three arguments are:

• [string or array] Either a string with the file's location or an array of files• [string or array] Media type such as 'screen', 'print' or 'aural'• [boolean] Set to TRUE if you want to have the index.php file included in the link – This

makes the difference between processing the request through Kohana (usually a media controller) or simply calling the file with an absolute path

Example: echo html::stylesheet(array( 'media/css/default', 'media/css/menu'),array( 'screen', 'print'), FALSE);

It will result in HTML as:

<link rel="stylesheet" href="http://localhost/media/css/default.css" media="screen" /><link rel="stylesheet" href="http://localhost/media/css/menu.css" media="print" />

Important

Don't forget to add a final TRUE parameter if your Kohana frameworks still need “index.php” in the URL (this will be the case until you modify this setting as explained in the tutorial from Christophe http://kohanaphp.com/tutorials/video/working_with_media_files.html).

link()'link' calls files such as feeds internally. Will render the <link> tag. Linking to stylesheets also uses the <link> tag but the html::stylesheet() helper can be used for those Arguments

• [string or array] Either a string with the file's location or an array of files• [string or array] Either a string or array with values for the 'rel' attribute (e.g. stylesheet,

alternate)• [string or array] Either a string or array with values for the 'type' attribute

(application/rss+xml etc.)• [boolean] set to TRUE to specify the suffix of the file, defaults to FALSE• [string or array] Either a string or array with values for the 'media' attribute (print, screen

etc.)

Page 148: KOHANA PHP framework

• [boolean] Set to TRUE if you want to have the index.php file included in the link – This makes the difference between processing the request through Kohana (usually a media controller) or simply calling the file with an absolute path

Example: echo html::link(array( 'welcome/home/rss', 'welcome/home/atom'),'alternate',array('application/rss+xml','application/atom+xml'), FALSE);

It will result in HTML as:

<link rel="alternate" type="application/rss+xml" href="http://localhost/welcome/home/rss" /><link rel="alternate" type="application/atom+xml" href="http://localhost/welcome/home/atom" />

Important

Don't forget to add a final TRUE parameter if your Kohana frameworks still need “index.php” in the URL (this will be the case until you modify this setting as explained in the tutorial from Christophe http://kohanaphp.com/tutorials/video/working_with_media_files.html).

script()'script' calls JavaScript files internally and will suffix .js if not present in your file call There are two arguments are:

• [string or array] Either a string with the file's location or an array of files• [boolean] Set to TRUE if you want to have the index.php file included in the link – This

makes the difference between processing the request through Kohana (usually a media controller) or simply calling the file with an absolute path

Example: echo html::script(array( 'media/js/login', 'media/js/iefixes.js'), FALSE);

It will result in HTML as:

<script type="text/javascript" src="http://localhost/media/js/login.js"></script><script type="text/javascript" src="http://localhost/media/js/iefixes.js"></script>

Important

Don't forget to add a final TRUE parameter if your Kohana frameworks still need “index.php” in the URL (this will be the case until you modify this setting as explained in the tutorial from Christophe http://kohanaphp.com/tutorials/video/working_with_media_files.html).

Page 149: KOHANA PHP framework

image()'image' creates a 'img' HTML tag.

There are two arguments are:

• [string or array] A string to specify the image 'src' attribute or an array of attributes• [boolean] Set to TRUE if you want to have '/index.php/' included in the link (to use views to

serve images using Kohana)

Example 1: echo html::image('media/images/thumbs/01.png');

It will result in HTML as:

<img src="http://localhost/media/images/thumbs/01.png" />

echo html::image(array('src' => 'media/images/thumbs/01.png', 'width' => '100', 'height' => 100, 'alt' => 'Thumbnail'));

<img src="http://localhost/media/images/thumbs/01.png" width="100" height="100" alt="Thumbnail" />

Example 2 (with html::anchor and lightbox): echo html::file_anchor('media/images/01.png', html::image('media/images/thumbs/01.png'), 'rel="lightbox"');

It will result in HTML as:

<a href="http://localhost/media/images/01.png" rel="lightbox"><img src="http://localhost/media/images/thumbs/01.png" /></a>

Important

Don't forget to add a final TRUE parameter if your Kohana frameworks still need “index.php” in the URL (this will be the case until you modify this setting as explained in the tutorial from Christophe http://kohanaphp.com/tutorials/video/working_with_media_files.html).

attributes()'attributes' parses attributes for a HTML tag from an array There are two arguments are:

• [array] An array of attributes you'd like to add to a HTML tag

Example 1: echo html::attributes( array ( 'style' => 'font-size: 20px; border-bottom: 1px solid #000;', 'rel' => 'lightbox', 'class' => 'image' ));

It will result in HTML as:

style="font-size: 20px; border-bottom: 1px solid #000;" rel="lightbox" class="image"

Page 150: KOHANA PHP framework

Example 2 (with html::anchor): echo html::file_anchor('home/images/01.png', 'See my picture!',html::attributes( array ( 'style' => 'font-size: 20px; border-bottom: 4px solid #000;', 'rel' => 'lightbox', 'class' => 'image' )));

It will result in HTML as:

<a href="http://localhost/home/images/01.png" style="font-size: 20px; border-bottom: 4px solid #000;" rel="lightbox" class="image">See my picture!</a>

breadcrumb()The function returns an array of links for each segment. Arguments:

• segments to use as breadcrumbs, defaults to using Router::$segments

Example:

echo Kohana::debug(html::breadcrumb());

will produce the following output:

Array ( [0] => <a href="http://localhost/ajax">Ajax</a> [1] => <a href="http://localhost/ajax/welcome">Welcome</a> [2] => <a href="http://localhost/welcome/text">Text</a> )

Inflector HelperProvides methods for working with the pluralization and singularization of words as well as other methods to work with phrases.

Methods

uncountable()inflector::uncountable($string) checks whether the given string is an uncountable word. Returns TRUE or FALSE.

This method uses a words list from the inflector.php file, located into the system/i18n/en_EN/ folder (or the language specified in the config item 'locale.language')

inflector::uncountable('money'); //returns TRUE inflector::uncountable('book'); //returns FALSE

Page 151: KOHANA PHP framework

singular()inflector::singular($string) will attempt to singularize the given string. Returns the string. If a string is uncountable it will return the string without modification. Note: this function works for English words only.

inflector::singular('books'); //returns 'book'

plural()inflector::plural($string) will attempt to pluralize the given string. Returns the string. If a string is uncountable it will return the string without modification. Note: this function works for English words only.

inflector::plural('book'); //returns 'books'

camelize()inflector::camelize($string) will attempt to camelize the given string. Returns the string.

inflector::camelize('system_initialization'); //returns 'systemInitialization'inflector::camelize('system initialization'); //returns 'systemInitialization'

underscore()inflector::underscore($string) makes a phrase underscored instead of spaced. Returns the string.

inflector::underscore('Underscores a phrase.'); //returns 'Underscores_a_phrase.'

humanize()inflector::humanize($string) makes a phrase human­readable instead of dashed or underscored. Returns the string.

inflector::humanize('Remove_underscores_from_a_phrase.'); //returns 'Remove underscores from a phrase.' inflector::humanize('Remove-dashes-from-a-phrase.'); //returns 'Remove dashes from a phrase.'

Number HelperProvides methods for rounding integer numbers.

Page 152: KOHANA PHP framework

Methods

round()num::round() accepts two arguments. An integer to round, and a nearest integer number to round too, defaults to 5.

Example

// Given an input of: $numbers = array(1,3,5,9,99,999);<p>Rounding numbers to nearest 5</p><?php foreach ($numbers as $number): ?> <p>Round <?php echo $number ?> to <?php echo num::round($number, 5) ?> </p><?php endforeach ?>

This will output as HTML

<p>Rounding numbers to nearest 5</p> <p>Round 1 to 0 </p> <p>Round 3 to 5 </p> <p>Round 5 to 5 </p> <p>Round 9 to 10 </p> <p>Round 99 to 100 </p> <p>Round 999 to 1000 </p>

Security HelperThe security helper assist in verifying the security of use input.

Methods

xss_clean()'xss_clean' behaves the same as xss_clean in the Input library.

• [string] String to be cleansed

strip_image_tags()'strip_image_tags()' strips the image tags out of a string and returns the string trimmed without the image tags.

• [string] String to be stripped

$string = '<b>Check this image:</b> <img src="http://www.example.com/example.jpg" />';print Kohana::debug(security::strip_image_tags($string));

It will result in HTML as:

<b>Check this image:</b> http://www.example.com/example.jpg

Page 153: KOHANA PHP framework

encode_php_tags()'encode_php_tags' replaces PHP tags in a string with their corresponding HTML entities.

• [string] String to santize

$string = '<?php echo "<b>Hello World!</b>" ?>';print Kohana::debug(security::encode_php_tags($string));

It will result in HTML as:

&lt;?php echo "<b>Hello World!</b>" ?&gt;

Text HelperProvides methods for working with Text.

Methods

limit_words()text::limit_words() accepts multiple parameters. Only the input string is required. The default end character is the ellipsis.

$long_description = 'The rain in Spain falls mainly in the plain';$limit = 4;$end_char = '&amp;nbsp;'; $short_description = text::limit_words($long_description, $limit, $end_char);

Generates:

The rain in Spain

limit_chars()text::limit_chars() accepts multiple parameters. Only the input string is required. The default end character is the ellipsis.

$long_description = 'The rain in Spain falls mainly in the plain';$limit = 4;$end_char = '&amp;nbsp;';$preserve_words = FALSE; $short_description = text::limit_chars($long_description, $limit, $end_char, $preserve_words);

Generates:

The r

alternate()text::alternate() accepts multiple parameters. The number of parameters determines the

Page 154: KOHANA PHP framework

alternation. This is handy if you loop through something and you for example want to alternate the color of a table row.

for($i=0:$i<5:$i++) echo text::alternate('1','2','boom');//returns 12boom12

random()text::random() accepts multiple optional parameters. Returns a random text string of specified length.

Possible values for $type are:

• alnum ­ 0­9, a­z and A­Z• alpha ­ a­z, A­Z• numeric ­ 0­9• nozero ­ 1­9• distinct ­ Only distinct characters that can't be mistaken for others.• For values that don't match any of the above, the characters passed in will be used.

echo text::random($type = 'alnum', $length = 10);

reduce_slashes()text::reduce_slashes() reduces multiple slashes in a string to single slashes.

<?php$str = "path/to//something";echo reduce_slashes($str); // Outputs: path/to/something?>

censor()text::censor() accepts multiple optional parameters. The input string and an array of marker words is required. Returns a string with the marker words censored by the specified replacement character.

$str = 'The income tax is a three letter word, but telemarketers are scum.';$replacement = '*';$badwords = array('tax', 'scum'); echo text::censor($str, $badwords, $replacement, $replace_partial_words = FALSE);

Generates:

The income *** is a three letter word, but telemarketers are ****.

bytes()text::bytes($bytes,$force_unit,$format,$si) Returns a human readable size.

• $bytes ­ Supply the number of bites

Page 155: KOHANA PHP framework

• $force_unit ­ defaults to NULL when supplied the function will return in those units.• $format ­ format of the return string• $si ­ Defaults to TRUE, when FALSE function will return IEC prefixes (KiB, MiB etc.) else

will return SI prefixes (kB, MB, GB etc)

echo text::bytes('2048'); //returns 2.05 kBecho text::bytes('4194304','kB'); //returns 4194.30 kBecho text::bytes('4194304','GiB'); //returns 0.00 GiBecho text::bytes('4194304',NULL, NULL, FALSE); //returns 4.00 MiB

widont()text::widont() Returns a string without widow words by inserting a non­breaking space between the last two words. A widow word is a single word at the end of a paragraph on a new line. It's considered bad style.

• $string ­ String with potential widow words

$paragraph='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras id dolor. Donec ...'; $paragraph=text::widont($paragraph);

URL HelperProvides methods for working with URL(s).

Methods

base()url::base() returns the base URL defined by the site_protocol and site_domain in config.php.

// site_domain = 'localhost/kohana/'// site_protocol = 'http' echo url::base();

Generates

http://localhost/kohana/

url::base() accepts two optional parameters. Set the first parameter to TRUE if you want to append the index_page defined in config.php to the base URL. Via the second parameter you can overwrite the default site_protocol from config.php.

// site_domain = 'localhost/kohana/'// site_protocol = 'http'// index_page = 'index.php' echo url::base(TRUE, 'https');

Generates

Page 156: KOHANA PHP framework

https://localhost/kohana/index.php

site()url::site() returns a URL based on the site_protocol, site_domain, index_page, url_suffix defined in config.php.

// site_domain = 'localhost/kohana/'// site_protocol = 'http'// index_page = 'index.php'// url_suffix = '.html' echo url::site();

Generates

http://localhost/kohana/index.php/.html

url::site() accepts two optional parameters. You can pass URL segments via the first one. The second one allows you to overwrite the default site_protocol from config.php.

// site_domain = 'localhost/kohana/'// site_protocol = 'http'// index_page = ''// url_suffix = '.html' echo url::site('admin/login', 'https');

Generates

https://localhost/kohana/admin/login.html

current()url::current() returns the current URI string. This method accepts one optional parameter. If you set it to TRUE the query string will be included in the return value.

// site_domain = 'localhost/kohana/'// site_protocol = 'http'// index_page = 'index.php'// url_suffix = '.html' // Current URL: http://localhost/kohana/index.php/welcome/home.html?query=string echo url::current();

Returns

welcome/home

While

echo url::current(TRUE);

Returns

welcome/home?query=string

Page 157: KOHANA PHP framework

title()url::title() returns a properly formatted title, for use in a URI. The first parameter, the input title string, is mandatory. The optional second parameter is used to set the separator character. By default this is a dash. You can only change this to an underscore.

$input_title = ' __Ecléçtic__ title\'s entered by cràzed users- ?> '; echo url::title($input_title, '_');

Generates:

eclectic_titles_entered_by_crazed_users

What happens to the input title? All non­alphanumeric characters, except for dashes or underscores (depending on the second parameter), will be deleted. However, non­ascii characters will first be transliterated (for example: à becomes a) in order to keep the URL title as readable as possible. Finally, the URL title is converted to lowercase.

redirect()url::redirect() generates an HTTP Server Header (302), which will redirect the browser to a specified URL, by default site_domain defined in config.php.

url::redirect() will always call the php exit function to prevent further script execution.

url::redirect('http://www.whitehouse.gov');

Will redirect the browser to the White House website.

The optional second parameter can be used to set the redirect method. The default is 302.

// site_domain = 'localhost/kohana/'// site_protocol = 'http' url::redirect('aboutus', 301);

Will redirect with a 301 header to http://localhost/kohana/aboutus.

If you wish to send a Multiple Choice (300) redirect, provide an array of URIs to the redirect method:

url::redirect(array('aboutus','http://www.kohana.php/'), 300);

The first URI in the array is considered the preferred URI and will be placed in the Location header. All of the URIs will then be output in a HTML unordered list. Generally the browser will follow the location header and this list will never be seen. However, there is no standard defined behavior for what a user agent should do upon receiving a 300 and the list could be used to present the user with the choices you have given.

Valid HelperProvides methods for validating inputs. It currently features validation for email­addresses, ip's, url's, digits/numbers and text.

Page 158: KOHANA PHP framework

Methods

email()'email' check whether an emailaddress is valid. It is more strict then the valid::email_rfc() method.

• [string] Email address to validate

$email = '[email protected]'; if(valid::email($email) == true) echo "Valid email"; else echo "Invalid email";

It will result in HTML as:

Valid email

email_rfc()'email_rfc' validates an emailaddress based on the RFC specifications (http://www.w3.org/Protocols/rfc822/). This validation is less strict than the valid::email() function.

• [string] Email address to validate

$email = '[email protected]'; if(valid::email($email) == true) echo "Valid email"; else echo "Invalid email";

It will result in HTML as:

Valid email

url()'url' does some simple validation on an URL to find out it if it could be existing.

• [string] URL to be validated• [string] protocol of the URL (e.g. http,ftp) – default = “http”

$url = 'http://www.kohanaphp.com'; if(valid::url($url) == true) echo "Valid URL"; else echo "Invalid URL";

It will result in HTML as:

Valid URL

$url = 'ftp://ftp.kohanaphp.com'; if(valid::url($url,"ftp") == true) echo "Valid URL"; else

Page 159: KOHANA PHP framework

echo "Invalid URL";

It will result in HTML as:

Valid URL

ip()'ip' validates an IP­address to make sure it could exist, but does not guarantee it actually does.

• [string] IP­address to be validated

$ip="123.456.678.912";if(valid::ip($ip) == true) echo "Valid IP";else echo "Invalid IP";

It will result in HTML as:

Invalid IP

$ip="65.181.130.41";if(valid::ip($ip) == true) echo "Valid IP";else echo "Invalid IP";

It will result in HTML as:

Valid IP

alpha()'alpha' checks whether a string consists of alphabetical characters only

• [string] String to be validated• [boolean] If true UTF­8 mode will be used – default = FALSE

$string="KohanaPHP is cool";if(valid::alpha($string) == true) echo "Valid string";else echo "Invalid string";

It will result in HTML as:

Invalid string

$string="KohanaPHPiscool";if(valid::alpha($string) == true) echo "Valid string";else echo "Invalid string";

Page 160: KOHANA PHP framework

It will result in HTML as:

Valid string

alpha_numeric()'alpha_numeric' checks whether a string consists of alphabetical characters and numbers only

• [string] String to be validated• [boolean] If true UTF­8 mode will be used – default = FALSE

$string="KohanaPHP Version 2 is cool";if(valid::alpha_numeric($string) == true) echo "Valid string";else echo "Invalid string";

It will result in HTML as:

Invalid string

$string="KohanaPHPVersion2iscool";if(valid::alpha_numeric($string) == true) echo "Valid string";else echo "Invalid string";

It will result in HTML as:

Valid string

alpha_dash()'alpha_dash' checks whether a string consists of alphabetical characters, numbers, underscores and dashes only

• [string] String to be validated• [boolean] If true UTF­8 mode will be used – default = FALSE

$string="KohanaPHP Version 2 is cool";if(valid::alpha_dash($string) == true) echo "Valid string";else echo "Invalid string";

It will result in HTML as:

Invalid string

$string="KohanaPHP_Version-2-is_cool";if(valid::alpha_dash($string) == true) echo "Valid string";else echo "Invalid string";

Page 161: KOHANA PHP framework

It will result in HTML as:

Valid string

digit()'digit' checks whether a string consists of digits only (no dots or dashes)

• [string] String to be validated• [boolean] If true UTF­8 mode will be used – default = FALSE

$digits = "23424.32";if(valid::digit($digits) == true) echo "Valid";else echo "Invalid";

It will result in HTML as:

Invalid

$digits = "2342432";if(valid::digit($digits) == true) echo "Valid";else echo "Invalid";

It will result in HTML as:

Valid

numeric()'numeric' checks whether a string is a valid number (negative and decimal numbers allowed)

$number = "-23424.32";if(valid::numeric($number) == true) echo "Valid";else echo "Invalid";

It will result in HTML as:

Valid

standard_text()