Kohana v3.3.0

This commit is contained in:
Deon George
2013-04-22 14:09:50 +10:00
commit f96694b18f
1280 changed files with 145034 additions and 0 deletions

View File

@@ -0,0 +1,93 @@
# Clean URLs
Removing `index.php` from your urls.
To keep your URLs clean, you will probably want to be able to access your app without having `/index.php/` in the URL. There are two steps to remove `index.php` from the URL.
1. Edit the bootstrap file
2. Set up rewriting
## 1. Configure Bootstrap
The first thing you will need to change is the `index_file` setting of [Kohana::init] to false:
Kohana::init(array(
'base_url' => '/myapp/',
'index_file' => FALSE,
));
This change will make it so all of the links generated using [URL::site], [URL::base], and [HTML::anchor] will no longer include "index.php" in the URL. All generated links will start with `/myapp/` instead of `/myapp/index.php/`.
## 2. URL Rewriting
Enabling rewriting is done differently, depending on your web server.
Rewriting will make it so urls will be passed to index.php.
## Apache
Rename `example.htaccess` to only `.htaccess` and alter the `RewriteBase` line to match the `base_url` setting from your [Kohana::init]
RewriteBase /myapp/
The rest of the `.htaccess file` rewrites all requests through index.php, unless the file exists on the server (so your css, images, favicon, etc. are still loaded like normal). In most cases, you are done!
### 404 errors
If you get a "404 Not Found" error when trying to view a page then it's likely Apache is not configured to read the `.htaccess` file.
In the main apache configuration file (usually `httpd.conf`), or in the virtual server configuration file, check that the `AccessFileName` directive is set to `.htaccess` and the `AllowOverride` directive is set to `All`.
AccessFileName .htaccess
<Directory "/var/www/html/myapp">
AllowOverride All
</Directory>
### Failed!
If you get a "Internal Server Error" or "No input file specified" error, try changing:
RewriteRule ^(?:application|modules|system)\b - [F,L]
Instead, we can try a slash:
RewriteRule ^(application|modules|system)/ - [F,L]
If that doesn't work, try changing:
RewriteRule .* index.php/$0 [PT]
To something more simple:
RewriteRule .* index.php [PT]
### Still Failed!
If you are still getting errors, check to make sure that your host supports URL `mod_rewrite`. If you can change the Apache configuration, add these lines to the configuration, usually `httpd.conf`:
<Directory "/var/www/html/myapp">
Order allow,deny
Allow from all
AllowOverride All
</Directory>
You should also check your Apache logs to see if they can shed some light on the error.
## NGINX
It is hard to give examples of nginx configuration, but here is a sample for a server:
location / {
index index.php index.html index.htm;
try_files $uri index.php;
}
location = index.php {
include fastcgi.conf;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
}
If you are having issues getting this working, enable debug level logging in nginx and check the access and error logs.

View File

@@ -0,0 +1,99 @@
# Custom Error Pages
Custom error pages allow you to display a friendly error message to users, rather than the standard Kohana stack trace.
## Prerequisites
1. You will need `'errors' => TRUE` passed to [Kohana::init]. This will convert PHP-errors into exceptions which are easier to handle (The default value is `TRUE`).
2. Custom error pages will only be used to handle throw [HTTP_Exception]'s. If you simply set a status of, for example, 404 via [Respose::status] the custom page will not be used.
## Extending the HTTP_Exception classes
Handling [HTTP_Exception]'s in Kohana has become easier with the changes introduced in 3.3.
For each [HTTP_Exception] class we can individually override the generation of the [Response] instance.
[!!] Note: We can also use HMVC to issue a sub-request to another page rather than generating the [Response] in the [HTTP_Exception] itself.
For example, to handle 404 pages we can do this in APPPATH/classes/HTTP/Exception/404.php:
class HTTP_Exception_404 extends Kohana_HTTP_Exception_404 {
/**
* Generate a Response for the 404 Exception.
*
* The user should be shown a nice 404 page.
*
* @return Response
*/
public function get_response()
{
$view = View::factory('errors/404');
// Remembering that `$this` is an instance of HTTP_Exception_404
$view->message = $this->getMessage();
$response = Response::factory()
->status(404)
->body($view->render());
return $response;
}
}
Another example, this time to handle 401 Unauthorized errors (aka "Not Logged In") we can do this in APPPATH/classes/HTTP/Exception/401.php:
class HTTP_Exception_401 extends Kohana_HTTP_Exception_401 {
/**
* Generate a Response for the 401 Exception.
*
* The user should be redirect to a login page.
*
* @return Response
*/
public function get_response()
{
$response = Response::factory()
->status(401)
->headers('Location', URL::site('account/login'));
return $response;
}
}
Finally, to override the default [Response] for all [HTTP_Exception]'s without a more specific override we can do this in APPPATH/classes/HTTP/Exception.php:
class HTTP_Exception extends Kohana_HTTP_Exception {
/**
* Generate a Response for all Exceptions without a more specific override
*
* The user should see a nice error page, however, if we are in development
* mode we should show the normal Kohana error page.
*
* @return Response
*/
public function get_response()
{
// Lets log the Exception, Just in case it's important!
Kohana_Exception::log($this);
if (Kohana::$environment >= Kohana::DEVELOPMENT)
{
// Show the normal Kohana error page.
return parent::get_response();
}
else
{
// Generate a nicer looking "Oops" page.
$view = View::factory('errors/default');
$response = Response::factory()
->status($this->getCode())
->body($view->render());
return $response;
}
}
}

