Since in this case I’m planning to move the “foreach” loop included within the “content_view.php” file out of it, the simplest way to do that is by implementing this part of the application straight into the controller. To demonstrate how to achieve this, below I listed the modified signature of the “WebPage” controller class, which now looks like this: <?php class WebPage extends Controller{ function WebPage(){ // load controller parent parent::Controller(); // load libraries here $this->load->database(); // load helpers here } // generate web page using partial sections function index(){ // generate headers section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); $query=$this->db->get('users'); if($query->num_rows > 0){ // generate content section $data['content']=NULL; foreach($query->result() as $user){ $data['content'].=$this->load->view('users_view',array('user'=>$user),TRUE); } } // generate footer section $data['footer']=$this->load->view('footer_view',array('footer'=>'Footer Section'),TRUE); // generate full web page $this->load->view('main_page',$data); } } ?> As shown above, the logic implemented by the “WebPage” controller practically remains the same, except for a tiny detail: now the “foreach” loop included previously within the “content_view.php” file has been moved within the controller, and in consequence it’s necessary to create a new view that displays the data retrieved from the “users” MySQL table. The signature of this new view file, called ”users_view.php,” looks as simple as this: <p><strong>First Name: </strong><?php echo $user->firstname;?></p> <p><strong>Last Name: </strong><?php echo $user->lastname;?></p> <p><strong>Email: </strong><?php echo $user->email;?></p> <hr /> Here you have it. Now the controller is responsible for looping over the rows fetched from the MySQL table, and the result is stored on the $data[‘content’] array element. Lastly, each section of the web page is embedded into the “main_page.php” view, which finishes rendering the whole web document. Not too hard to understand, right? Having implemented an alternative approach to building a basic MySQL-based web application, now it’s time to put all of its pieces together, since two of its files were modified. Thus, in the last section of this tutorial I’ll be listing for you the full source code of this sample PHP program, so you can copy/paste it and introduce your own improvements. Now, jump forward and read the next few lines. We’re almost finished!
blog comments powered by Disqus |
|
|
|
|
|
|
|