Senin, 29 Desember 2014

Pengenalan Code Igniter (Part 02): contoh aplikasi guestbook dengan CI dan database MySQL

Kali ini saya akan coba melanjutkan tutorial pada sebelumnya tentang pengenalan Code Igniter. Kita akan menbuat suatu contoh aplikasi guestbook dengan CI dan database MySQL.

Pertama buat database di MySQL dengan nama "tutorial" kemudian buat tabel  seperti di bawah:

tbl_guestbook :
id: int(4) PRIMARY AUTO INCREMENT
email: varchar (50) NOT NULL
comments: text
cdate: datetime

Sebelum memulai membuat aplikasi guestbook, saya asumsikan anda sudah terlebih dahulu mengerti konsep dasar OOP di PHP, serta arsitektur MVC (model-view-controller di code igniter).

1. buat controller guestbook.php dan simpan dalam direktori application\controllers:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 
 
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Guestbook extends CI_Controller {

 /**
  * Index Page for this controller.
  *
  * Maps to the following URL
  *   http://localhost/my_example/CI/index.php/guestbook
  * - or -  
  *   http://localhost/my_example/CI/index.php/guestbook/index

  * So any other public methods not prefixed with an underscore will
  * map to /index.php/welcome/<method_name>
  * @see http://codeigniter.com/user_guide/general/urls.html
  */
    function __construct() {
        parent::__construct();
        $this->load->model('guestbook_model');
    }

    public function index() {
        $data['guestbook_comments'] = $this->guestbook_model->getComments();
 $this->load->view('guestbook_view', $data);
    }

    public function postComment() {
        $data = array(
            'email' => $this->input->post('txtEmail'),
            'comments' => $this->input->post('txtComments'),
            'cdate' => date('Y-m-d h:i:s')
        );
        $this->guestbook_model->postComment($data);
        redirect('/guestbook/index');
    }
}

/* End of file Guestbook.php */
/* Location: ./application/controllers/Guestbook.php */

Controller Guestbook merupakan class turunan dari CI_Controller. Function __construct akan
dijalankan pada saat browser melakukan request ke controller ini.
baris perintah parent::__construct akan menjalankan function __construct di controller parent
yaitu (CI_Controller) di mana terpadat perintah perintah untuk class loader.

Saat kita melakukan request:  

http://localhost/my_example/CI/index.php/guestbook 

maka controller class Guestbook akan di-instantiate dan function index dijalankan. pada baris perintah:
 
$data['guestbook_comments'] = $this->guestbook_model->getComments();

mem-query ke database untuk data guestbook comment dan simpan ke dalam variable $data. Berikutnya, baris perintah:
 
$this->load->view('guestbook_view', $data);
 
akan load dan render view "guestbook_view" dengan mengirim data yang tersimpan dalam variable array $data.

Function postComment() akan dieksekusi ketika pengunjung melakukan request dengan isi form guestbook dan melakukan submit. Function ini menerima data dari field-field seperti email, comments, cdata kemudian menggunakan model untuk menyimpan data:

$this->guestbook_model->postComment($data);
 
Setelah berhasil menyimpan data posting maka akan redirect ke halaman guestbook/index.

2. Buat file guestbook_model.php dan simpan dalam direktori application/models sebagai berikut:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
 
<?php
/**
 * Created by PhpStorm.
 * User: weirdo
 * Date: 12/29/14
 * Time: 1:42 AM
 */

//namespace application\models;


class Guestbook_model extends CI_Model{
    function __construct() {
        parent::__construct();
    }

    public function getComments() {
        $this->db->order_by('cdate', 'desc');
        return $this->db->get('tbl_guestbook')->result();
    }

    public function postComment($data) {
        return $this->db->insert('tbl_guestbook', $data);
    }
} 
 
 
 

Seperti halnya controller, guestbook_model merupakan class turunan dari class CI_Model di mana dalam function __construct sudah inisialisasi method-method dasar untuk kita lebih mudah melakukan interaksi dengan database.

function getComments() melakukan query ke table "tbl_guestbook" untuk mendapatkan data comments semua pengunjung. function ini diakses oleh controller guestbook/index (perhatian cara penulisan seperti ini artinya controller guestbook -> function index).

function postComment() melakukan penyimpanan data posting comment yang diakses oleh controller guestbook/postComment.

3. Buat file guestbook_view.php untuk menampilkan data posting serta menyediakan form untuk pengunjung dapat isi posting. Simpanlah ke dalam direktori application/views.


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Welcome to CodeIgniter</title>

 <style type="text/css">

 ::selection{ background-color: #E13300; color: white; }
 ::moz-selection{ background-color: #E13300; color: white; }
 ::webkit-selection{ background-color: #E13300; color: white; }

 body {
  background-color: #fff;
  margin: 40px;
  font: 13px/20px normal Helvetica, Arial, sans-serif;
  color: #4F5155;
 }

 a {
  color: #003399;
  background-color: transparent;
  font-weight: normal;
 }

 h1 {
  color: #444;
  background-color: transparent;
  border-bottom: 1px solid #D0D0D0;
  font-size: 19px;
  font-weight: normal;
  margin: 0 0 14px 0;
  padding: 14px 15px 10px 15px;
 }

 code {
  font-family: Consolas, Monaco, Courier New, Courier, monospace;
  font-size: 12px;
  background-color: #f9f9f9;
  border: 1px solid #D0D0D0;
  color: #002166;
  display: block;
  margin: 14px 0 14px 0;
  padding: 12px 10px 12px 10px;
 }

 #body{
  margin: 0 15px 0 15px;
 }
 
 p.footer{
  text-align: right;
  font-size: 11px;
  border-top: 1px solid #D0D0D0;
  line-height: 32px;
  padding: 0 10px 0 10px;
  margin: 20px 0 0 0;
 }
 
 #container{
  margin: 10px;
  border: 1px solid #D0D0D0;
  -webkit-box-shadow: 0 0 8px #D0D0D0;
 }
 </style>
</head>
<body>

<div id="container">
 <h1>MY GUESTBOOK</h1>

 <div id="body">
        <form action="postComment" method="POST" id="guestbook_form">
            <div style="width: 100px; float: left">Email</div><input type="text" name="txtEmail" style="width: 200px;" /> <br/>
            <div style="width: 100px; float: left">Comments</div>
            <textarea name="txtComments" style="width: 200px;"></textarea>
            <br/>
            <div style="width: 100px; float: left">&nbsp;</div>
            <input type="submit" name="submit" value="POST" />
        </form>
        <br/>
        <table>
            <?php
            if(!empty($guestbook_comments)) :
            foreach($guestbook_comments as $idx => $comment) {
            ?>
                <tr>
                    <td><?php echo '<b>' . $comment->email . '</b> - ' . $comment->cdate;?></td>
                </tr>
                <tr>
                    <td><?php echo $comment->comments;?></td>
                </tr>
            <?php
            }
            endif
            ?>
        </table>
    </div>

 <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>

</body>
</html>

Pada bagian selanjutnya kita akan coba membuat aplikasi lebih lengkap, lebih kompleks. kita akan coba menggunakan library, helper, autoload, templating, modular dan fitur-fitur lain dari Code Igniter.

Semoga bermanfaat.

Power by PHP & Code Igniter: bareksa.com

1 komentar: