Added Kohana v3.0.9

This commit is contained in:
Deon George
2011-01-14 01:49:56 +11:00
parent fe11dd5f51
commit b6e9961846
520 changed files with 54728 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
<?php defined('SYSPATH') or die('No direct script access.');
class ORM extends Kohana_ORM {}

View File

@@ -0,0 +1,23 @@
<?php defined('SYSPATH') or die('No direct script access.');
return array(
// Leave this alone
'modules' => array(
// This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename'
'orm' => array(
// Whether this modules userguide pages should be shown
'enabled' => TRUE,
// The name that should show up on the userguide index page
'name' => 'ORM',
// A short description of this module, shown on the index page
'description' => 'Object modeling and relation mapping.',
// Copyright message, shown in the footer for this module
'copyright' => '&copy; 20082010 Kohana Team',
)
)
);

View File

@@ -0,0 +1,8 @@
There will be subpages to this page that have examples. The following is a sample list, don't feel limited by his, or that these are required. Items on the list can be combined, split up, removed or added to.
- Simple one table, one class model. Show CRUD examples.
- Examples of changing things like $_table_name, $_labels, with, etc.
- Example of using validation
- Example of a one to one relationship.
- Example of one to many
- Example of many to many.

View File

@@ -0,0 +1,120 @@
# Simple example
This is a simple example of a single ORM model, that has no relationships, but uses validation on the fields.
## SQL schema
CREATE TABLE IF NOT EXISTS `members` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`firstname` varchar(32) NOT NULL,
`lastname` varchar(32) NOT NULL,
`email` varchar(127) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
## Model
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_Member extends ORM {
protected $_rules = array(
'username' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(32),
'regex' => array('/^[-\pL\pN_.]++$/uD'),
),
'firstname' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(32),
'regex' => array('/^[-\pL\pN_.]++$/uD'),
),
'lastname' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(32),
'regex' => array('/^[-\pL\pN_.]++$/uD'),
),
'email' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(127),
'email' => NULL,
),
);
}
[!!] The `$_rules` array will be passed to a [Validate] object and tested when you call `check()`.
[!!] Please notice that defining the primary key "id" in the model is not necessary. Also the table name in the database is plural and the model name is singular.
## Controller
<?php defined('SYSPATH') or die('No direct access allowed.');
class Controller_Member extends Controller_Template {
public function action_index()
{
// -------------
// - Example 1 -
// -------------
// Create an instance of a model
$member = ORM::factory('member');
// Get all members with the First name "Peter" find_all()
// means we get all records matching the query.
$member->where('firstname', '=', 'Peter')->find_all();
// Count records in the $member object
$member->count_all();
// -------------
// - Example 2 -
// -------------
// Create an instance of a model
$member = ORM::factory('member');
// Get a member with the user name "bongo" find() means
// we only want the first record matching the query.
$member->where('username', '=', 'bongo')->find();
// -------------
// - Example 3 -
// -------------
// Create an instance of a model
$member = ORM::factory('member');
// Do a INSERT query
$member->username = 'bongo';
$member->firstname = 'Peter';
$member->lastname = 'Smith';
$member->save();
// -------------
// - Example 4 -
// -------------
// Create an instance of a model where the
// table field "id" is "1"
$member = ORM::factory('member', 1);
// You can create the instance like below
// If you do not want to use the "id" field
$member = ORM::factory('member')->where('username', '=', 'bongo')->find();
// Do a UPDATE query
$member->username = 'bongo';
$member->firstname = 'Peter';
$member->lastname = 'Smith';
$member->save();
}
}
[!!] $member will be a PHP object where you can access the values from the query e.g. echo $member->firstname

View File

