Skip to content
Jeremy Bush edited this page Jan 10, 2011 · 8 revisions

Auto_Modeler is an extension to your models that enables rapid application development at a small cost. It enables you to easily create, edit, delete and retrieve database records.

Setup

In order to use Auto_Modeler with your models, copy the module to your MODPATH, and add it in your bootstrap.php file. Then you need to add the following to your model you wish to use it with:

<?php

class Model_Blog extends AutoModeler {
  protected $_table_name = 'blogs';

  protected $_data = array('id' => '', 'title' => '', 'content' => '');
}

The $data variable is an associative array containing the table column names and default values for the blogs table in this case.

API Reference

Auto_Modeler gives you the following methods to use on your models:

construct($id)

The constructor enables you to either create an empty object when no parameter is passed as $id, or it fetches a row when the parameter is passed.

$blog_entry = new Blog_Model(5); // Get the row from the blogs table with id=5

factory($model, $id)

The factory method returns a model instance of the model name provided. You can also specify an id to create a specific object. Works similar to ORM::factory(). Using this, you can chain methods off models that shouldn't be instantiated.

load(Database_Query_Builder_Select $query = NULL, $limit = 1)

The load method takes a query builder object, and loads a model or resultset of models with it. Use this method for loading where you need more advanced criteria than the object id. If you want all results, pass NULL as the $limit parameter.

__get()

This enables you to retrieve the items from the $data array.

<h1><?=$blog_entry->title?></h1>
<p><?=$blog_entry->content?></p>

__set()

This enables you to set the items in the $data array.

    $blog_entry = new Model_Blog;
    $blog_entry->title = 'Demo';
    $blog_entry->content = 'My awesome content';

set_fields($array)

This method allows for bulk setting of $data variables. If you have an entire array of data you want to pass to the model (for instance, from a submitted form), you can use this method to reduce TLOC.

    $blog_entry->set_fields($this->input->post());

is_valid($validation = NULL)

The valid method will perform the validation on your model. You can use this before you save to ensure the model is valid. save() will call this method internally.

You can pass an existing validation object into this method.

Returns either TRUE on success, or an array that contains a html version of the errors and the raw errors array from the validation object.

See the In Model Validation section below for details.

save($validation = NULL)

This method saves the model to your database. If $data['id'] is empty, it will do a database INSERT and assign the inserted row id to $data['id']. If $data['id'] is not empty, it will do a database UPDATE.

    $blog_entry->save();
    echo $blog_entry->id; // 6

If the validation fails, this method will throw an Auto_Modeler_Exception. You can echo it to get the html version of the errors, or use the errors property to get the raw errors array returned by validation.

errors($lang = NULL)

The errors method behaves the same as the validation object's errors() method. Use it to retrieve an array of validation errors from the current object.

delete()

This method deletes the current object and it's associated database row.

   $blog_entry->delete();

You can set $type to 'or' to do an OR WHERE query.

select_list($key, $display, Database_Query_Builder_Select $query = NULL)

This method returns an associative array, where the keys of the array is set to $key column of each row, and the value is set to the $display column. You can optionally specify the $query parameter to pass to filter for different data.

<h1>All my Blogs!</h1>
<?=html::dropdown('blog_id', $blog_entry->select_list('id', 'title'))?>
<h1>Only users with username = foobar</h1>
<?=html::dropdown('blog_id', AutoModeler::factory('testuser')->select_list('id', 'username', db::select()->where('username', '=', 'foobar')))?>

ArrayAccess

You can also access your model fields via the ArrayAccess interface: $user['username']

In-Model Validation

Auto_Modeler supports in-model validation. You can defines your field rules in your model, and upon save(), the library will run validation for you on the entered fields. The process to do this is as follows:

Create a $_rules array in your model. They key is the field name, and the value is an array of rules.

    $_rules = array('name' => array('required', 'alpha_dash', 'min_length' => array('2')),
                   'address' => array('required'));

Now, when you save() your model, it will check the "name" and "address" fields with the rules provided. If validation fails, the library will throw an exception containing the failed error messages. You can use a try/catch block to detect failing validation:

<?php
    public function add()
    {
        $client = new Model_Client();

               $this->template->body = new View('admin/client/form');
               $this->template->body->errors = '';
               $this->template->body->client = $client;
               $this->template->body->title = 'Add';

        if ( $_POST) // Save the data
        {
            $client->set_fields(array_intersect_key(array('name', 'address'), $_POST));

            try
            {
                $client->save();
                $this->request->redirect('client/view/'.$client->short_name);
            }
            catch (Kohana_User_Exception $e)
            {
                $this->template->body->client = $client;
                $this->template->body->errors = $e;
            }
        }
    }

In your view, you can simply echo the $errors variable to get a nice list of errors. You can also use $e->errors to get a raw array, for example if you want to display your errors inline with your fields.

Passing pre-built validations

For more advanced validations, such as password verifications that don't directly belong to the model, you can pass a pre-built validation object to save() and validate() and it will combine the validation objects. Below is an example:

<?php

class Controller_Test extends Controller
{
	public function index()
	{
		$user = new Model_User;
		
		$_POST = array('username' => 'foobar',
		               'password' => 'testing',
		               'repeat_password' => 'tsting');

		$validation = new Validation($_POST);
		$validation->add_rules('password', 'matches[repeat_password]');
		try
		{
			$user->set_fields($_POST);
			$user->save($validation);
		}
		catch (Auto_Modeler_Exception $e)
		{
			echo $e;
			echo Kohana::debug($e->errors);
			die(Kohana::debug($e));
		}

		die(Kohana::debug($user));
	}
}

If you run this, you will get an error about the passwords not matching. You can take the example from here to create advanced validation schemes for your models.