Subversion hosting, CVS hosting, Trac hosting, Bugzilla hosting and software collaboration Providing hosted Subversion, CVS, Trac and Bugzilla repositories
 

March 7, 2008

Basic Views In CodeIgniter

Filed under: Software Development — Tags: , , , , — Greg Larkin @ 3:24 pm

Hi everyone,

A while back, I hooked up my CodeIgniter sample application to a MySQL database. That was easy, and now I’ll show how to move your presentation code into separate view files, instead of echo’ing HTML from inside a controller file.

According to the CodeIgniter manual, views are stored in the /views (hmm, that makes sense!) directory of your application, and they can be divided up across functional areas with subdirectories. Since it’s possible to create page snippets and load them in sequence, you might have a directory structure like this:

/views
  /global
    /layout
      /header.php
      /footer.php
  /navigation
      /left_side.php
      /bottom_links.php
  /user
    /add.php
    /edit.php
    /delete.php
    ...
  /group
    /add.php
    /edit.php
    /delete.php
    ...
  /...
  /...

Then when you want to render a particular page, say the “add user” page of your web app’s administrative interface, the code would look like this:

$this->load->view(‘global/layout/header.php’);
$this->load->view(‘global/navigation/left_side.php’);
$this->load->view(‘user/add.php’);
$this->load->view(‘global/navigation/bottom_links.php’);
$this->load->view(‘global/layout/footer.php’);

I haven’t gotten that complex yet, but I did move the code to display my user count into a view and set the value in the controller like so:

function count_users()
{
        $numUsers = $this->user->count_users();
        $data = array(‘num_users’ => $numUsers);
        $this->load->view(‘user/showcount’, $data);
}

The file /views/user/showcount.php is pretty simple:

<html>
<head><title>Welcome to the User Area!</title></head>
<body>
This page is rendered by the file: <?php echo __FILE__; ?>
<p>There are <?php echo $num_users; ?> users defined in the database.
<p><?php echo anchor(‘user’, ‘Go back’); ?>
</body>
</html>

Ok, this all seems to be pretty easy. Of course, there’s a bunch more functionality in the CodeIgniter framework, but I think what I’ll do for my next post is shift gears and go through the same basic exercises using CakePHP, Prado, and the Zend Framework.

It will be interesting to see if there’s any similarity to the way the classic “Hello, world.” program varies in complexity based on implementation language!

Bookmark and Share

Keep in touch,
Greg
SourceHosting.net, LLC


No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.


Call me - Greg Larkin: error

Powered by WordPress