Updated to KH 3.3 and improved

This commit is contained in:
Deon George
2013-04-13 16:17:56 +10:00
parent 6f50463ec7
commit 6f7913d363
1551 changed files with 96188 additions and 29813 deletions

View File

@@ -18,7 +18,7 @@ CREATE TABLE IF NOT EXISTS `roles_users` (
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`email` varchar(127) NOT NULL,
`email` varchar(254) NOT NULL,
`username` varchar(32) NOT NULL DEFAULT '',
`password` varchar(64) NOT NULL,
`logins` int(10) UNSIGNED NOT NULL DEFAULT '0',
@@ -33,12 +33,12 @@ CREATE TABLE IF NOT EXISTS `user_tokens` (
`user_id` int(11) UNSIGNED NOT NULL,
`user_agent` varchar(40) NOT NULL,
`token` varchar(40) NOT NULL,
`type` varchar(100) NOT NULL,
`created` int(10) UNSIGNED NOT NULL,
`expires` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_token` (`token`),
KEY `fk_user_id` (`user_id`)
KEY `fk_user_id` (`user_id`),
KEY `expires` (`expires`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `roles_users`

View File

@@ -16,7 +16,7 @@ CREATE TABLE roles_users
CREATE TABLE users
(
id serial,
email varchar(318) NOT NULL,
email varchar(254) NOT NULL,
username varchar(32) NOT NULL,
"password" varchar(64) NOT NULL,
logins integer NOT NULL DEFAULT 0,

View File

@@ -0,0 +1,3 @@
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Auth_ORM extends Kohana_Auth_ORM { }

View File

@@ -1,10 +1,10 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
* ORM Auth driver.
*
* @package Kohana/Auth
* @author Kohana Team
* @copyright (c) 2007-2011 Kohana Team
* @copyright (c) 2007-2012 Kohana Team
* @license http://kohanaframework.org/license
*/
class Kohana_Auth_ORM extends Auth {
@@ -32,7 +32,7 @@ class Kohana_Auth_ORM extends Auth {
if (is_array($role))
{
// Get all the roles
$roles = ORM::factory('role')
$roles = ORM::factory('Role')
->where('name', 'IN', $role)
->find_all()
->as_array(NULL, 'id');
@@ -46,7 +46,7 @@ class Kohana_Auth_ORM extends Auth {
if ( ! is_object($role))
{
// Load the role
$roles = ORM::factory('role', array('name' => $role));
$roles = ORM::factory('Role', array('name' => $role));
if ( ! $roles->loaded())
return FALSE;
@@ -60,9 +60,9 @@ class Kohana_Auth_ORM extends Auth {
/**
* Logs a user in.
*
* @param string username
* @param string password
* @param boolean enable autologin
* @param string $username
* @param string $password
* @param boolean $remember enable autologin
* @return boolean
*/
protected function _login($user, $password, $remember)
@@ -72,24 +72,30 @@ class Kohana_Auth_ORM extends Auth {
$username = $user;
// Load the user
$user = ORM::factory('user');
$user = ORM::factory('User');
$user->where($user->unique_key($username), '=', $username)->find();
}
if (is_string($password))
{
// Create a hashed password
$password = $this->hash($password);
}
// If the passwords match, perform a login
if ($user->has('roles', ORM::factory('role', array('name' => 'login'))) AND $user->password === $password)
if ($user->has('roles', ORM::factory('Role', array('name' => 'login'))) AND $user->password === $password)
{
if ($remember === TRUE)
{
// Token data
$data = array(
'user_id' => $user->id,
'user_id' => $user->pk(),
'expires' => time() + $this->_config['lifetime'],
'user_agent' => sha1(Request::$user_agent),
);
// Create a new autologin token
$token = ORM::factory('user_token')
$token = ORM::factory('User_Token')
->values($data)
->create();
@@ -110,8 +116,8 @@ class Kohana_Auth_ORM extends Auth {
/**
* Forces a user to be logged in, without specifying a password.
*
* @param mixed username string, or user ORM object
* @param boolean mark the session as forced
* @param mixed $user username string, or user ORM object
* @param boolean $mark_session_as_forced mark the session as forced
* @return boolean
*/
public function force_login($user, $mark_session_as_forced = FALSE)
@@ -121,7 +127,7 @@ class Kohana_Auth_ORM extends Auth {
$username = $user;
// Load the user
$user = ORM::factory('user');
$user = ORM::factory('User');
$user->where($user->unique_key($username), '=', $username)->find();
}
@@ -145,7 +151,7 @@ class Kohana_Auth_ORM extends Auth {
if ($token = Cookie::get('authautologin'))
{
// Load the token and user
$token = ORM::factory('user_token', array('token' => $token));
$token = ORM::factory('User_Token', array('token' => $token));
if ($token->loaded() AND $token->user->loaded())
{
@@ -174,18 +180,20 @@ class Kohana_Auth_ORM extends Auth {
/**
* Gets the currently logged in user from the session (with auto_login check).
* Returns FALSE if no user is currently logged in.
* Returns $default if no user is currently logged in.
*
* @param mixed $default to return in case user isn't logged in
* @return mixed
*/
public function get_user($default = NULL)
{
$user = parent::get_user($default);
if ( ! $user)
if ($user === $default)
{
// check for "remembered" login
$user = $this->auto_login();
if (($user = $this->auto_login()) === FALSE)
return $default;
}
return $user;
@@ -194,8 +202,8 @@ class Kohana_Auth_ORM extends Auth {
/**
* Log a user out and remove any autologin cookies.
*
* @param boolean completely destroy the session
* @param boolean remove all tokens for user
* @param boolean $destroy completely destroy the session
* @param boolean $logout_all remove all tokens for user
* @return boolean
*/
public function logout($destroy = FALSE, $logout_all = FALSE)
@@ -209,11 +217,17 @@ class Kohana_Auth_ORM extends Auth {
Cookie::delete('authautologin');
// Clear the autologin token from the database
$token = ORM::factory('user_token', array('token' => $token));
$token = ORM::factory('User_Token', array('token' => $token));
if ($token->loaded() AND $logout_all)
{
ORM::factory('user_token')->where('user_id', '=', $token->user_id)->delete_all();
// Delete all user tokens. This isn't the most elegant solution but does the job
$tokens = ORM::factory('User_Token')->where('user_id','=',$token->user_id)->find_all();
foreach ($tokens as $_token)
{
$_token->delete();
}
}
elseif ($token->loaded())
{
@@ -227,7 +241,7 @@ class Kohana_Auth_ORM extends Auth {
/**
* Get the stored password for a username.
*
* @param mixed username string, or user ORM object
* @param mixed $user username string, or user ORM object
* @return string
*/
public function password($user)
@@ -237,7 +251,7 @@ class Kohana_Auth_ORM extends Auth {
$username = $user;
// Load the user
$user = ORM::factory('user');
$user = ORM::factory('User');
$user->where($user->unique_key($username), '=', $username)->find();
}
@@ -248,7 +262,7 @@ class Kohana_Auth_ORM extends Auth {
* Complete the login for a user by incrementing the logins and setting
* session data: user_id, username, roles.
*
* @param object user ORM object
* @param object $user user ORM object
* @return void
*/
protected function complete_login($user)
@@ -274,4 +288,4 @@ class Kohana_Auth_ORM extends Auth {
return ($this->hash($password) === $user->password);
}
} // End Auth ORM
} // End Auth ORM

View File

@@ -1,10 +1,10 @@
<?php defined('SYSPATH') or die('No direct script access.');
<?php defined('SYSPATH') OR die('No direct script access.');
/**
* ORM Validation exceptions.
*
* @package Kohana/ORM
* @author Kohana Team
* @copyright (c) 2007-2010 Kohana Team
* @copyright (c) 2007-2012 Kohana Team
* @license http://kohanaframework.org/license
*/
class Kohana_ORM_Validation_Exception extends Kohana_Exception {
@@ -16,27 +16,28 @@ class Kohana_ORM_Validation_Exception extends Kohana_Exception {
protected $_objects = array();
/**
* The _object_name property of the main ORM model this exception was created for
* The alias of the main ORM model this exception was created for
* @var string
*/
protected $_object_name = NULL;
protected $_alias = NULL;
/**
* Constructs a new exception for the specified model
*
* @param string $object_name The _object_name of the model this exception is for
* @param string $alias The alias to use when looking for error messages
* @param Validation $object The Validation object of the model
* @param string $message The error message
* @param array $values The array of values for the error message
* @param integer $code The error code for the exception
* @return void
*/
public function __construct($object_name, Validation $object, $message = 'Failed to validate array', array $values = NULL, $code = 0)
public function __construct($alias, Validation $object, $message = 'Failed to validate array', array $values = NULL, $code = 0, Exception $previous = NULL)
{
$this->_object_name = $object_name;
$this->_alias = $alias;
$this->_objects['_object'] = $object;
$this->_objects['_has_many'] = FALSE;
parent::__construct($message, $values, $code);
parent::__construct($message, $values, $code, $previous);
}
/**
@@ -62,6 +63,9 @@ class Kohana_ORM_Validation_Exception extends Kohana_Exception {
*/
public function add_object($alias, Validation $object, $has_many = FALSE)
{
// We will need this when generating errors
$this->_objects[$alias]['_has_many'] = ($has_many !== FALSE);
if ($has_many === TRUE)
{
// This is most likely a has_many relationship
@@ -84,13 +88,17 @@ class Kohana_ORM_Validation_Exception extends Kohana_Exception {
* Merges an ORM_Validation_Exception object into the current exception
* Useful when you want to combine errors into one array
*
* @param string $alias The relationship alias from the model
* @param ORM_Validation_Exception $object The exception to merge
* @param mixed $has_many The array key to use if this exception can be merged multiple times
* @return ORM_Validation_Exception
*/
public function merge($alias, ORM_Validation_Exception $object, $has_many = FALSE)
public function merge(ORM_Validation_Exception $object, $has_many = FALSE)
{
$alias = $object->alias();
// We will need this when generating errors
$this->_objects[$alias]['_has_many'] = ($has_many !== FALSE);
if ($has_many === TRUE)
{
// This is most likely a has_many relationship
@@ -122,48 +130,46 @@ class Kohana_ORM_Validation_Exception extends Kohana_Exception {
*/
public function errors($directory = NULL, $translate = TRUE)
{
if ($directory !== NULL)
{
// Everything starts at $directory/$object_name
$directory .= '/'.$this->_object_name;
}
return $this->generate_errors($this->_objects, $directory, $translate);
return $this->generate_errors($this->_alias, $this->_objects, $directory, $translate);
}
/**
* Recursive method to fetch all the errors in this exception
*
* @param string $alias Alias to use for messages file
* @param array $array Array of Validation objects to get errors from
* @param string $directory Directory to load error messages from
* @param mixed $translate Translate the message
* @return array
*/
protected function generate_errors(array $array, $directory, $translate)
protected function generate_errors($alias, array $array, $directory, $translate)
{
$errors = array();
foreach ($array as $alias => $object)
foreach ($array as $key => $object)
{
if ($directory === NULL)
{
// Return the raw errors
$file = NULL;
}
else
{
$file = trim($directory.'/'.$alias, '/');
}
if (is_array($object))
{
// Recursively fill the errors array
$errors[$alias] = $this->generate_errors($object, $file, $translate);
$errors[$key] = ($key === '_external')
// Search for errors in $alias/_external.php
? $this->generate_errors($alias.'/'.$key, $object, $directory, $translate)
// Regular models get their own file not nested within $alias
: $this->generate_errors($key, $object, $directory, $translate);
}
else
elseif ($object instanceof Validation)
{
if ($directory === NULL)
{
// Return the raw errors
$file = NULL;
}
else
{
$file = trim($directory.'/'.$alias, '/');
}
// Merge in this array of errors
$errors += $object->errors($directory, $translate);
$errors += $object->errors($file, $translate);
}
}
@@ -179,4 +185,14 @@ class Kohana_ORM_Validation_Exception extends Kohana_Exception {
{
return $this->_objects;
}
/**
* Returns the protected _alias property from this exception
*
* @return string
*/
public function alias()
{
return $this->_alias;
}
} // End Kohana_ORM_Validation_Exception

View File

@@ -1,4 +1,4 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
* Default auth role
*
@@ -10,7 +10,9 @@
class Model_Auth_Role extends ORM {
// Relationships
protected $_has_many = array('users' => array('through' => 'roles_users'));
protected $_has_many = array(
'users' => array('model' => 'User','through' => 'roles_users'),
);
public function rules()
{
@@ -26,4 +28,4 @@ class Model_Auth_Role extends ORM {
);
}
} // End Auth Role Model
} // End Auth Role Model

View File

@@ -1,10 +1,10 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
* Default auth user
*
* @package Kohana/Auth
* @author Kohana Team
* @copyright (c) 2007-2011 Kohana Team
* @copyright (c) 2007-2012 Kohana Team
* @license http://kohanaframework.org/license
*/
class Model_Auth_User extends ORM {
@@ -15,8 +15,8 @@ class Model_Auth_User extends ORM {
* @var array Relationhips
*/
protected $_has_many = array(
'user_tokens' => array('model' => 'user_token'),
'roles' => array('model' => 'role', 'through' => 'roles_users'),
'user_tokens' => array('model' => 'User_Token'),
'roles' => array('model' => 'Role', 'through' => 'roles_users'),
);
/**
@@ -32,20 +32,16 @@ class Model_Auth_User extends ORM {
return array(
'username' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 32)),
array('regex', array(':value', '/^[-\pL\pN_.]++$/uD')),
array(array($this, 'username_available'), array(':validation', ':field')),
array(array($this, 'unique'), array('username', ':value')),
),
'password' => array(
array('not_empty'),
),
'email' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 127)),
array('email'),
array(array($this, 'email_available'), array(':validation', ':field')),
array(array($this, 'unique'), array('email', ':value')),
),
);
}
@@ -99,38 +95,6 @@ class Model_Auth_User extends ORM {
}
}
/**
* Does the reverse of unique_key_exists() by triggering error if username exists.
* Validation callback.
*
* @param Validation Validation object
* @param string Field name
* @return void
*/
public function username_available(Validation $validation, $field)
{
if ($this->unique_key_exists($validation[$field], 'username'))
{
$validation->error($field, 'username_available', array($validation[$field]));
}
}
/**
* Does the reverse of unique_key_exists() by triggering error if email exists.
* Validation callback.
*
* @param Validation Validation object
* @param string Field name
* @return void
*/
public function email_available(Validation $validation, $field)
{
if ($this->unique_key_exists($validation[$field], 'email'))
{
$validation->error($field, 'email_available', array($validation[$field]));
}
}
/**
* Tests if a unique key value exists in the database.
*
@@ -146,7 +110,7 @@ class Model_Auth_User extends ORM {
$field = $this->unique_key($value);
}
return (bool) DB::select(array('COUNT("*")', 'total_count'))
return (bool) DB::select(array(DB::expr('COUNT(*)'), 'total_count'))
->from($this->_table_name)
->where($field, '=', $value)
->where($this->_primary_key, '!=', $this->pk())
@@ -183,7 +147,7 @@ class Model_Auth_User extends ORM {
*
* Example usage:
* ~~~
* $user = ORM::factory('user')->create_user($_POST, array(
* $user = ORM::factory('User')->create_user($_POST, array(
* 'username',
* 'password',
* 'email',
@@ -210,7 +174,7 @@ class Model_Auth_User extends ORM {
*
* Example usage:
* ~~~
* $user = ORM::factory('user')
* $user = ORM::factory('User')
* ->where('username', '=', 'kiall')
* ->find()
* ->update_user($_POST, array(
@@ -237,4 +201,4 @@ class Model_Auth_User extends ORM {
return $this->values($values, $expected)->update($extra_validation);
}
} // End Auth User Model
} // End Auth User Model

View File

@@ -1,16 +1,23 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
* Default auth user toke
*
* @package Kohana/Auth
* @author Kohana Team
* @copyright (c) 2007-2011 Kohana Team
* @copyright (c) 2007-2012 Kohana Team
* @license http://kohanaframework.org/license
*/
class Model_Auth_User_Token extends ORM {
// Relationships
protected $_belongs_to = array('user' => array());
protected $_belongs_to = array(
'user' => array('model' => 'User'),
);
protected $_created_column = array(
'column' => 'created',
'format' => TRUE,
);
/**
* Handles garbage collection and deleting of expired objects.
@@ -62,9 +69,9 @@ class Model_Auth_User_Token extends ORM {
{
$token = sha1(uniqid(Text::random('alnum', 32), TRUE));
}
while(ORM::factory('user_token', array('token' => $token))->loaded());
while (ORM::factory('User_Token', array('token' => $token))->loaded());
return $token;
}
} // End Auth User Token Model
} // End Auth User Token Model

View File

@@ -1,4 +1,4 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Model_Role extends Model_Auth_Role {

View File

@@ -1,4 +1,4 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Model_User extends Model_Auth_User {

View File

@@ -1,4 +1,4 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Model_User_Token extends Model_Auth_User_Token {

View File

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

View File

@@ -1,4 +1,4 @@
<?php defined('SYSPATH') or die('No direct script access.');
<?php defined('SYSPATH') OR die('No direct script access.');
/**
* ORM Validation exceptions.
*

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
<?php defined('SYSPATH') or die('No direct script access.');
<?php defined('SYSPATH') OR die('No direct script access.');
return array(
// Leave this alone
@@ -17,7 +17,7 @@ return array(
'description' => 'Official ORM module, a modeling library for object relational mapping.',
// Copyright message, shown in the footer for this module
'copyright' => '&copy; 20082011 Kohana Team',
'copyright' => '&copy; 20082012 Kohana Team',
)
)
);

View File

@@ -67,7 +67,7 @@ This is a simple example of a single ORM model, that has no relationships, but u
*/
// Create an instance of a model
$members = ORM::factory('member');
$members = ORM::factory('Member');
// Get all members with the first name "Peter" find_all()
// means we get all records matching the query.
@@ -81,7 +81,7 @@ This is a simple example of a single ORM model, that has no relationships, but u
*/
// Create an instance of a model
$member = ORM::factory('member');
$member = ORM::factory('Member');
// Get a member with the user name "bongo" find() means
// we only want the first record matching the query.
@@ -92,7 +92,7 @@ This is a simple example of a single ORM model, that has no relationships, but u
*/
// Create an instance of a model
$member = ORM::factory('member');
$member = ORM::factory('Member');
// Do an INSERT query
$member->username = 'bongo';
@@ -106,7 +106,7 @@ This is a simple example of a single ORM model, that has no relationships, but u
// Create an instance of a model where the
// table field "id" is "1"
$member = ORM::factory('member', 1);
$member = ORM::factory('Member', 1);
// Do an UPDATE query
$member->username = 'bongo';

View File

@@ -44,7 +44,7 @@ This example will create user accounts and demonstrate how to handle model and c
public function username_available($username)
{
// There are simpler ways to do this, but I will use ORM for the sake of the example
return ORM::factory('member', array('username' => $username))->loaded();
return ORM::factory('Member', array('username' => $username))->loaded();
}
public function hash_password($password)
@@ -85,7 +85,7 @@ Please forgive my slightly ugly form. I am trying not to use any modules or unre
if ($_POST)
{
$member = ORM::factory('member')
$member = ORM::factory('Member')
// The ORM::values() method is a shortcut to assign many values at once
->values($_POST, array('username', 'password'));

View File

@@ -1,21 +1,40 @@
# Filters
Filters in ORM work much like they used to when they were part of the Validate class in 3.0.x however they have been modified to match the flexible syntax of [Validation] rules in 3.1.x. Filters run as soon as the field is set in your model and should be used to format the data before it is inserted into the Database.
Filters in ORM work much like they used to when they were part of the Validate class in 3.0.x. However, they have been modified to match the flexible syntax of [Validation] rules in 3.1.x.
Define your filters the same way you define rules, as an array returned by the `ORM::filters()` method like the following:
Filters run as soon as the field is set in your model and should be used to format the data before it is inserted into the Database. Filters are defined the same way you define [rules](validation), as an array returned by the `ORM::filters()` method, like the following:
public function filters()
{
return array(
// Field Filters
// $field_name => array(mixed $callback[, array $params = array(':value')]),
'username' => array(
// PHP Function Callback, default implicit param of ':value'
array('trim'),
),
'password' => array(
array(array($this, 'hash_password')),
// Callback method with object context and params
array(array($this, 'hash_password'), array(':value', Model_User::salt())),
),
'created_on' => array(
// Callback static method with params
array('Format::date', array(':value', 'Y-m-d H:i:s')),
),
'other_field' => array(
// Callback static method with implicit param of ':value'
array('MyClass::static_method'),
// Callback method with object context with implicit param of ':value'
array(array($this, 'change_other_field')),
// PHP function callback with explicit params
array('str_replace', array('luango', 'thomas', ':value'),
// Function as the callback (PHP 5.3+)
array(function($value) {
// Do something to $value and return it.
return some_function($value);
}),
),
);
}

View File

@@ -7,3 +7,4 @@
- [Examples](examples)
- [Simple](examples/simple)
- [Validation](examples/validation)
- [Upgrading](upgrading)

View File

@@ -37,7 +37,7 @@ If you wanted access a post's author by using code like `$post->author` then you
protected $_belongs_to = array(
'author' => array(
'model' => 'user',
'model' => 'User',
),
);
@@ -68,7 +68,7 @@ Let's assume now you want to access the posts using the name `stories` instead,
protected $_has_many = array(
'stories' => array(
'model' => 'post',
'model' => 'Post',
'foreign_key' => 'author_id',
),
);
@@ -79,7 +79,7 @@ A `has_one` relationship is almost identical to a `has_many` relationship. In a
protected $_has_one = array(
'story' => array(
'model' => 'post',
'model' => 'Post',
'foreign_key' => 'author_id',
),
);
@@ -92,7 +92,7 @@ To define the `has_many` "through" relationship, the same syntax for standard ha
protected $_has_many = array(
'categories' => array(
'model' => 'category',
'model' => 'Category',
'through' => 'categories_posts',
),
);
@@ -101,7 +101,7 @@ In the Category model:
protected $_has_many = array(
'posts' => array(
'model' => 'post',
'model' => 'Post',
'through' => 'categories_posts',
),
);

View File

@@ -0,0 +1,16 @@
# Upgrading
## Table aliases
ORM [will now alias the main table](http://dev.kohanaframework.org/issues/4066) in a query to the model's singular object name.
i.e. Prior to 3.2 ORM set the from table like so:
$this->_db_builder->from($this->_table_name);
As of 3.2 it is now aliased like so:
$this->_db_builder->from(array($this->_table_name, $this->_object_name));
If you have a model `Model_Order` then when building a query use the alias like so:
$model->where('order.id', '=', $id);

View File

@@ -4,7 +4,7 @@
To create a new `Model_User` instance, you can do one of two things:
$user = ORM::factory('user');
$user = ORM::factory('User');
// Or
$user = new Model_User();
@@ -12,7 +12,7 @@ To create a new `Model_User` instance, you can do one of two things:
To insert a new record into the database, create a new instance of the model:
$user = ORM::factory('user');
$user = ORM::factory('User');
Then, assign values for each of the properties;
@@ -33,11 +33,11 @@ Insert the new record into the database by running [ORM::save]:
To find an object you can call the [ORM::find] method or pass the id into the ORM constructor:
// Find user with ID 20
$user = ORM::factory('user')
$user = ORM::factory('User')
->where('id', '=', 20)
->find();
// Or
$user = ORM::factory('user', 20);
$user = ORM::factory('User', 20);
## Check that ORM loaded a record
@@ -70,6 +70,25 @@ And if you want to save the changes you just made back to the database, just run
To delete an object, you can call the [ORM::delete] method on a loaded ORM model.
$user = ORM::factory('user', 20);
$user = ORM::factory('User', 20);
$user->delete();
## Mass assignment
To set multiple values at once, use [ORM::values]
try
{
$user = ORM::factory('user')
->values($this->request->post(), array('username','password'))
->create();
}
catch (ORM_Validation_Exception $e)
{
// Handle validation errors ...
}
[!!] Although the second argument is optional, it is *highly recommended* to specify the list of columns you expect to change. Not doing so will leave your code _vulnerable_ in case the attacker adds fields you didn't expect.

View File

@@ -41,7 +41,7 @@ All models automatically validate their own data when `ORM::save()`, `ORM::updat
{
try
{
$user = ORM::factory('user');
$user = ORM::factory('User');
$user->username = 'invalid username';
$user->save();
}
@@ -61,7 +61,7 @@ In the below example, the error messages will be defined in `application/message
{
try
{
$user = ORM::factory('user');
$user = ORM::factory('User');
$user->username = 'invalid username';
$user->save();
}
@@ -79,7 +79,7 @@ Certain forms contain information that should not be validated by the model, but
{
try
{
$user = ORM::factory('user');
$user = ORM::factory('User');
$user->username = $_POST['username'];
$user->password = $_POST['password'];
@@ -108,4 +108,4 @@ Because the validation object was passed as a parameter to the model, any errors
This ensures that errors from multiple validation objects and models will never overwrite each other.
[!!] The power of the [ORM_Validation_Exception] can be leveraged in many different ways to merge errors from related models. Take a look at the list of [Examples](examples) for some great use cases.
[!!] The power of the [ORM_Validation_Exception] can be leveraged in many different ways to merge errors from related models. Take a look at the list of [Examples](examples) for some great use cases.