kohana doc

Upload: jevas

Post on 07-Apr-2018

237 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Kohana Doc

    1/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 globaldata.

    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 quotesare

    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

    http://htmlpurifier.org/http://php.net/mysql_real_escape_stringhttp://en.wikipedia.org/wiki/SQL_injectionhttp://php.net/magic_quoteshttp://php.net/magic_quoteshttp://en.wikipedia.org/wiki/Convention_over_Configurationhttp://en.wikipedia.org/wiki/Loose_coupling#Loose_coupling_in_computinghttp://php.net/mysql_real_escape_stringhttp://en.wikipedia.org/wiki/SQL_injectionhttp://php.net/magic_quoteshttp://en.wikipedia.org/wiki/Convention_over_Configurationhttp://en.wikipedia.org/wiki/Loose_coupling#Loose_coupling_in_computinghttp://htmlpurifier.org/
  • 8/6/2019 Kohana Doc

    2/161

    community feedback.

    MVC

    Kohana 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.

    CodeIgniter

    Kohana was originally a fork ofCodeIgniter (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.

    http://en.wikipedia.org/wiki/Model-View-Controllerhttp://codeigniter.com/http://codeigniter.com/http://ellislab.com/http://codeigniter.com/user_guide/license.htmlhttp://phputf8.sourceforge.net/http://en.wikipedia.org/wiki/Model-View-Controllerhttp://codeigniter.com/http://ellislab.com/http://codeigniter.com/user_guide/license.htmlhttp://phputf8.sourceforge.net/
  • 8/6/2019 Kohana Doc

    3/161

    phputf8 is 2005 Harry Fuecks.

    Popoon

    The default XSS filter used by Kohana was originally created byChristian Stocker for the popoon

    framework. The original file is calledexternalinput.php.

    popoon is 2001 2006 Bitflux GmbH

    HTML Purifier

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

    HTML Purifier is 2006 2007 Edward Z. Yang

    SwiftMailer

    The recommended way to send emails in Kohana is usingSwiftMailer. This is an optional

    download.

    SwiftMailer is Chris Corbyn

    PHP Markdown

    Markdown 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.0

    November 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 Days

    September October 2007

    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txthttp://www.liip.ch/http://www.liip.ch/http://www.popoon.org/http://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.phphttp://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.phphttp://svn.bitflux.ch/repos/public/popoon/trunk/LICENSEhttp://htmlpurifier.org/http://htmlpurifier.org/svnroot/htmlpurifier/trunk/LICENSEhttp://www.swiftmailer.org/http://www.swiftmailer.org/http://swiftmailer.svn.sourceforge.net/svnroot/swiftmailer/trunk/php4/LICENSEhttp://en.wikipedia.org/wiki/Markdownhttp://michelf.com/projects/php-markdownhttp://michelf.com/projects/php-markdown/licensehttp://en.wikiquote.org/wiki/George_Santayanahttp://en.wikiquote.org/wiki/George_Santayanahttp://www.gnu.org/licenses/old-licenses/lgpl-2.1.txthttp://www.liip.ch/http://www.popoon.org/http://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.phphttp://svn.bitflux.ch/repos/public/popoon/trunk/LICENSEhttp://htmlpurifier.org/http://htmlpurifier.org/svnroot/htmlpurifier/trunk/LICENSEhttp://www.swiftmailer.org/http://swiftmailer.svn.sourceforge.net/svnroot/swiftmailer/trunk/php4/LICENSEhttp://en.wikipedia.org/wiki/Markdownhttp://michelf.com/projects/php-markdownhttp://michelf.com/projects/php-markdown/licensehttp://en.wikiquote.org/wiki/George_Santayana
  • 8/6/2019 Kohana Doc

    4/161

    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 Times

    August 2007. Our Project leader goes walkabout, not much happens.

    Kohana 1.0

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

    Lots of ideas and discussions on the way forward,

    Kohana

    June 2007.

    A new Name, forum, Trac.

    In The Beginning

    BlueFlame, 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 support

    2. PHP version >= 5.1.3

    3. 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 andPostgreSQL, with addition drivers planned.

    Required Extensions

    1. PCRE must be compiled with enable-utf8 and enable-unicode-propertiesfor UTF 8 functions to work properly.

    http://codeigniter.com/forums/viewthread/53347/http://unicode.org/http://docs.kohanaphp.com/libraries/databasehttp://www.mysql.com/http://www.postgresql.org/http://www.postgresql.org/http://php.net/pcrehttp://codeigniter.com/forums/viewthread/53347/http://unicode.org/http://docs.kohanaphp.com/libraries/databasehttp://www.mysql.com/http://www.postgresql.org/http://php.net/pcre
  • 8/6/2019 Kohana Doc

    5/161

    2. iconv is required for UTF 8 transliteration.

    3. mcrypt is required for encryption.

    4. SPL is required for several core libraries.1)

    Recommended Extensions

    1. 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 favoritebrowser

    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 Configuration

    You 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 toconfigure a database connection, you can copy over system/config/database.php toapplication/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 readtheTroubleshooting page of the user guide, visit the Kohana Wiki, or ask for assistance in the

    community forums.

    http://php.net/iconvhttp://php.net/mcrypthttp://php.net/splhttp://docs.kohanaphp.com/installation/requirements#fn__1http://docs.kohanaphp.com/installation/requirements#fn__1http://php.net/mbstringhttp://kohanaphp.com/download.htmlhttp://docs.kohanaphp.com/general/configurationhttp://kohanaphp.com/tutorials/remove_index.htmlhttp://docs.kohanaphp.com/libraries/database/configurationhttp://docs.kohanaphp.com/libraries/database/configurationhttp://docs.kohanaphp.com/general/troubleshootinghttp://docs.kohanaphp.com/general/troubleshootinghttp://trac.kohanaphp.com/wikihttp://forum.kohanaphp.com/http://php.net/iconvhttp://php.net/mcrypthttp://php.net/splhttp://docs.kohanaphp.com/installation/requirements#fn__1http://php.net/mbstringhttp://kohanaphp.com/download.htmlhttp://docs.kohanaphp.com/general/configurationhttp://kohanaphp.com/tutorials/remove_index.htmlhttp://docs.kohanaphp.com/libraries/database/configurationhttp://docs.kohanaphp.com/general/troubleshootinghttp://trac.kohanaphp.com/wikihttp://forum.kohanaphp.com/
  • 8/6/2019 Kohana Doc

    6/161

    [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 Users

    To 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'sdocument 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 ofthe 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 in

    2. Open index.php file in an editor

    3. 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 bymultiple 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 applicationA, 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

    http://trac.kohanaphp.com/newtickethttp://kohanaphp.com/download.htmlhttp://docs.kohanaphp.com/installation/upgrading/2.2http://docs.kohanaphp.com/installation/upgrading/2.1http://trac.kohanaphp.com/newtickethttp://kohanaphp.com/download.htmlhttp://docs.kohanaphp.com/installation/upgrading/2.2http://docs.kohanaphp.com/installation/upgrading/2.1
  • 8/6/2019 Kohana Doc

    7/161

  • 8/6/2019 Kohana Doc

    8/161

    show_errors has been removed.

    Helpers

    Helpers must be renamed from helper_name to helper_name_Core if they need tobe extended.

    The parameter to add index.php from the URL in html helpers now defaults to false, itneeds 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).

    $querynum_rows() has been removed. Use count(query) instead.

    Deprecated stuff

    Use http_build_query() instead ofhtml::query_string(). Use $thispaginationsql_offset instead of$thispaginationsql_offset().

    Use $thispaginationsql_limit instead of$thispaginationsql_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

    http://docs.kohanaphp.com/core/kohana#debughttp://docs.kohanaphp.com/core/kohana#debughttp://docs.kohanaphp.com/libraries/profilerhttp://docs.kohanaphp.com/core/loghttp://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/http://forum.kohanaphp.com/http://forum.kohanaphp.com/index.php?action=searchhttp://docs.kohanaphp.com/core/kohana#debughttp://docs.kohanaphp.com/libraries/profilerhttp://docs.kohanaphp.com/core/loghttp://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/http://forum.kohanaphp.com/http://forum.kohanaphp.com/index.php?action=search
  • 8/6/2019 Kohana Doc

    9/161

    production environment.

    1. Remove the various demo and example controllers

    Kohana 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 files

    Kohana 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 defaultconfiguration 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 productiondomain.

    set $config['display_errors'] = FALSE; to disable error messages from beingdisplayed. 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 (ifrequired)

    system/config/log.php set your $config['threshold'] = 1;. This setsyour 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 root

    If 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 securitypractice 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

    http://docs.kohanaphp.com/general/filesystemhttp://kohanaphp.com/tutorials/remove_index.htmlhttp://docs.kohanaphp.com/general/filesystemhttp://kohanaphp.com/tutorials/remove_index.html
  • 8/6/2019 Kohana Doc

    10/161

    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 levelabove 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 orabsolute 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 URLs

    Removing 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 rewritingRewriteEngineOn

    # 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} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

    # For reuests that are not actual files or directories,

  • 8/6/2019 Kohana Doc

    11/161

    # 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/installationto learn how to move system/ and application/ out ofyour 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 rewritingRewriteEngineOn

    # 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/URL

    RewriteRule ^(.*)$ 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.phpBecause we are rewriting the URL to index.php/access_denied/, we will need aController to handle these URLs. Let's create one now:

    http://doc.kohanaphp.com/installationhttp://doc.kohanaphp.com/installationhttp://doc.kohanaphp.com/installationhttp://doc.kohanaphp.com/installationhttp://doc.kohanaphp.com/installation
  • 8/6/2019 Kohana Doc

    12/161

  • 8/6/2019 Kohana Doc

    13/161

    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 somesituations 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.

    Installation

    Starting with a fresh Kohana install, delete application folder, and copy your existing

    application folder to the same location.

    Configuration

    Remove your old config folder.

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

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

    3. Review theUser Guide: Configuration page

    Logging

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

    Class Names

    Rename all your controllers to {NAME}_Controller. For example, if your old controller wasPage, make it Page_Controller.

    Make your Controller contructors PHP5 if needed:1. function __construct() instead offunction Page()2. parent::__construct() instead ofparent::Controller()

    http://httpd.apache.org/docs/2.0/mod/mod_rewrite.htmlhttp://httpd.apache.org/docs/2.0/mod/mod_rewrite.htmlhttp://httpd.apache.org/docs/2.0/mod/mod_rewrite.htmlhttp://docs.kohanaphp.com/general/configurationhttp://docs.kohanaphp.com/general/configurationhttp://httpd.apache.org/docs/2.0/mod/mod_rewrite.htmlhttp://httpd.apache.org/docs/2.0/mod/mod_rewrite.htmlhttp://docs.kohanaphp.com/general/configuration
  • 8/6/2019 Kohana Doc

    14/161

    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: $thisloadmodel('page')3. If you add a __construct() function, be sure to call parent::__construct()

    Libraries

    Base Controllers

    If 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 extendsController_Core

    2. Change references to MY_Controller in your controllers to Controller

    3. Use the PHP5 syntax for the constructor in your base controller

    URI

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

    Other

    Class names need to have _Core appended to them and be capitalized. The file names should alsohave 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).

    $thisload is deprecated. Kohana uses auto loading so you can instantiate an object (e.g. newView()) without including the class first.

    Helpers

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

    1. Example: html::anchor() instead ofanchor()

    2. Example: url::base instead ofbase_url()3. Example: form::open() instead ofform_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:

  • 8/6/2019 Kohana Doc

    15/161

    change it to the following to work in Kohana:

    for

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

    Models

    There 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);

    http://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/arrayhttp://www.php.net/arrayhttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echo
  • 8/6/2019 Kohana Doc

    16/161

  • 8/6/2019 Kohana Doc

    17/161

  • 8/6/2019 Kohana Doc

    18/161

    Kohana Filesystem

    File types

    Strictly 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 Basics

    First 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

    http://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/libraries/validationhttp://docs.kohanaphp.com/libraries/inputhttp://docs.kohanaphp.com/libraries/ormhttp://docs.kohanaphp.com/libraries/archivehttp://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/libraries/validationhttp://docs.kohanaphp.com/libraries/inputhttp://docs.kohanaphp.com/libraries/ormhttp://docs.kohanaphp.com/libraries/archive
  • 8/6/2019 Kohana Doc

    19/161

    | +- 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.

    Cascading

    The 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 viewfile called layout.php in the application/viewsandsystem/views directories, the one in application will be returned when layout.php issearched 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.

    Modular

    The 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 aretreated no differently from regular modules apart from the exceptions listed below.

    Exceptions

    There are 2 main exceptions in the filesystem:

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

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

    Configuration and i18n Files

    These 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 infiles lower down.

    http://docs.kohanaphp.com/general/viewshttp://docs.kohanaphp.com/general/viewshttp://en.wikipedia.org/wiki/Image:Kohana-modules.pnghttp://docs.kohanaphp.com/general/moduleshttp://docs.kohanaphp.com/general/viewshttp://en.wikipedia.org/wiki/Image:Kohana-modules.pnghttp://docs.kohanaphp.com/general/modules
  • 8/6/2019 Kohana Doc

    20/161

    See Configuration and Internationalization for more information on this.

    Built in directories

    cache

    By default, theCache 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.

    config

    All configuration files that are read by theConfig classmust be stored here.

    controllers

    All controllersto be directed to by the router must go in here.

    helpers

    See Helpers.

    hooks

    See Hooks.

    i18n

    Language 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 .

    libraries

    See Libraries.

    logs

    By default, log files generated by the Log classare stored in the application/logs directory.

    models

    See Models.

    vendor

    3rd party libraries and scripts that are not integrated into Kohana should be stored here. See

    Librariesfor more information.

    views

    See Views.

    http://docs.kohanaphp.com/general/configurationhttp://docs.kohanaphp.com/general/i18nhttp://docs.kohanaphp.com/libraries/cachehttp://docs.kohanaphp.com/libraries/cachehttp://docs.kohanaphp.com/core/confighttp://docs.kohanaphp.com/core/confighttp://docs.kohanaphp.com/core/confighttp://docs.kohanaphp.com/general/controllershttp://docs.kohanaphp.com/general/controllershttp://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/general/helpershttp://docs.kohanaphp.com/general/hookshttp://docs.kohanaphp.com/core/kohana#kohanalanghttp://docs.kohanaphp.com/general/i18nhttp://docs.kohanaphp.com/general/librarieshttp://docs.kohanaphp.com/core/loghttp://docs.kohanaphp.com/core/loghttp://docs.kohanaphp.com/general/modelshttp://docs.kohanaphp.com/general/librarieshttp://docs.kohanaphp.com/general/librarieshttp://docs.kohanaphp.com/general/viewshttp://docs.kohanaphp.com/general/configurationhttp://docs.kohanaphp.com/general/i18nhttp://docs.kohanaphp.com/libraries/cachehttp://docs.kohanaphp.com/core/confighttp://docs.kohanaphp.com/general/controllershttp://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/general/helpershttp://docs.kohanaphp.com/general/hookshttp://docs.kohanaphp.com/core/kohana#kohanalanghttp://docs.kohanaphp.com/general/i18nhttp://docs.kohanaphp.com/general/librarieshttp://docs.kohanaphp.com/core/loghttp://docs.kohanaphp.com/general/modelshttp://docs.kohanaphp.com/general/librarieshttp://docs.kohanaphp.com/general/views
  • 8/6/2019 Kohana Doc

    21/161

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

    Structure of config files

    Configuration 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 files

    The 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 ishardcoded into the application/config directory and cannot be moved elsewhere.

    config.php

    Config.phpis 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 * 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 Cachelibrary.

    http://docs.kohanaphp.com/core/confighttp://docs.kohanaphp.com/core/confighttp://docs.kohanaphp.com/general/configuration/confighttp://docs.kohanaphp.com/general/configuration/confighttp://docs.kohanaphp.com/libraries/cachehttp://docs.kohanaphp.com/core/confighttp://docs.kohanaphp.com/general/configuration/confighttp://docs.kohanaphp.com/libraries/cache
  • 8/6/2019 Kohana Doc

    22/161

    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.phpSets the logging threshold. See the Logpage.

    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

    http://docs.kohanaphp.com/helpers/cookiehttp://docs.kohanaphp.com/libraries/database/configurationhttp://docs.kohanaphp.com/general/hookshttp://docs.kohanaphp.com/general/i18nhttp://docs.kohanaphp.com/core/loghttp://docs.kohanaphp.com/core/loghttp://docs.kohanaphp.com/libraries/paginationhttp://docs.kohanaphp.com/libraries/profilerhttp://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/libraries/user_agenthttp://docs.kohanaphp.com/helpers/cookiehttp://docs.kohanaphp.com/libraries/database/configurationhttp://docs.kohanaphp.com/general/hookshttp://docs.kohanaphp.com/general/i18nhttp://docs.kohanaphp.com/core/loghttp://docs.kohanaphp.com/libraries/paginationhttp://docs.kohanaphp.com/libraries/profilerhttp://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/libraries/user_agent
  • 8/6/2019 Kohana Doc

    23/161

    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 theindex() 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');}

    }

    Segments

    As said, Kohana urls contain segments.

    http://localhost/control/action/arg1/arg2http://docs.kohanaphp.com/general/controllershttp://www.php.net/echohttp://localhost/control/action/arg1/arg2http://docs.kohanaphp.com/general/controllershttp://www.php.net/echo
  • 8/6/2019 Kohana Doc

    24/161

    Example

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

    Contains the segments

    articles

    edit 1

    my first article

    AURI 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 rewriting

    By 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.

    Suffix

    Kohana 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 therouting page.

    Query strings and GET support

    Query 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.

    http://docs.kohanaphp.com/libraries/urihttp://docs.kohanaphp.com/libraries/urihttp://docs.kohanaphp.com/helpers/urlhttp://kohanaphp.com/tutorials/remove_index.htmlhttp://forumarchive.kohanaphp.com/index.php/topic,246.0.htmlhttp://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/libraries/urihttp://docs.kohanaphp.com/helpers/urlhttp://kohanaphp.com/tutorials/remove_index.htmlhttp://forumarchive.kohanaphp.com/index.php/topic,246.0.htmlhttp://docs.kohanaphp.com/general/routing
  • 8/6/2019 Kohana Doc

    25/161

    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 theURI 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 configuration

    In order to alter routing you have to have a copy ofroutes.php in yourapplication/config directory. If it is not already there copy the one from thesystem/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 changingthis, 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 controllershould 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 controllerwould be used even though it wasn't specified in the URI. The result would be the same as if the

    browser had gone towww.example.com/welcome.

    Specifying your own routes

    In 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.comand youhad the following routing rule:

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

    and you visitedwww.example.com/test in a web browser, you would see the page at

    www.example.com/foo/bar.

    http://www.example.com/article/22http://www.example.com/http://www.example.com/welcomehttp://www.example.com/welcomehttp://www.example.com/http://www.example.com/http://www.example.com/testhttp://www.example.com/testhttp://www.example.com/foo/barhttp://www.example.com/article/22http://www.example.com/http://www.example.com/welcomehttp://www.example.com/http://www.example.com/testhttp://www.example.com/foo/bar
  • 8/6/2019 Kohana Doc

    26/161

  • 8/6/2019 Kohana Doc

    27/161

    Loading libraries

    Libraries 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 database

    Apart 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 helpers

    Note:

    Loading a helper using $thisloadhelper() 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

    automaticallyecho url::base();

    Loading views

    Views 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 theviews page Information on the

    view class can be found on the view class page.

    Example

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

    Loading models

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

    theModels page.

    http://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://docs.kohanaphp.com/general/viewshttp://docs.kohanaphp.com/general/viewshttp://docs.kohanaphp.com/core/viewshttp://docs.kohanaphp.com/general/modelshttp://docs.kohanaphp.com/general/modelshttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://docs.kohanaphp.com/general/viewshttp://docs.kohanaphp.com/core/viewshttp://docs.kohanaphp.com/general/models
  • 8/6/2019 Kohana Doc

    28/161

  • 8/6/2019 Kohana Doc

    29/161

    A simple controller

    We 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 controller

    In 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 urlwww.yoursite.com/article/overview it will display

    Article list goes here!

    Controller with arguments

    Say 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()

    http://www.php.net/echohttp://www.yoursite.com/articlehttp://www.yoursite.com/articlehttp://www.yoursite.com/articlehttp://www.yoursite.com/article/indexhttp://www.php.net/echohttp://www.php.net/echohttp://www.yoursite.com/article/overviewhttp://www.yoursite.com/article/overviewhttp://www.yoursite.com/article/view/http://www.php.net/echohttp://www.yoursite.com/articlehttp://www.yoursite.com/articlehttp://www.yoursite.com/article/indexhttp://www.php.net/echohttp://www.php.net/echohttp://www.yoursite.com/article/overviewhttp://www.yoursite.com/article/view/
  • 8/6/2019 Kohana Doc

    30/161

    { 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 subdirectories

    If 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.phpwill correspond to the urlhttp://localhost/admin/user

    Routing controllers elsewhere

    If for some reason the mapping from the URI to the controller and method is not right for you youcan use routing to map a URI to another controller. E.g. have localhost/about/me map to

    http://localhost/articles/view/1

    See Routingfor more information on this.

    Special methods

    index

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

    _remap

    If 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 )

    http://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.yoursite.com/article/view/http://localhost/admin/userhttp://localhost/admin/userhttp://localhost/admin/userhttp://localhost/articles/view/1http://docs.kohanaphp.com/general/routinghttp://docs.kohanaphp.com/general/routinghttp://example.com/welcomehttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.yoursite.com/article/view/http://localhost/admin/userhttp://localhost/admin/userhttp://localhost/articles/view/1http://docs.kohanaphp.com/general/routinghttp://example.com/welcome
  • 8/6/2019 Kohana Doc

    31/161

    {// 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 methods

    Sometimes 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!';

    }

    http://learn.kohanaphp.com/2008/03/26/using-_remap/http://example.com/welcome/sthrandom90923http://example.com/welcome/sthrandom90923http://www.php.net/echohttp://learn.kohanaphp.com/2008/03/26/using-_remap/http://example.com/welcome/sthrandom90923http://example.com/welcome/sthrandom90923http://www.php.net/echo
  • 8/6/2019 Kohana Doc

    32/161

    private function _article_form(){

    echo 'Article form';}

    }

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

    Class constructors

    If 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 callwww.yoursite.com/article/view/5 , it will retrieve the article whose id is 5.

    Special Controllers

    Using a base controller for your application

    Using 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.

    ExampleMY_Controller.php

  • 8/6/2019 Kohana Doc

    33/161

    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 inapplication/libraries This class has all the methods of the original Controller plus yourown.

    Note: The prefix MY_ can be configured in application/config/config.php bychanging 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 libraries

    When 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 toextend 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 thefollowing file:

    http://docs.kohanaphp.com/general/loadinghttp://docs.kohanaphp.com/general/loading
  • 8/6/2019 Kohana Doc

    34/161

    File: application/libraries/Book.php

    Extending libraries

    Kohana 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 theirclass 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 theconfiguration 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

  • 8/6/2019 Kohana Doc

    35/161

    application.

    The deprecated preloadconfiguration option (which pre loads libraries and models) has beenreplaced 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

    3rd party libraries

    If you should require 3rd party libraries (such as Simplepie, Zend Framework, or Pear libraries) youcan 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 thefollowing 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

    http://docs.kohanaphp.com/general/configurationhttp://docs.kohanaphp.com/libraries/profilerhttp://www.php.net/definedhttp://www.php.net/diehttp://docs.kohanaphp.com/core/kohanahttp://www.php.net/ini_sethttp://www.php.net/ini_gethttp://docs.kohanaphp.com/general/configurationhttp://docs.kohanaphp.com/libraries/profilerhttp://www.php.net/definedhttp://www.php.net/diehttp://docs.kohanaphp.com/core/kohanahttp://www.php.net/ini_sethttp://www.php.net/ini_get
  • 8/6/2019 Kohana Doc

    36/161

    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 ofa 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 helpers

    When 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, inmodules/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

  • 8/6/2019 Kohana Doc

    37/161

    ?>

    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 newhelper 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 classnames.

    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'sHTML helper. You might do the

    following:

    File:application/helpers/MY_html.php

    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

  • 8/6/2019 Kohana Doc

    38/161

    }?>

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

    Overview

    Views 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 intothem. 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 views

    Views need to be placed in the views directory. The filename minus the extension becomes theview'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 views

    There 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 object

    Create a new instance of the class.

    $view = new View('welcome');

    http://docs.kohanaphp.com/core/viewhttp://docs.kohanaphp.com/core/view
  • 8/6/2019 Kohana Doc

    39/161

    Factory

    Use 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');

    Loader

    Since 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:

    Note:

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

    Note:

    You cannot use $view data = $data;

    http://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echo
  • 8/6/2019 Kohana Doc

    40/161

    Views within views

    To 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 inview header.php$view->content->heading = 'Heading of your page'; // string for variable$heading in view content.php$view->footer->copyright = 'Copyright'; // string for variable $headingin view footer.php$view->render(TRUE);

    View: template.php

    View: header.php

    View: content.php

    View: footer.php

    Output:

    Title of page

    Heading of your page

    Copyright

    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 anddynamic content (banners, customized ads) to add a professional touch.

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

    http://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://december.com/html/4/element/html.htmlhttp://december.com/html/4/element/head.htmlhttp://december.com/html/4/element/title.htmlhttp://december.com/html/4/element/body.htmlhttp://december.com/html/4/element/h1.htmlhttp://docs.kohanaphp.com/addons/templatehttp://docs.kohanaphp.com/addons/templatehttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://www.php.net/echohttp://december.com/html/4/element/html.htmlhttp://december.com/html/4/element/head.htmlhttp://december.com/html/4/element/title.htmlhttp://december.com/html/4/element/body.htmlhttp://december.com/html/4/element/h1.htmlhttp://docs.kohanaphp.com/addons/template
  • 8/6/2019 Kohana Doc

    41/161

    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 Example

    Controller: 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

  • 8/6/2019 Kohana Doc

    42/161

    echo $product['quantity']; echo '';

    }?>

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

    Output:

    Products Products

    Product13 Product27

    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

    http://www.php.net/echohttp://www.php.net/echohttp://december.com/html/4/element/html.htmlhttp://december.com/html/4/element/head.htmlhttp://december.com/html/4/element/title.htmlhttp://december.com/html/4/element/body.htmlhttp://december.com/html/4/element/h1.htmlhttp://december.com/html/4/element/table.htmlhttp://december.com/html/4/element/tr.htmlhttp://december.com/html/4/element/tr.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/tr.htmlhttp://december.com/html/4/element/tr.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/td.htmlhttp://docs.kohanaphp.com/libraries/ormhttp://www.php.net/echohttp://www.php.net/echohttp://december.com/html/4/element/html.htmlhttp://december.com/html/4/element/head.htmlhttp://december.com/html/4/element/title.htmlhttp://december.com/html/4/element/body.htmlhttp://december.com/html/4/element/h1.htmlhttp://december.com/html/4/element/table.htmlhttp://december.com/html/4/element/tr.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/tr.htmlhttp://december.com/html/4/element/td.htmlhttp://december.com/html/4/element/td.htmlhttp://docs.kohanaphp.com/libraries/orm
  • 8/6/2019 Kohana Doc

    43/161

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

    The file would initially look something like this:

  • 8/6/2019 Kohana Doc

    44/161

    public function __construct($id = NULL){

    // load database library into $this->db (can be omitted if notrequired)

    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 $thisinputpost('var_name',

    TRUE) to ensure data is sanitized before using. Learn more about the Input library.

    Using a database in your model

    If your model's constructor contains the line parent::__construct();, the default databasefunctionality will be loaded into $thisdb. You can use all of the database's functions with the$thisdb object.

    Using a model in your controller

    Using 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

    http://docs.kohanaphp.com/libraries/inputhttp://docs.kohanaphp.com/libraries/input
  • 8/6/2019 Kohana Doc

    45/161

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

    controller constructor: $thisuser = 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 =$thisuserget_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 $username. See Database Library for moreinformation.

    ORM

    See 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 modelfor, 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 andcallback. 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 Events

    The 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. CallsRouter::find_uri and Router::setup by default.

    system.execute

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

    CallsKohana::instanceby default.

    system.post_routing

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

    http://docs.kohanaphp.com/general/viewshttp://docs.kohanaphp.com/libraries/database/resulthttp://docs.kohanaphp.com/libraries/ormhttp://docs.kohanaphp.com/core/eventhttp://php.net/manual/en/language.pseudo-types.php#language.types.callbackhttp://php.net/manual/en/language.pseudo-types.php#language.types.callbackhttp://docs.kohanaphp.com/general/events#fn__1http://docs.kohanaphp.com/general/events#fn__1http://docs.kohanaphp.com/core/kohana#setuphttp://docs.kohanaphp.com/libraries/router#setuphttp://docs.kohanaphp.com/libraries/router#setuphttp://docs.kohanaphp.com/libraries/router#setuphttp://docs.kohanaphp.com/core/kohana#instancehttp://docs.kohanaphp.com/core/kohana#instancehttp://docs.kohanaphp.com/core/kohana#instancehttp://docs.kohanaphp.com/general/viewshttp://docs.kohanaphp.com/libraries/database/resulthttp://docs.kohanaphp.com/libraries/ormhttp://docs.kohanaphp.com/core/eventhttp://php.net/manual/en/language.pseudo-types.php#language.types.callbackhttp://docs.kohanaphp.com/general/events#fn__1http://docs.kohanaphp.com/core/kohana#setuphttp://docs.kohanaphp.com/libraries/router#setuphttp://docs.kohanaphp.com/libraries/router#setuphttp://docs.kohanaphp.com/core/kohana#instance
  • 8/6/2019 Kohana Doc

    46/161

    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, andSession data will not be saved.

    system.display

    Displays the output that Kohana has generated. Views can be loaded, but headers have already beensent. The rendered output can be manipulated asEvent::$data.

    system.shutdown

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

    default.

    Hooks

    Hooks are included early in Kohana and can be used to execute code before e.g. controllers areloaded 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 theHooks 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

    http://docs.kohanaphp.com/core/kohana#show_404http://docs.kohanaphp.com/general/events#system.executehttp://docs.kohanaphp.com/core/kohana#instancehttp://docs.kohanaphp.com/general/events#system.executehttp://docs.kohanaphp.com/core/kohana#instancehttp://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/general/events#datahttp://docs.kohanaphp.com/general/events#datahttp://docs.kohanaphp.com/general/hookshttp://docs.kohanaphp.com/general/hookshttp://docs.kohanaphp.com/general/events#fnt__1http://docs.kohanaphp.com/core/kohana#show_404http://docs.kohanaphp.com/general/events#system.executehttp://docs.kohanaphp.com/core/kohana#instancehttp://docs.kohanaphp.com/general/events#system.executehttp://docs.kohanaphp.com/core/kohana#instancehttp://docs.kohanaphp.com/libraries/sessionhttp://docs.kohanaphp.com/general/events#datahttp://docs.kohanaphp.com/general/hookshttp://docs.kohanaphp.com/general/events#fnt__1
  • 8/6/2019 Kohana Doc

    47/161

    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.readyHook files should be put in application/hooks or similarly in a module folder.

    Configuring hooks

    To configure hooks edit 'hooks.php in your application/config directory. If the file is not therecopy 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 beincluded.

    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 events

    The power of hooks mainly comes from the Eventsclass. 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.'';

    }}Event::add('system.display', array('Power', 'Kohana'));

    This will add a small notice to the bottom of each page (). 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

    http://www.php.net/arrayhttp://docs.kohanaphp.com/core/eventhttp://docs.kohanaphp.com/core/eventhttp://www.php.net/arrayhttp://www.php.net/arrayhttp://docs.kohanaphp.com/core/eventhttp://www.php.net/array
  • 8/6/2019 Kohana Doc

    48/161

    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_errors

    In 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.

    Exceptions

    Exceptions 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_Exception

    Kohana_Exception extends Exception. To throw a Kohana_Exception an i18nlanguage 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"//...

    http://docs.kohanaphp.com/core/loghttp://docs.kohanaphp.com/general/errorhandling#kohana_exceptionhttp://docs.kohanaphp.com/general/errorhandling#kohana_exceptionhttp://docs.kohanaphp.com/general/errorhandling#kohana_user_exceptionhttp://docs.kohanaphp.com/general/errorhandling#kohana_user_excepti