It is sure nice to have a framework handle all the logic in your web application, but without dynamic content loading, your web application will be seen as lacking and not modern. We don’t want to give the upper hand to the competitors by a mistake of implementation do we?
Today, i will write a long tutorial on how to serve content and have it updated via ajax. This article will be in three parts:
1 – Creating the table and writing the model
2 – Implementing CodeIgniter REST Server and use it to serve data
3 – Write the AJAX handlers in the UI Part
We will first start with creating the table and the model. We will name our objects “animals” as an example. In your own web application though, you will have at least 3-4 tables, different models, and you’ll operate on multiple models in your controllers.
Now let’s remember the MVC pattern: “Database logic in the models, Controlling logic (switching types, loading data to variables, echoing, calculations) in the controllers, and the presentation logic (HTML, JS) in the views). Point it out in the comments if i break this rule in my tutorials (though doubtful i ever will).
So, let’s create our table:
CREATE TABLE animals (animal_id INT PRIMARY KEY AUTO_INCREMENT, animal_name VARCHAR(128) NOT NULL, animal_owner VARCHAR(128) NOT NULL, animal_sex VARCHAR(1) NOT NULL, animal_birth_date DATETIME);
Explanation: the animal id is the primary key for our tables (primary keys are used for database relations AND differentiating different rows with similar data), animal name is pretty obvious to me, animal_owner is the name of our owner, the sex, being a single character (either M for male or F for female).
The birth date, we will insert it by the database via the PHP date() function, but we will deal with that later.
Now, it is the time to write our model. In your CodeIgniter installation, create the following file under:
application/model/
A file with the name and extension:
animal_model.php
Now open that up and write the following code in there:
class Animal_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } protected $tbl_name = "animals"; public function create_animal($animal_birth_date) { $this->db->set('animal_name',$this->input->post('animal_name')); $this->db->set('animal_owner',$this->input->post('animal_owner')); $this->db->set('animal_sex',$this->input->post('animal_sex')); $this->db->set('animal_birth_date',$animal_birth_date); $this->db->insert($this->tbl_name); } public function get_all_animals() { $query = $this->db->get($this->tbl_name); if($query->num_rows() > 0) { return $query->result_array(); } } public function get_animal_by_id($animal_id) { $query = $this->db->get_where($this->tbl_name , array('animal_id' => $animal_id)); if($query->num_rows() > 0) { return $query->result_array(); } } public function update_animal_by_id() { $this->db->set('animal_name',$this->input->post('animal_name')); $this->db->set('animal_owner',$this->input->post('animal_owner')); $this->db->set('animal_sex',$this->input->post('animal_sex')); $this->db->set('animal_birth_date',$animal_birth_date); $this->db->where('animal_id',$this->input->post('animal_id')); $this->db->update($this->tbl_name); } public function delete_animal_by_id() { $this->db->delete($this->tbl_name,array('animal_id' => $this->input->post('animal_id'))); } }
Note: I omit the PHP tags because stupid WordPress doesn’t accept them, so you will have to do that yourself. Every Web Application’s Model object should have the following methods:
- A method to create objects, via POST
- A method to get objects, both the whole collection, and a single one (like i did by id)
- A method to update objects, by the id (because Title is an unreliable option for finding the right object)
- Finally, a method to delete objects by id.
You will see that i used a $tbl_name variable to have the table name there. That will be available to the model’s method via the $this reserved keyword and it’s extending classes (albeit no class ever extends an user-written CodeIgniter model).
You will also see that i have called the parent constructor, because not doing so will make you lose the parent classes inside definitions (such as variables or methods) when extending it’s constructor.
I am also calling the $this-> load ->database ( ) method to load the database by the config. You can check the official documentation to see which parameters this function receives to do modifications on the database, you can also assign the value returned by it to have multiple connections to your database.
For creation and update logic, i use data directly data from POST because that’s what we will do from the controller for 100% conciseness.
You will also notice that i always return arrays (i hate dealing with objects except in result arrays). The main reason for this is because arrays are much much lighter than objects (see the Zend reference for comparing a size of an array to a size of an object in memory allocation) plus it is much prettier and easier to stick other arrays to an array. We don’t deal with instances etc. either.
Now before stepping to the second part of this tutorial, i want you to go and read up the Active Records reference (just throw an eye on it fast) to get an idea of what functions you have available to do operations on the database.
You have some options to extend this model, with functions like:
- animal_ set_ sex ()
- animal_set_birthdate()
- animal_get_by_sex()
And you could write thousands of specific functions to get and set animals. Or you could be the smart guy and do:
//Method to set value(s) for row(s) with a named column public function get_animals_by_column($column_name,$column_value) { $query = $this->db->get_where($this->tbl_name,array($column_name,$column_value); ......
And you just provide the column name and the value for that column, instead of having to write thousands of functions for the same kind of retrieval / insert.
We will use this model to dynamically get / set data on the view using AJAX and our Rest Controller. But in the following article our targets will be:
- Setting up the PhilSurgeon CodeIgniter REST Server
- Writing a Rest controller for our animals to do operations on the animals DB
- Load the views for the web application
See you in the next article then!
Comments