I'm Dan Previte, a web developer and a geek in general living in Chicago and working for Caxy Inc.

Sample CodeIgniter Blog Controller


I never get comments, or requests, so this is for Peter.

Here's a sample controller for CodeIgniter. This is pretty much the structure and it doesn't do much. When you go to yoursite.com/blog, anything in the index function will run.

If you added a function called edit, and went to yoursite.com/blog/edit, then that would run.

All this controller does is load the links from the links table, get the page content for the current page ID, and then passes that to the views. In your views folder you would have 2 files, sidebar.php and content.php. Those would be your template files.

$links would be a variable available in the sidebar view that just contains the result of the database query from _load_links().

<?php
  /**
   * Blog Class Controller
   *
   * @package Null-Logic
   **/

  class Blog extends Controller {

    /**
     * Default Blog Class Function
     *
     * @return void
     **/

    function index() {
      $this->display();
    }

    function display($page_ID = 0) {
      $this->load->view('content', array(
        'sidebar' => $this->load->view('sidebar', array(
          'links' => $this->_load_links()
        ), true),
        'content' => $this->_load_content($page)
      ));
    }

    /**
     * Get the links for the sidebar
     **/

    function _load_links() {
      $query = $this->db->get('links');
      return $query->result();
    }

    /**
     * Get the content for this page
     **/

    function _load_content($page) {
      $query = $this->db->get_where('pages', array(
        'ID' = $page
      ));
      return $query->row();
    }

  }
?>

And then the view for the sidebar can be anything, like:


<div id="sidebar">
<ul class="links">
  <?php
    foreach($links as $link) {
      echo '
<li><a href="'
. $link->href . '">' . $link->text . '</a>';
    }
  ?> <!-- Fixed missing closing PHP tag. Thanks Jay! -->
</ul>
 

One Response to “Sample CodeIgniter Blog Controller”

  1. very txs for ur reaply man, iam apreciate a lot this, iam working in the code now, i was reading the documentation too, i will show u my advance :)

    txs again!

    Peter

Leave a Reply