@@ -0,0 +1,22 @@
# ORM
Kohana 3.X includes a powerful Object Relational Mapping (ORM) module that uses the active record pattern and database introspection to determine a model's column information. ORM is integrated tightly with the [Validate] library.
The ORM allows for manipulation and control of data within a database as though it was a PHP object. Once you define the relationships ORM allows you to pull data from your database, manipulate the data in any way you like and then save the result back to the database without the use of SQL. By creating relationships between models that follow convention over configuration, much of the repetition of writing queries to create, read, update and delete information from the database can be reduced or entirely removed. All of the relationships can be handled automatically by the ORM library and you can access related data as standard object properties.
ORM is included with the Kohana 3.X install but needs to be enabled before you can use it. In your `application/bootstrap.php` file modify the call to Kohana::modules and include the ORM modules.
## Getting started
Before we use ORM, we must enable the modules required
Kohana::modules(array(
...
'database' => MODPATH.'database',
'orm' => MODPATH.'orm',
...
));
[!!] The database module is requried for the ORM module to work. Of course the database module has to be configured to use a existing database.
You can now created your [models](models) and [use ORM](using).

View File

@@ -0,0 +1,7 @@
## [ORM]()
- [Creating ORM Models](models)
- [Basic usage](using)
- [Relationships](relationships)
- [Validation](validation)
- [Examples](examples)
- [Simple](examples/simple)

View File

@@ -0,0 +1,36 @@
# Creating your Model
To create a model for the table `member` in your database, create the file `application/classes/model/member.php` with the following syntax:
class Model_Member extends ORM
{
...
}
(this should provide more examples)
## Ignoring Columns
Sometimes you might want to store a property for a model but won't want it to be saved in the database. If you add an column name to the `$_ignored_columns` array then ORM will not save or touch that column. Example:
protected $_ignored_columns = array('password_confirm');
## Overriding the Table name
If you wish to change the database table that a model uses, just override the `$_table_name` variable like this:
protected $_table_name = 'strange_tablename';
## Changing the primary key
ORM assumes each model (and database table) have an `id` column that is indexed and unique. If your primary key column isn't named `id`, that's fine - just override the `$_primary_key` variable like this:
protected $_primary_key = 'strange_pkey';
## Use a non-default database
For each model, you can define which database configuration ORM will run queries on. If you override the `$_db` variable in your model, ORM will connect to that database. Example:
protected $_db = 'alternate';

View File

