Instalasi CodeIgniter + MVC

15 Mar

Code Igniter (CI) adalah salah satu dari webframework yang bisa digunakan dalam mengembangkan sebuah aplikasi web. CI menerapkan konsep MVC, dan cukup mudah dipelajari, sehingga banyak developer yang memanfaatkan framework ini. Dengan mencoba fitur dan library yang ada, saya yakin seorang programmer php / web developer akan sudah menguasai tool ini dalam kurang dari 24 jam belajar.


  1. Download
  2. Copykan ke Folder aplikasi


  1. Ubah Folder khusus CI. Folder khususnya adalah:
    1. System, misal di ubah menjadi r_system
    2. Application, misalnya di ubah menjadi r_application
  2. Buka file index.php
  3. Cari variabel:
    1. $system_folder , ubah isinya menjadi r_system
    2. $application_folder, ubah isinya menjadi r_application
  4. Metode lain, folder system dan application di letakkan di atas folder root / web root, sehingga tidak bisa di akses melalui http / browser.

Database Configuration

  • The config file is located at application/config/database.php.
$db[‘default’][‘hostname’] = “localhost”;
$db[‘default’][‘username’] = “root”;
$db[‘default’][‘password’] = “”;
$db[‘default’][‘database’] = “database_name”;
$db[‘default’][‘dbdriver’] = “mysql”;
$db[‘default’][‘dbprefix’] = “”;
$db[‘default’][‘pconnect’] = TRUE;
$db[‘default’][‘db_debug’] = FALSE;
$db[‘default’][‘cache_on’] = FALSE;
$db[‘default’][‘cachedir’] = “”;
$db[‘default’][‘char_set’] = “utf8”;
$db[‘default’][‘dbcollat’] = “utf8_general_ci”;
$db[‘default’][‘swap_pre’] = “”;
$db[‘default’][‘autoinit’] = TRUE;
$db[‘default’][‘stricton’] = FALSE;


CodeIgniter is based on the Model-View-Controller development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

  • The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
    • Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.
  • The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.
  • The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

CodeIgniter has a fairly loose approach to MVC since Models are not required. If you don’t need the added separation, or find that maintaining models requires more complexity than you want, you can ignore them and build your application minimally using Controllers and Views. CodeIgniter also enables you to incorporate your own existing scripts, or even develop core libraries for the system, enabling you to work in a way that makes the most sense to you.

Application Flowchart

The following graphic illustrates how data flows throughout the system:

  1. The index.php serves as the front controller, initializing the base resources needed to run CodeIgniter.
  2. The Router examines the HTTP request to determine what should be done with it.
  3. If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.
  4. Security. Before the application controller is loaded, the HTTP request and any user submitted data is filtered for security.
  5. The Controller loads the model, core libraries, helpers, and any other resources needed to process the specific request.
  6. The finalized View is rendered then sent to the web browser to be seen. If caching is enabled, the view is cached first so that on subsequent requests it can be served.

CodeIgniter URLs

The segments in the URL, in following with the Model-View-Controller approach, usually represent:

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

Controller – Contoh halaman static dengan Controller

File ini di letakkan di folder controller. Nama file hars sama dengan nama class yang akan dibuat.

File ini dipanggil dengan cara : index.php/[nama controller]/[nama methode]/[argumen]

  1. Buat di application/controllers/pages.php
  2. Isi nya

class pages extends CI_Controller {

public function view($page = ‘home’)


Echo “hi there”;



  1. Buka :

Contoh lain:


class pages extends CI_Controller


public function view($page = ‘home’)


echo “memanggil halaman $page”;




Dipanggil dengan :

  • Methode default yang dipanggil adalah : index, jadi jika methode tidak disebutkan, yang akan di jalankan adalah’index’
  • The controller is what will become the center of every request to your web application.
  • In very technical CodeIgniter discussions, it may be referred to as the super object


  • Disimpan di folder application/views
  • Contoh, kita akan membuat template halaman, yang terdiri dari header, dan footer
  • application/views/templates/header.php, isi


<title><?php echo $title ?> – CodeIgniter 2 Tutorial</title>



<h1>CodeIgniter 2 Tutorial</h1>

  • application/views/templates/footer.php
<strong>&copy; 2011</strong>



  • Controller Logic
public function view($page = ‘home’)


    if ( ! file_exists(‘application/views/pages/’.$page.’.php’))


        // Whoops, we don’t have a page for that!



    $data[‘title’] = ucfirst($page); // Capitalize the first letter

    $this->load->view(‘templates/header’, $data);

    $this->load->view(‘pages/’.$page, $data);

    $this->load->view(‘templates/footer’, $data);


  • Di application/views/pagess/contoh.php

echo “ini halaman contoh <br>”;


