Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Saving magazines using active records

From: Up and Running with PHP CodeIgniter

Video: Saving magazines using active records

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.

Saving magazines using active records

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.

Show transcript

This video is part of

Image for Up and Running with PHP CodeIgniter
Up and Running with PHP CodeIgniter

23 video lessons · 5040 viewers

Jon Peck
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Up and Running with PHP CodeIgniter.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.