@@ -0,0 +1,89 @@
# Relationships
Kohana ORM supports four types of object relationships: `belongs_to`, `has_many`, `has_many "through"` and `has_one`. The `has_many "through"` relationship can be used to function like Active Record's `has_many_and_belongs_to` relationship type.
## belongs_to
A `belongs_to` relation should be used when you have one model that belongs to another. For example, a `Child` model belongs_to a `Parent` or a `Flag` model `belongs_to` a `Country`.
This is the base `belongs_to` relationship:
protected $_belongs_to = array('[alias name]' => array('model' => '[model name]', 'foreign_key' => '[column]'));
You can omit any or all of the keys/values in the array on the right, in which case defaults are used:
protected $_belongs_to = array('[alias name]' => array());
The **alias name** is what is used to access the related model in your code. If you had a `Post` model that belonged to a `User` model and wished to use the default values of the `belongs_to` configuration then your code would look like this:
protected $_belongs_to = array('user' => array());
To access the user model, you would use `$post->user`. Since we're using the defaults above, the alias name will be used for the model name, and the foreign key in the posts table will be the alias name followed by `_id`, in this case it would be `user_id`. (You can change the `_id` suffix by modifying the `$foreign_key_suffix` variable in the model.)
Let's say your `Post` database table schema doesn't have a `user_id` column but instead has an `author_id` column which is a foreign key for a record in the `User` table. You could use code like this:
protected $_belongs_to = array('user' => array('foreign_key' => 'author_id'));
If you wanted access a post's author by using code like `$post->author` then you would simply need to change the alias and add the `model` index:
protected $_belongs_to = array('author' => array('model' => 'user', 'foreign_key' => 'author_id'));
## has_many
The standard `has_many` relationship will likely fall on the other side of a `belongs_to` relationship. In the above examples, a post belongs to a user. From the user's perspective, a user has many posts. A has_many relationship is defined below:
protected $_has_many = array('[alias name]' => array('model' => '[model name]', 'foreign_key' => '[column]'));
Again, you can omit all keys in the right array to use the defaults:
protected $_has_many = array('[alias name]' => array());
For our user and post example, this would look like the following in the user model:
protected $_has_many = array('posts' => array());
Using the above, the posts could be access using `$user->posts->find_all()`. Notice the `find_all()` used in this example. With `belongs_to` and `has_one` relationship types, the model is already loaded with necessary data. For `has_many` relationships, however, you may want to limit the number of results or add additional conditions to the SQL query; you can do so prior to the `find_all()`.
The model name used by default will be the singular name of the alias using the `inflector` class. In this case, `posts` uses `post` as the model name. The foreign key used by default is the owner model's name followed by `_id`. In this case, the foreign key will be `user_id` and it must exist in the posts table as before.
Let's assume now you want to access the posts using the name `stories` instead, and are still using the `author_id` key as in the `belongs_to` example. You would define your has_many relationship as:
protected $_has_many = array('stories' => array('model' => 'post', 'foreign_key' => 'author_id'));
## has_one
A `has_one` relationship almost identical to a `has_many` relationship. In a `has_one` relationship, there can be 1 and only 1 relationship (rather than 1 or more in a has_many). If a user can only have one post or story, rather than many then the code would look like this:
protected $_has_one = array('story' => array('model' => 'post', 'foreign_key' => 'author_id'));
## has_many "through"
A `has_many "through"` relationship is used for many-to-many relationships. For instance, let's assume now we have an additional model, called `Category`. Posts may belong to more than one category, and each category may have more than one post. To link them together, an additional model (and table) is needed with columns for a `post_id` and a `category_id` (sometimes called a pivot table). We'll name the model for this `Post_Category` and the corresponding table `post_categories`.
To define the `has_many` "through" relationship, the same syntax for standard has_many relationships is used with the addition of a 'through' parameter. Let's assume we're working with the Post model:
protected $_has_many = array('categories' => array('model' => 'category', 'through' => 'post_category'));
In the Category model:
protected $_has_many = array('posts' => array('model' => 'post', 'through' => 'post_category'));
In the Post_Category model:
protected $_belongs_to = array('post' => array(), 'category' => array());
Defaults were used in the `belongs_to` relationships above, but you could override these if you wish to use aliasing, etc. To access the categories and posts, you simply use `$post->categories->find_all()` and `$category->posts->find_all()`
Methods are available to check for, add, and remove relationships for many-to-many relationships. Let's assume you have a $post model loaded, and a $category model loaded as well. You can check to see if the $post is related to this $category with the following call:
$post->has('category', $category);
The first parameter is the alias name to use (in case your post model has more than one relationship to the category model - although this will be rare) and the second is the model to check for a relationship with.
Assuming you want to add the relationship (by creating a new record in the post_categories table), you would simply do:
$post->add('category', $category);
To remove:
$post->remove('category', $category);

View File

@@ -0,0 +1,78 @@
# Basic Usage
## Load a new model instance
To create a new `Model_User` instance you can do two things:
$user = ORM::factory('user');
// or
$user = new Model_User();
## Inserting
To insert a new record into the database, create a new instance of the model:
$user = ORM::factory('user');
Then, assign values for each of the properties;
$user->first_name = 'Trent';
$user->last_name = 'Reznor';
$user->city = 'Mercer';
$user->state = 'PA';
Insert the new record into the database by running [ORM::save]:
$user->save();
[ORM::save] checks to see if a value is set for the primary key (`id` by default). If the primary key is set, then ORM will execute an `UPDATE` otherwise it will execute an `INSERT`.
## Finding a object
To find an object you can call the [ORM::find] function or pass the id into the ORM constructor:
//find user with ID 20
$user = ORM::factory('user');
$user->find(20);
// or
$user = ORM::factory('user', 20);
## Check that ORM loaded a record
Use the [ORM::loaded] function to check that ORM successfully loaded a record.
if ($user->loaded())
{
//load was successful
}
else
{
//error
}
## Updating and Saving
Once an ORM model has been loaded, you can modify a model's properties like this:
$user->first_name = "Trent";
$user->last_name = "Reznor";
And if you want to save the changes you just made back to the database, just run a `save()` call like this:
$user->save();
## Deleting
To delete an object, you can call the [ORM::delete] function on a loaded ORM model, or pass an id to the delete function of a unloaded model.
$user = ORM::factory('user')->find(20);
$user->delete();
or
ORM::factory('user')->delete(20);