Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
One of the convenient and time saving features of CodeIgniter is a loose implementation of the active record design pattern. When I use CodeIgniter's active records, I don't need to create classes to connect to each database table, but I should create a model for each database table. And I can use active records to make the models perform database operations. This system is database agnostic, meaning all the query syntax is generated automatically. I can access CodeIgniter's database using $this->db followed by commands such as insert Update and delete. Rather than explicitly breaking down each command, I will demonstrate by example, by updating the models to allow them to be persistent.
I am also going to extend the bare minimum of native CodeIgniter model class to be more functional by adding generic CRUD functionality to it. This approach will also demonstrate how to extend the CodeIgniter functionality. If I wanted to generically extend a CodeIgniter class, a specific naming convention is required. Instead of ci_, use my_. I'll switch to NetBeans and navigate to the Core folder. I'm going to extend the CI model class, so, I'll create a new file named, my_model.php.
Class, my_model extends CI_model. Now, your initial reaction may be to make this class abstract. I'll be honest, that's what I wanted to do first. But CodeIgniter instantiates these classes and abstract classes can't be instantiated. Therefore, it'll just have generic functionality that won't work until it's extended. I'll start by adding a constant containing the name of the database table that'll store records of a given model. This is very helpful for organization and documentation as well. I have to set a value, so, I'll just make it abstract, and just override it. I will define a second constant containing the primary key for the table, const DB_TABLE_PK equals abstract.
Next, I am to going to create the four CRUD methods. I will start with create, which will be an insert method. I will make it private as I'm going to have a more unifying save method that will determine whether to call insert or update. That's in documentation, create record. I'm going to use this DB to access active record, then the method insert, which takes two arguments. The name of the table then questioned as a string.
And then object containing the arguments that mapped to table columns that will be written, which will just be this. The insert operation will not manually populate anything, so, I will have to manually populate the model with the insert ID. Fortunately there's a method for that. This curly brace this DB_TABLE_PK equals this db, and then the method, insert_id. That's all that' needed. And let's do a more complex one, which is the update method, which I'll also make private, so, I can call it from the unified save method. Private function update.
Then give a documentation, update record. This -> db -> update, takes three arguments: the name of the table to update, which will be this db table, and an array or object containing the columns or values to update, which will just be this. And the primary key of the table that will be updated. This DB_TABLE_ PK, I'll use the constants defined earlier to make a generic. To prepare for a loading method, I'm going to make a helper that will populate the model from an array or standard class. Which will take one argument, a mixed row.
So, public function populate. And I'll take a row. So, populate from an array or standard class, param mixed row. And then for each row as key value, this dollar sign key equals value. Next, I'll implement a method for loading a single record from the database into a model that takes one argument. I'll call it public function load, which'll take one argument, the ID of the record.
(NOISE) Load from the database. Param will be an integer containing the primary key. In this method, I will assign a variable called query to the result of this -> db -> get_where, which retrieves a standard object with a result. It takes two arguments, which is the table name again, DB_TABLE followed by an array of the key value pairs that it will be matched against. Which in this case will be just the primary key and the ID I want to look up. This DB_TABLE_PK, assign to ID.
I'll use the previously created populate method to populate the object. So, this -> populate with query -> row. The final method of CRUD is delete: public function delete. Delete the current record, this -> db -> delete. The delete method takes the name of the table, this DB_TABLE followed by an array similar to the where statement I used in load.
This time, I'll specify the argument containing the primary key using the constant. This DB_TABLE_PK, this, this DB_TABLE_PK. Finally, I'll unset this primary key once the deletion operation has occurred, as the record won't exist anymore. Now that I have the full CRUD functionality to find, let's make a public method for saving that will decide whether to insert or update, public function save.
Save the record. If is set this primary key, use the update method, this -> update. Otherwise, it's an insert. The final piece of common funtionality that I'll impliment is an unfilter get which will retrieve all records from the models database table. I'll include optional support for a limit and off-set, which will be useful if I ever implement impugnation. I'll start with documentation.
Get an array of models with an optional limit, offset. Param, int, limit, which will be optional. Param, int, offset: optional, like if it's set, requires limit. Return an array of models populated by database, keyed by the primary key. Then, public function get, will limit defaulting to 0 and an offset also defaulting to 0.
So, if there is a limit, I'm going to assign query to this -> db -> get. Which takes the name of the table, this -> DB_TABLE, and an optional limit and offset. Limit offset. So, if there is no limit query equals this db -> get, and then just this DB_TABLE, which will return all rows.
Now that the query's been performed, let's build the return value. I'll start with an empty array. Alright val equals array. Then, get the class of the current model, get_class of this. I can iterate over the query using the method result, which will return database rows, for each query -> result as row. Create a new instance of the current class. So, model equals new class. Populated with a helper function, so, model -> populate with row. Then, added to the return value using the primary key. Ret_val, row, and then this DB_TABLE_PK equals model. The primary key is a nice shortcut if you don't want to use the constant or try to remember what the key name is.
Finally, return the ret_val, save the file. This seems like a lot of work, and in someways it is. However, it also highlights how to extend native CodeIgniter classes, and it will save me from writing returning code in returning my models. Let's give the models' four CRUD functionality, open the publication model. Instead of CI model, we'll extend my model instead. Then I'll add the constants containing the table name, Const DB_TABLE equals publications.
And the primary key, const DB_TABLE_PK equals publication_id, save then open the issue model. Again, I'll extend MY_MODEL const DB_TABLE equals issues, and const DB_TABLE_PK equals issue id. Save again. At this point the models have now four CRUD functionality using CodeIgniter's active records.
Let's test it out. Open the magazine controller and navigate to the index method. CodeIgniter requires that models be loaded before they can be used by using load. I'll demonstrate two ways of working with methods. One by using this and the other by instantiation. I'll start by creating the publication. So, this -> load -> model, which has just one argument, the name of the model, which will be Publication. When a model is loaded, the model is made available through this using the class name as the property name. I'm going to set the publication name using, this. So, this -> publication -> publication_name equals Sandy shore. That's all I need to create the record.
So, I will save it. This -> publication -> save. Let's see the result by dumping the model. Echo tt pre, var_export, this -> publication, True. Now close the pre and the tt. After I've created the publication, I'll create a new issue. Same as before, I'll use load to get the model. This -> load -> model, the model's name is Issue.
However, this time I'll instantiate a new issue model and assign it to a variable. If I didn't use this load, the class would not be found. Issue equals new Issue. I'll set the publication id from the publication model. Issue -> publication_id equals this -> publication -> publication_id. I'm going to set the issue number to two. Issue -> issue_number equals 2. And I'll set the date of the publication using PHP's date for February 1st, 2013. Issue -> issue_date_publication equals date, 2013-02-01. CodeIgniter is going to handle the conversion of MySQL's date format, which is time saving.
When I'm done, I'll save the issue; issue -> save, and then debug the result. I'm just going to copy and paste that from above, and var_export issue, TRUE. Save the controller, then return to the browser and refresh. I can see two models. The first containing publication id number one named sandy shore, and then issue id number one with publication id number one, an issue number set as two, and the date publication.
Note that the issue cover which I didn't set, is still null. We'll set the cover later in the course. This way of looking at magazine back issues works, technically I guess, but is this really nice to look at? Instead of dumping the result, let's format it cleanly.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 101058 Viewers
61 Video lessons · 87839 Viewers
71 Video lessons · 71720 Viewers
56 Video lessons · 103597 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.