Logged in as

Auto_Modeler Documentation

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

Setup

In order to use Auto_Modeler with your models, you need to first place the library in your application/libraries directory. Then you need to add the following to your model you wish to use it with:

class Blog_Model extends Auto_Modeler {
    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.

Magic get()

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

title?>

content?>

Magic set()

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

$blog_entry = new Blog_Model();
$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());

valid()

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. See the In Model Validation section below for details.

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.

save()

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

delete()

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

$blog_entry->delete();

fetch_all($orderby, $direction)

This method retrieves all the rows in the table. You can optionally set the ORDER BY and direction of the sorting.

$all_blogs = $blog_entry->fetch_all();

fetch_where($where, $orderby, $direction, $type)

This method retrieves rows in the table based on your where condition. You can optionally set the ORDER BY and direction of the sorting.

$all_blogs = $blog_entry->fetch_where(array('date <=' => strtotime('yesterday'));

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

select_list($key, $display, $order_by, $where)

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 an $order and $where clause to pass to filter for different data.

All my Blogs!

select_list('id', 'title'))?>

has_attribute($key)

Tells you if the model has an attribute named $key. Returns TRUE/FALSE.

Column Aliasing

Auto Modeler supports column aliasing. To do this, simply add an $aliases variable to your class. The key is the alias, and the value is the real table name in your database.

protected $aliases = array('foobar' => 'user');

ArrayAccess

You can also access your model fields via the ArrayAccess interface. This will respect your aliases and relationships.

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'),
                           '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:

public function add()
{
        $client = new Client_Model();

                $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($this->input->post());

                try
                {
                        $client->save();
                        url::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.

Additional Validation Methods

As you can see, the above method will only validate fields that belong to the model you are validating. If you need to make sure other fields in your form are valid (for example, making sure a file upload is valid), you can pass these in as parameters of the save() method.

$asset->valid(
        array('country' => $this->input->post('country', array()), 'category' => $this->input->post('category', array())), // Additional data to validate with the form
        array('check_country', 'check_category', 'validate_file_upload')); // Model callbacks to run
);

In this example, we are checking to ensure that a country is checked, a category is checked, and verifying a file was uploaded. Here is the model:

 '',
                            'title'    => '',
                            'description'    => '');

    protected $has_many = array('files', 'countries');
    protected $belongs_to = array('categories');

    protected $rules = array('title' => array('required'),
                             'description' => array('required'));

    protected function check_country(Validation &$validation)
    {
        $validation->add_rules('country', 'required');
    }

    protected function check_category(Validation &$validation)
    {
        $validation->add_rules('category', 'required');
    }

    protected function validate_file_upload(Validation &$validation)
    {
        if (isset($_FILES) AND $_FILES['file']['error'])
            $validation->add_error('file', 'no_file');
        else if (count($this->db->getwhere('files', array('filename' => $_FILES['file']['name']))))
            $validation->add_error('file', 'duplicate_filename');
    }
}

The variables you pass in to the first parameter of save() will be added to the validation library to be checked, and the second parameter are the additional form-specific rules you want to run, which are located in the model.

Also available in: HTML TXT