View File

@@ -0,0 +1,143 @@
# Creating a New Application
[!!] The following examples assume that your web server is already set up, and you are going to create a new application at <http://localhost/gitorial/>.
Using your console, change to the empty directory `gitorial` and run `git init`. This will create the bare structure for a new git repository.
Next, we will create a [submodule](http://www.kernel.org/pub/software/scm/git/docs/git-submodule.html) for the `system` directory. Go to <http://github.com/kohana/core> and copy the "Clone URL":
![Github Clone URL](http://img.skitch.com/20091019-rud5mmqbf776jwua6hx9nm1n.png)
Now use the URL to create the submodule for `system`:
git submodule add git://github.com/kohana/core.git system
[!!] This will create a link to the current development version of the next stable release. The development version should almost always be safe to use, have the same API as the current stable download with bugfixes applied.
Now add whatever submodules you need. For example, if you need the [Database] module:
git submodule add git://github.com/kohana/database.git modules/database
After submodules are added, they must be initialized:
git submodule init
Now that the submodules are added, you can commit them:
git commit -m 'Added initial submodules'
Next, create the application directory structure. This is the bare minimum required:
mkdir -p application/classes/{Controller,Model}
mkdir -p application/{config,views}
mkdir -m 0777 -p application/{cache,logs}
If you run `find application` you should see this:
application
application/cache
application/config
application/classes
application/classes/Controller
application/classes/Model
application/logs
application/views
We don't want git to track log or cache files, so add a `.gitignore` file to each of the directories. This will ignore all non-hidden files:
echo '[^.]*' > application/{logs,cache}/.gitignore
[!!] Git ignores empty directories, so adding a `.gitignore` file also makes sure that git will track the directory, but not the files within it.
Now we need the `index.php` and `bootstrap.php` files:
wget https://github.com/kohana/kohana/raw/3.3/master/index.php --no-check-certificate
wget https://github.com/kohana/kohana/raw/3.3/master/application/bootstrap.php --no-check-certificate -O application/bootstrap.php
Commit these changes too:
git add application
git commit -m 'Added initial directory structure'
That's all there is to it. You now have an application that is using Git for versioning.
## Adding Submodules
To add a new submodule complete the following steps:
1. run the following code - git submodule add repository path for each new submodule e.g.:
git submodule add git://github.com/shadowhand/sprig.git modules/sprig
2. then init and update the submodules:
git submodule init
git submodule update
## Updating Submodules
At some point you will probably also want to upgrade your submodules. To update all of your submodules to the latest `HEAD` version:
git submodule foreach 'git checkout 3.3/master && git pull origin 3.3/master'
To update a single submodule, for example, `system`:
cd system
git checkout 3.3/master
git pull origin 3.3/master
cd ..
git add system
git commit -m 'Updated system to latest version'
If you want to update a single submodule to a specific commit:
cd modules/database
git pull origin 3.3/master
git checkout fbfdea919028b951c23c3d99d2bc1f5bbeda0c0b
cd ../..
git add database
git commit -m 'Updated database module'
Note that you can also check out the commit at a tagged official release point, for example:
git checkout v3.3.0
Simply run `git tag` without arguments to get a list of all tags.
## Removing Submodules
To remove a submodule that is no longer needed complete the following steps:
1. open .gitmodules and remove the reference to the to submodule
It will look something like this:
[submodule "modules/auth"]
path = modules/auth
url = git://github.com/kohana/auth.git
2. open .git/config and remove the reference to the to submodule\\
[submodule "modules/auth"]
url = git://github.com/kohana/auth.git
3. run git rm --cached path/to/submodule, e.g.
git rm --cached modules/auth
**Note:** Do not put a trailing slash at the end of path. If you put a trailing slash at the end of the command, it will fail.
## Updating Remote Repository URL
During the development of a project, the source of a submodule may change for any reason (you've created your own fork, the server URL changed, the repository name or path changed, etc...) and you'll have to update those changes. To do so, you'll need to perform the following steps:
1. edit the .gitmodules file, and change the URL for the submodules which changed.
2. in your source tree's root run:
git submodule sync
3. run `git init` to update the project's repository configuration with the new URLs:
git submodule init
And it's done, now you can continue pushing and pulling your submodules with no problems.
Source: http://jtrancas.wordpress.com/2011/02/06/git-submodule-location/

View File

@@ -0,0 +1,106 @@
# Hello, World
Just about every framework ever written has some kind of hello world example included, so it'd be pretty rude of us to break this tradition!
We'll start out by creating a very very basic hello world, and then we'll expand it to follow MVC principles.
## Bare bones
First off we have to make a controller that Kohana can use to handle a request.
Create the file `application/classes/Controller/Hello.php` in your application folder and fill it out like so:
<?php defined('SYSPATH') OR die('No Direct Script Access');
Class Controller_Hello extends Controller
{
public function action_index()
{
echo 'hello, world!';
}
}
Lets see what's going on here:
`<?php defined('SYSPATH') OR die('No Direct Script Access');`
: You should recognize the first tag as an opening php tag (if you don't you should probably [learn php](http://php.net)). What follows is a small check that makes sure that this file is being included by Kohana. It stops people from accessing files directly from the url.
`Class Controller_Hello extends Controller`
: This line declares our controller, each controller class has to be prefixed with `Controller_` and an underscore delimited path to the folder the controller is in (see [Conventions and styles](about.conventions) for more info). Each controller should also extend the base `Controller` class which provides a standard structure for controllers.
`public function action_index()`
: This defines the "index" action of our controller. Kohana will attempt to call this action if the user hasn't specified an action. (See [Routes, URLs and Links](tutorials.urls))
`echo 'hello, world!';`
: And this is the line which outputs the customary phrase!
Now if you open your browser and go to http://localhost/index.php/hello you should see something like:
![Hello, World!](hello_world_1.png "Hello, World!")
## That was good, but we can do better
What we did in the previous section was a good example of how easy it to create an *extremely* basic Kohana app. (In fact it's so basic, that you should never make it again!)
If you've ever heard anything about MVC you'll probably have realised that echoing content out in a controller is strictly against the principles of MVC.
The proper way to code with an MVC framework is to use _views_ to handle the presentation of your application, and allow the controller to do what it does best control the flow of the request!
Lets change our original controller slightly:
<?php defined('SYSPATH') OR die('No Direct Script Access');
Class Controller_Hello extends Controller_Template
{
public $template = 'site';
public function action_index()
{
$this->template->message = 'hello, world!';
}
}
`extends Controller_Template`
: We're now extending the template controller, it makes it more convenient to use views within our controller.
`public $template = 'site';`
: The template controller needs to know what template you want to use. It'll automatically load the view defined in this variable and assign the view object to it.
`$this->template->message = 'hello, world!';`
: `$this->template` is a reference to the view object for our site template. What we're doing here is assigning a variable called "message", with a value of "hello, world!" to the view.
Now lets try running our code...
![Hello, World!](hello_world_2_error.png "Hello, World!")
For some reason Kohana's thrown a wobbly and isn't showing our amazing message.
If we look at the error message we can see that the View library wasn't able to find our site template, probably because we haven't made it yet *doh*!
Let's go and make the view file `application/views/site.php` for our message:
<html>
<head>
<title>We've got a message for you!</title>
<style type="text/css">
body {font-family: Georgia;}
h1 {font-style: italic;}
</style>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p>We just wanted to say it! :)</p>
</body>
</html>
If we refresh the page then we can see the fruits of our labour:
![hello, world! We just wanted to say it!](hello_world_2.png "hello, world! We just wanted to say it!")
## Stage 3 Profit!
In this tutorial you've learnt how to create a controller and use a view to separate your logic from your display.
This is obviously a very basic introduction to working with Kohana and doesn't even scrape the potential you have when developing applications with it.

View File

@@ -0,0 +1,219 @@
# Importing Kohana as a Library
If you're working with an existing codebase it's often difficult to modernise the code as it would mean a complete rewrite and there's rarely the time. An alternative is to improve the codebase incrementally as best you can, gradually outsourcing code to external libraries to reduce the amount of old code there is to maintain.
This tutorial describes how to include the Kohana PHP framework into existing PHP applications, without having to use the routing and HMVC request handling features.
[!!] The code modified in this tutorial was copied from Kohana version 3.1.x. You may need to update it to work with future releases.
In normal usage of the Kohana framework, the `index.php` file acts as the request handler; it sets up the environment, loads the system configuration, and then handles the request (see [Request Flow](flow)).
We'll walk you through the steps required to create a file we'll call `include.php` which will allow you to include Kohana from exiting PHP applications.
## Demo application
The following file will serve as our (insultingly simple) demo application for this tutorial.
### File: `demo.php`
~~~
<?php
$content = 'Hello World';
?>
<html>
<head>
<title>Demo page</title>
</head>
<body>
<?php echo $content; ?>
</body>
</html>
~~~
## Install Kohana
[Download and install the Kohana framework](install); from this point on, we'll be referring to the location of the Kohana libraries as the `kohana` directory.
## Create a common setup file
Since `index.php` and `include.php` will duplicate a lot of code, we're going to move that code to a third file, `common.php`. The bulk of the code is unchanged; we've changed the install check to exit rather than return after rendering, and removed the request execution.
The new file creates the initial request object, rather than fully executing the request, so that, if you do define routes, the `Request::$initial` variable will be set up correctly.
### File: `kohana/common.php`
~~~
<?php
/**
* The directory in which your application specific resources are located.
* The application directory must contain the bootstrap.php file.
*
* @link http://kohanaframework.org/guide/about.install#application
*/
$application = 'application';
/**
* The directory in which your modules are located.
*
* @link http://kohanaframework.org/guide/about.install#modules
*/
$modules = 'modules';
/**
* The directory in which the Kohana resources are located. The system
* directory must contain the classes/kohana.php file.
*
* @link http://kohanaframework.org/guide/about.install#system
*/
$system = 'system';
/**
* The default extension of resource files. If you change this, all resources
* must be renamed to use the new extension.
*
* @link http://kohanaframework.org/guide/about.install#ext
*/
define('EXT', '.php');
/**
* Set the PHP error reporting level. If you set this in php.ini, you remove this.
* @link http://www.php.net/manual/errorfunc.configuration#ini.error-reporting
*
* When developing your application, it is highly recommended to enable notices
* and strict warnings. Enable them by using: E_ALL | E_STRICT
*
* In a production environment, it is safe to ignore notices and strict warnings.
* Disable them by using: E_ALL ^ E_NOTICE
*
* When using a legacy application with PHP >= 5.3, it is recommended to disable
* deprecated notices. Disable with: E_ALL & ~E_DEPRECATED
*/
error_reporting(E_ALL | E_STRICT);
/**
* End of standard configuration! Changing any of the code below should only be
* attempted by those with a working knowledge of Kohana internals.
*
* @link http://kohanaframework.org/guide/using.configuration
*/
// Set the full path to the docroot
define('DOCROOT', realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR);
// Make the application relative to the docroot, for symlink'd index.php
if ( ! is_dir($application) AND is_dir(DOCROOT.$application))
$application = DOCROOT.$application;
// Make the modules relative to the docroot, for symlink'd index.php
if ( ! is_dir($modules) AND is_dir(DOCROOT.$modules))
$modules = DOCROOT.$modules;
// Make the system relative to the docroot, for symlink'd index.php
if ( ! is_dir($system) AND is_dir(DOCROOT.$system))
$system = DOCROOT.$system;
// Define the absolute paths for configured directories
define('APPPATH', realpath($application).DIRECTORY_SEPARATOR);
define('MODPATH', realpath($modules).DIRECTORY_SEPARATOR);
define('SYSPATH', realpath($system).DIRECTORY_SEPARATOR);
// Clean up the configuration vars
unset($application, $modules, $system);
if (file_exists('install'.EXT))
{
// Load the installation check
include 'install'.EXT;
exit; // Changes were made here
}
/**
* Define the start time of the application, used for profiling.
*/
if ( ! defined('KOHANA_START_TIME'))
{
define('KOHANA_START_TIME', microtime(TRUE));
}
/**
* Define the memory usage at the start of the application, used for profiling.
*/
if ( ! defined('KOHANA_START_MEMORY'))
{
define('KOHANA_START_MEMORY', memory_get_usage());
}
// Bootstrap the application
require APPPATH.'bootstrap'.EXT;
/**
* Instantiate the request object. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].
* If no source is specified, the URI will be automatically detected.
*/
Request::factory(); // Changes were made here
~~~
## Alter Kohana's `index.php`
Having moved most of the code from Kohana's `index.php` to `common.php` the new `kohana/index.php` contains only this:
### File: `kohana/index.php`
~~~
<?php
require_once 'common.php';
// Execute the request
Request::$initial->execute()
->execute()
->send_headers(TRUE)
->body();
~~~
## Create the include file
Our `include.php` file is also pretty simple. The try-catch clause is needed because if the request matches no routes Kohana will throw an `HTTP_Exception_404` exception.
### File: `kohana/include.php`
~~~
<?php
try {
require_once 'common.php';
}
catch (HTTP_Exception_404 $e)
{
// The request did not match any routes; ignore the 404 exception.
}
~~~
**NB:** Due to the way Kohana's routing works, if the request matches no routes it will fail to instantiate an object, and `Request::$current` and `Request::$initial` will not be available.
## Integration
Now that we're set up, we can add Kohana into our application using a single include, and then we're good to go.
### File: `demo.php`
~~~
<?php
require_once 'kohana/include.php';
$content = 'Hello World';
$content = HTML::anchor('http://kohanaframework.org/', $content);
?>
<html>
<head>
<title>Demo page</title>
</head>
<body>
<?php echo $content; ?>
<hr />
<?php echo URL::base(); ?>
<hr />
<?php echo Debug::dump(array(1,2,3,4,5)); ?>
</body>
</html>
~~~

View File

@@ -0,0 +1,54 @@
# Sharing Kohana
Kohana follows a [front controller pattern](http://en.wikipedia.org/wiki/Front_Controller_pattern "Front Controller pattern") (which means that all requests are sent to `index.php`) and as such the [filesystem](files) is very configurable. Inside of `index.php` you can change the `$application`, `$modules`, and `$system` paths.
[!!] There is a security check at the top of every Kohana file to prevent it from being accessed without using the front controller. Also, the `.htaccess` file should protect those folders as well. Moving the application, modules, and system directories to a location that cannot be accessed via the web can add another layer of security, but is optional.
The `$application` variable lets you set the directory that contains your application files. By default, this is `application`. The `$modules` variable lets you set the directory that contains module files. The `$system` variable lets you set the directory that contains the default Kohana files. You can move these three directories anywhere.
For instance, by default the directories are set up like this:
www/
index.php
application/
modules/
system/
You could move the directories out of the web root so they look like this:
application/
modules/
system/
www/
index.php
Then you would need to change the settings in `index.php` to be:
$application = '../application';
$modules = '../modules';
$system = '../system';
## Sharing system and modules
To take this a step further, we could point several Kohana apps to the same system and modules folders. For example (and this is just an example, you could arrange these anyway you want):
apps/
foobar/
application/
www/
bazbar/
application/
www/
kohana/
3.0.6/
3.0.7/
3.0.8/
modules/
And you would need to change the settings in `index.php` to be:
$application = '../application';
$system = '../../../kohana/3.0.6';
$modules = '../../../kohana/modules';
With this method each app can point to a central copy of Kohana, and when you add a new version, allow you to quickly update the apps by editing their respective `index.php` files.

View File

@@ -0,0 +1 @@
Simple example of controller model and view working together.

View File

@@ -0,0 +1,7 @@
Making a template driven site.
<http://kerkness.ca/wiki/doku.php?id=template-site:create_the_template>
<http://kerkness.ca/wiki/doku.php?id=template-site:extending_the_template_controller>
<http://kerkness.ca/wiki/doku.php?id=template-site:basic_page_controller>

View File

@@ -0,0 +1,5 @@
<http://kerkness.ca/wiki/doku.php?id=routing:static_pages>
<http://kerkness.ca/wiki/doku.php?id=routing:multi-language_with_a_route>