|
Auto_Modeler
Auto_Modeler Documentation
Auto_Modeler DocumentationAuto_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. SetupIn 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 ReferenceAuto_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. <h1><?=$blog_entry->title?></h1>
<p><?=$blog_entry->content?></p>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()); 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; // 6delete()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. <h1>All my Blogs!</h1>
<?=html::dropdown('blog_id', $blog_entry->select_list('id', 'title'))?>has_attribute($key)Tells you if the model has an attribute named $key. Returns TRUE/FALSE. In-Model ValidationAuto_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 MethodsAs 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->save(
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', 'check_file') // 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: <?php
class Asset_Model extends Auto_Modeler_ORM {
// Database table name
protected $table_name = 'assets';
// Database fields and default values
protected $data = array('id' => '',
'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 check_file(Validation &$validation)
{
$validation->add_callbacks('file', array($this, 'validate_file_upload'));
}
public function validate_file_upload(Validation &$validation, $input)
{
if (isset($_FILES) AND $_FILES[$input]['error'])
$validation->add_error($input, 'no_file');
else if (count($this->db->getwhere('files', array('filename' => $_FILES[$input]['name']))))
$validation->add_error($input, '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. |
Sign in to add a comment