As I stated in the previous segment, I'm going to implement the first two methods of the "Users" controller to retrieve all of the users stored on the MySQL table, and to insert a new one. That being explained, here's how these methods now look: // list all users public function index() { $data['users'] = AbstractModel::factory('User')->order_by('id')->fetch(); $data['title'] = 'User List'; $data['heading'] = 'List of available users'; $this->load->view('users_view', $data); }
// save a new user public function save() { $user = AbstractModel::factory('User'); $user->firstname = 'Wendy'; $user->lastname = 'Torrance'; $user->email = 'wendy@torrance.com'; if ($user->save()) { redirect ('/users'); } $this->load->view('error_view', array('error' => $user->error)); } As shown above, the "index()" method demonstrates how helpful the chainable methods of the custom model can be. It uses only one line of code to fetch all the users from the corresponding MySQL table. In this case, I decided to call the "factory" method to create an instance of the model, but you may want to directly use its constructor instead. Once the index method has retrieved the data from the MySQL table, it's directly embedded into a new view file called "users_view," for displaying purposes. Later on, I'm going to list the definition of this file, so don't worry about it for the moment. Now, regarding the definition of the "save()" method, it first creates a new user, then assigns to the object the corresponding properties, and finally saves this data to the database table. Also, you may have noticed that, again, I used the "factory()" method to create a new user. Why did I do this, instead of creating the user object only once? I did it only to keep the code of each method uncluttered. But to do things more correctly, an instance of the user model should be created in the constructor and stored as a property of the controller, thus making it accessible to all of its methods. Now that you hopefully understood how the previous methods do their things, it's time to code the remaining ones, which will be tasked with updating and deleting an existing user. This process will be discussed in the last section of this tutorial. So click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|