Sunday, April 13, 2014

An MVC example in PHP CodeIgniter



URLs in CodeIgniter: example.com/class/function/ID

    The first segment represents the controller class that should be invoked.
    The second segment represents the class function, or method, that should be called.
    The third, and any additional segments, represent the ID and any variables that will be passed to the controller.

.htaccess should be modified as:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]


An MVC example in PHP CodeIgniter
Visit the your site using a URL similar to this: example.com/index.php/blog/
1) Controller:
application/controllers/blog.php

<?php
class Blog extends CI_Controller {

public function index()
{

    $this->load->model('blogmodel');

    $data['query'] = $this->blogmodel->get_last_ten_entries();

    $this->load->view('blogview', $data); }
}
?>


Note: Class names must start with an uppercase letter.
2) View
application/views/blogview.php

<html>
<head>
<title>My Blog</title>
</head>
<body>
    <h1>Welcome to my Blog!</h1>

   Last ten entries:

 <?php echo $query; ?>

</body>
</html>

3) Model
application/models/blogmodel.php

class Blogmodel extends CI_Model {

    var $title   = '';
    var $content = '';
    var $date    = '';

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
   
    function get_last_ten_entries()
    {
        $query = $this->db->get('entries', 10);
        return $query->result();
    }

    function insert_entry()
    {
        $this->title   = $_POST['title']; // please read the below note
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->insert('entries', $this);
    }

    function update_entry()
    {
        $this->title   = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->update('entries', $this, array('id' => $_POST['id']));
    }

}

Note: Class names must start with an uppercase letter.
Reference:

PHP CodeIgniter tutorial

No comments:

Post a Comment