In order to build a complete web page with the views that you saw in the previous section, it’s necessary to define a controller class that first stores the strings returned from each of them, and then passes this content to the layout view. If this sounds a bit confusing to you, the following web page controller should help to clarify any issues that you might have. Here it is: <?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 header section $data['header']=$this->load->view('header_view',array('header'=>'Header Section'),TRUE); // generate content section $data['content']=$this->load->view('content_view',array('users'=>$this->db->get('users')),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); } } ?> Do you see how simple it is to generate a dynamic web page by returning strings with the “$this->load->view()” method? I guess you do. In the above example, each of the sections that make up the page are stored temporally on the $data array, and then it’s passed to the “main_page” view for displaying purposes. Hopefully, this code sample should give you a clear idea of how to return contents from a view after they've been loaded, via the third “TRUE” argument as shown before. And finally, assuming that all of this has been set up correctly, if you type the following URL into your browser: http://localhost/codeigniter/index.php/webpage Then you should get the following output:
Here you have it. At this point, you've learned how to use the “$this->load->view()” method in a slightly different way to generate a simple database-driven web application with CodeIgniter. All of the examples developed in this tutorial can be enhanced. For example, you might want to create a users model and utilize it within the controller to fetch database rows, instead of using the database class directly. Whatever you decide to do, one thing is certain: CodeIgniter will keep you entertained for hours! Final thoughts In this fourth part of this series, I explained how to build a simple, yet dynamic, web page by returning strings from some views. As was illustrated earlier, this approach permits us to generate partial sections of a web document in a pretty intuitive and flexible fashion, and I’m sure that you’ll find even more useful ways to use it. In the following article, I’ll be discussing how to make views even more "dumb" (if the term is actually applicable) by removing certain presentation logic from them. If you wish to learn how this will be done, don’t miss the upcoming tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|