  • The controller is now functioning! Point your browser to [your-site-url]index.php/pages/view to see your page. When you visit index.php/pages/view/about you’ll see the about page, again including the header and footer.

Dynamic Content – Model

  • Instead of writing database operations right in the controller, queries should be placed in a model, so they can easily be reused later.
  • Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.
  • Tabel contoh :
    id int(11) NOT NULL AUTO_INCREMENT, 
    title varchar(128) NOT NULL, 
    slug varchar(128) NOT NULL, 
    text text NOT NULL, 
    PRIMARY KEY (id), 
    KEY slug (slug) 
  • Buat file : application/models/news_model.php

class news_model extends CI_Model {

public function __construct()




public function get_news($slug = FALSE)


if ($slug === FALSE)


$query = $this->db->get(‘news’);

return $query->result_array();

$query = $this->db->get_where(‘news’, array(‘slug’ => $slug));

return $query->row_array();




Menampilkan News

  • Buat file di application/controllers/news.php

class news extends CI_Controller {

public function __construct()





    public function index() 
    $data['news'] = $this->news_model->get_news(); 
    $data['title'] = 'News archive'; 
    $this->load->view('templates/header', $data); 
    $this->load->view('news/index', $data); 
    public function view($slug) 
        $data['news'] = $this->news_model->get_news($slug); 



  • You now need to create a view to render the news items. Create application/views/news/index.php
<?php foreach ($news as $news_item): ?>

<h2><?php echo $news_item[‘title’] ?></h2>

<div id=”main”>

<?php echo $news_item[‘text’] ?>


<p><a href=”news/<?php echo $news_item[‘slug’] ?>”>View article</a></p>

<?php endforeach ?>

  • add some code to the controller and create a new view
public function view($slug) 
    $data['news_item'] = $this->news_model->get_news($slug); 
    if (empty($data['news_item'])) 
    $data['title'] = $data['news_item']['title']; 
    $this->load->view('templates/header', $data); 
    $this->load->view('news/view', $data); 
  • The only things left to do is create the corresponding view at application/views/news/view.php
echo '<h2>'.$news_item['title'].'</h2>'; 
echo $news_item['text']; 

Create Form

  • To input data into the database you need to create a form where you can input the information to be stored. This means you’ll be needing a form with two fields, one for the title and one for the text. You’ll derive the slug from our title in the model.
  • Create the new view at application/views/news/create.php
<h2>Create a news item</h2>

<?php echo validation_errors(); ?>

<?php echo form_open(‘news/create’) ?>

<label for=”title”>Title</label>

<input type=”input” name=”title” /><br />

<label for=”text”>Text</label>

<textarea name=”text”></textarea><br />

<input type=”submit” name=”submit” value=”Create news item” />


  • form_open() function, is provided by the form helper and renders the form element and adds extra functionality, like adding a hidden CSFR prevention field.
  • validation_errors() function, is used to report errors related to form validation.
  • news controller
public function create() 
    $data['title'] = 'Create a news item'; 
    $this->form_validation->set_rules('title', 'Title', 'required'); 
    $this->form_validation->set_rules('text', 'text', 'required'); 
    if ($this->form_validation->run() === FALSE) 
        $this->load->view('templates/header', $data);     
  • you can see a condition that checks whether the form validation ran successfully. If it did not, the form is displayed, if it was submitted and passed all the rules, the model is called. After this, a view is loaded to display a success message.
  • Create a view at application/view/news/success.php
  • Open up the model created earlier and add the following
public function set_news() 
    $slug = url_title($this->input->post('title'), 'dash', TRUE); 
    $data = array( 
        'title' => $this->input->post('title'), 
        'slug' => $slug, 
        'text' => $this->input->post('text') 
    return $this->db->insert('news', $data); 
  • The third line contains a new function, url_title(). This function – provided by the URL helper – strips down the string you pass it, replacing all spaces by dashes (-) and makes sure everything is in lowercase characters. This leaves you with a nice slug, perfect for creating URIs.

Controller dengan tidak memakai konsep MVC

public function lihat()



$query = $this->db->query(‘select * from news’);
if ($query->num_rows() > 0)


foreach ($query->result() as $row)


echo $row->title.” *** “.$row->slug.” *** HH *** “.$row->text.”<br>”;




PHP Dasar

Koneksi ke Tabel


$cnn = mysql_connect(“localhost”,”root”,”dvo”) or die(“Could not connect to db”);

if ($cnn) mysql_select_db(“arsip01”);


$sql = “select id_bagian, nm_bagian from bagian order by id_bagian”;

$hasil = mysql_query($sql) or die(“SQL error- $sql”);

if ($hasil==false) exit;

$no1 = 1;

while ($row=mysql_fetch_row($hasil))


Echo $row[0].”-“. $row[1];


Melakukan input data ke tabel

$sql = “query”

$hasil = mysql_query($sql) or die(“”);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: