Transcript
Page 1: Mvc With Codeigniter

MVC withCodeigniter PHP Framework

Page 2: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 2

MVC( Model – View – Controller )

Page 3: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 3

Software Design PatternSoftware Design PatternSoftware Design PatternSoftware Design Pattern● Masalah dalam develop software:

● Algoritma mana yang akan digunakan?● Design mana yang cocok untuk digunakan?● Teknik apa yang harus diterapkan?● Modul apa saja yang dapat ditambahkan?

● Tiap masalah dalam develop software adalah unik, karena itu solusinya harus lebih unik.

● Bagaimana menerapkan solusi yang tepat pada masalah yang sedang dihadapi?

● Design Pattern merupakan solusi umum dalam menghadapi masalah yang sering timbul pada pengembangan aplikasi.

Page 4: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 4

MVC – MVC – Model View ControllerModel View ControllerMVC – MVC – Model View ControllerModel View Controller

● Metode pendekatan pembuatan aplikasi dengan memisahkan aplikasi menjadi 3 segmen:● Model● View● Controller

● Struktur aplikasi lebih diutamakan dalam penggunaan kembali code program (reuse).

Page 5: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 5

MVC – MVC – Model View ControllerModel View Controller (cont.)(cont.)MVC – MVC – Model View ControllerModel View Controller (cont.)(cont.)

Page 6: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 6

MVC – MVC – ModelModelMVC – MVC – ModelModel

● Merupakan representasi tipe data yang akan digunakan oleh aplikasi.● contoh:

– model database– model RSS Feeds– API Calls

● Pertimbangan aspek:● Desain database.● Query & Store Procedure.● Object Class.● Data Access Layer.● Mediasi antara Controller dan View.

Page 7: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 7

MVC – MVC – ViewViewMVC – MVC – ViewView

● Informasi yang akan ditampilkan kepada pengguna melalui browser.

● Dapat berupa file HTML, generated PHP to HTML (template engine).

● Pertimbangan aspek:● Reporting.● Forms.● Validation.● AJAX.● Graphic & Styling.● UI testing.● Mediasi antara Controller dan Model.

Page 8: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 8

MVC – MVC – ControllerControllerMVC – MVC – ControllerController

● Business logic dari aplikasi yang menjadi jembatan antara Model dan View.

● Me-respon terhadap HTTP Request dan menghasilkan halaman web yang diminta oleh pengguna.

● Pertimbangan aspek:● Validasi data.● Menggunakan database layer.● Algoritma.● Mediasi antara View dan Model.

Page 9: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 9

How MVC can HELP ?How MVC can HELP ?How MVC can HELP ?How MVC can HELP ?

Page 10: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 10

Framework

Page 11: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 11

Framework – Framework – memudahkan kompleksitasmemudahkan kompleksitasFramework – Framework – memudahkan kompleksitasmemudahkan kompleksitas

● Menyediakan fungsi – fungsi umum.● Digunakan untuk aplikasi yang lebih spesifik.● Alur dikontrol oleh framework.● Fokus pada pengembangan aplikasi.

Page 12: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 12

Mengapa menggunakan Framework?Mengapa menggunakan Framework?Mengapa menggunakan Framework?Mengapa menggunakan Framework?● Aplikasi berbasis web semakin kompleks →

tambah sulit untuk maintenance.● tambah menu A, menu B, transaksi C, dll

● Membantu dalam menerapkan konsep MVC.● pemisahan antara model, view dan controller

terlihat jelas.● Menyediakan mediasi antar muka 3 layer MVC.

● tidak perlu kuatir dalam melakukan integrasi antara presentation ke business layer dan ke data access layer.

Page 13: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 13

Harapan dari adanya FrameworkHarapan dari adanya FrameworkHarapan dari adanya FrameworkHarapan dari adanya Framework● Mudah digunakan.● Fasilitasi performa aplikasi.● Menjamin keamanan.● Memisahkan HTML dan PHP.● Mendukung AJAX.● Tidak ada batasan penggunaan

istilah.● Mendukung API.● Meningkatkan kualitas code.● Melatih best practices.

● Kemampuan untuk dikonfigurasi

● Mendukung internationalisasi (multi-language).

● Ketersediaan dokumentasi.

● Komunitas aktif.

● Dukungan terhadap produk yang komersial.

● Lisensi yang ramah.

● Ketersediaan dengan web hosting.

Page 14: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 14

PHP FrameworkPHP FrameworkPHP FrameworkPHP Framework● CakePHP

● http://www.cakephp.org● Codeigniter

● http://www.codeigniter.com● Zend Framework

● http://framework.zend.com● DOOPHP

● http://www.doophp.com

40+ PHP Framework Available!

Page 15: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 15

Framework – Framework – KISSKISSFramework – Framework – KISSKISS

● KISS (Keep it Short and Simple)● Mencapai KISS:

● Hindari istilah “Not Invented Here”.– gunakan kembali resource yang sudah ada.

● Inovasi.– inovasi tidak harus selalu hal yang baru; improvisasi dari

yang sudah ada.● Terbuka terhadap perubahan.● Simplicity is a mindset.

– coding disiplin, penggunaan tools, penggunaan library, penggunaan framework harus simple.→

Page 16: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 16

Codeigniter 2( PHP Framework )

Page 17: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 17

Codeigniter – Codeigniter – PHP FrameworkPHP FrameworkCodeigniter – Codeigniter – PHP FrameworkPHP Framework

● Membantu dalam pembuatan web based PHP application.

● Selesai lebih cepat.● Menyediakan library yang sering dibutuhkan.● Struktur logika lebih simple.● Dapat lebih fokus pada pengerjaan aplikasi.● Minimalisir penggunaan code pada hanya yang

dibutuhkan saja.

Page 18: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 18

Codeigniter FeatureCodeigniter FeatureCodeigniter FeatureCodeigniter Feature● Free (lisensi Apache/BSD).● Ringan.● Cepat.● Menggunakan konsep MVC.● Human Readable URL.● Dukungan library dalam pembuatan aplikasi.● Mudah dalam pembuatan library, class.● Tidak membutuhkan Template Engine.● Dokumentasi lengkap.● Adanya Komunitas.

Page 19: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 19

Codeigniter Application Flow ChartCodeigniter Application Flow ChartCodeigniter Application Flow ChartCodeigniter Application Flow Chart

Page 20: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 20

CI ControllerCI ControllerCI ControllerCI Controller● Huruf pertama nama class harus huruf besar.● Extends -kan CI_Controller.● Simpan pada:

● application/controllers● Akses URL:

● http://localhost/index.php/nama_controller

<?php

class Blog extends CI_Controller

{

}

?>

Page 21: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 21

CI Controller – CI Controller – FunctionsFunctionsCI Controller – CI Controller – FunctionsFunctions

● Segmen: setelah nama controller● http://localhost/index.php/nama_controller/nama_fungsi

● Default loaded function index()→● http://localhost/index.php/nama_controller/index

<?php

class Blog extends CI_Controller

{

public function index()

{

echo 'Hello World!';

}

public function comments()

{

echo 'Look at this!';

}

}

?>

Page 22: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 22

CI Controller – CI Controller – Functions ParameterFunctions ParameterCI Controller – CI Controller – Functions ParameterFunctions Parameter

● Function dengan parameter diakses melalui segment selanjutnya setelah nama fungsi:● http://localhost/index.php/products/shoes/sandals/123

<?php

class Products extends CI_Controller {

public function shoes($types, $id)

{

echo $types;

echo $id;

}

}

?>

Page 23: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 23

CI Controller – CI Controller – Private FunctionsPrivate FunctionsCI Controller – CI Controller – Private FunctionsPrivate Functions

● Function tidak dapat diakses melalui URL.● Gunakan underscore ( _ ) pada nama functions.<?php

class Blog extends CI_Controller

{

public function comments()

{

$this->_utility();

}

private function _utility()

{

echo 'This is utility';

}

}

?>

Page 24: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 24

CI Controller – CI Controller – ConstructorsConstructorsCI Controller – CI Controller – ConstructorsConstructors

● Menjalankan default algoritma.● Tidak mengembalikan value.

<?php

class Blog extends CI_Controller {

public function __construct()

{

parent::__construct();

// Your own constructor code

}

}

?>

Page 25: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 25

CI Controller – CI Controller – Full SkeletonFull SkeletonCI Controller – CI Controller – Full SkeletonFull Skeleton<?php

class Blog extends CI_Controller

{

public function __construct()

{

parent::__construct();

// Your own constructor code

}

public function index()

{

echo 'Hello World!';

}

public function comments()

{

$this->_utility();

}

private function _utility()

{

echo 'This is utility';

}

}

?>

Page 26: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 26

CI ViewsCI ViewsCI ViewsCI Views● Desain website (HTML, CSS, jQuery, etc)● Regular .php files● Simpan pada:

● application/views

<html>

<head>

<title>My Blog</title>

</head>

<body>

<h1>Welcome to my Blog!</h1>

</body>

</html>

Page 27: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 27

CI Views – CI Views – Loading ViewLoading ViewCI Views – CI Views – Loading ViewLoading View

● Controller melakukan load View● $this->load->view('view_file_name');

<?php

class Blog extends CI_Controller {

function index()

{

$this->load->view('blogview');

}

}

?>

Page 28: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 28

CI Views – CI Views – Dynamic DataDynamic DataCI Views – CI Views – Dynamic DataDynamic Data

● Controller melakukan load View dengan parameter data yang akan ditampilkan pada view● $this->load->view('view_file_name', $variable);

<?php

class Blog extends CI_Controller {

function index()

{

$data['title'] = "My Real Title";

$data['heading'] = "My Real Heading";

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

}

}

?>

<html>

<head>

<title><?php echo $title;?></title>

</head>

<body>

<h1><?php echo $heading;?></h1>

</body>

</html>

Page 29: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 29

CI ModelCI ModelCI ModelCI Model● Huruf pertama nama class harus huruf besar.● Nama file harus huruf kecil.● Extends -kan CI_Model.● Simpan pada:

● application/models

class Model_name extends CI_Model {

function __construct()

{

parent::__construct();

}

}

Page 30: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 30

CI Model – CI Model – Loading ModelLoading ModelCI Model – CI Model – Loading ModelLoading Model

● Controller memanggil Model● $this->load->model('model_file_name');

<?php

class Blog_controller extends CI_Controller {

function blog()

{

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

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

$this->load->view('blog', $data);

}

}

?>

Page 31: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 31

CI Form HelperCI Form HelperCI Form HelperCI Form Helper● Load helper:

● $this->load->helper('form');● Form helper functions:

● form_open()● form_open_multipart()● form_hidden()● form_input()● form_password()● form_upload()● form_textarea()● form_dropdown()● form_multiselect()● form_checkbox()

● form_radio()● form_submit()● form_reset()● form_button()● form_close()

● set_value()● set_select()● set_checkbox()● set_radio()

Page 32: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 32

CI Form Helper – CI Form Helper – form_open()form_open()CI Form Helper – CI Form Helper – form_open()form_open()

echo form_open('email/send');

<form method="post" accept-charset="utf-8"

action="http://example.com/index.php/email/send" />

● Attribute$attributes = array('class' => 'email', 'id' => 'myform');

echo form_open('email/send', $attributes);

<form method="post" accept-charset="utf-8"

action="http:/example.com/index.php/email/send"

class="email" id="myform" />

Page 33: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 33

CI Input ClassCI Input ClassCI Input ClassCI Input Class● Tujuan:

● Melakukan pre-processes global input data untuk meningkatkan keamanan.

● Menyediakan fungsi untuk menangani input data.● Security Filtering:

● Menghilangkan predefined variable GET ($_GET).● Menghilangkan global variables.● Filter predefined variable POST/COOKIE.● Mendukung XSS (Cross-site Scripting Hacks).● Standarisasi newline menjadi \n

Page 34: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 34

CI Input Class – CI Input Class – functionsfunctionsCI Input Class – CI Input Class – functionsfunctions

● $this->input->post();● $this->input->cookie();● $this->input->server();

if ( ! isset($_POST['something']))

{

$something = FALSE;

}

else

{

$something = $_POST['something'];

}

$something = $this->input->post('something');

Page 35: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 35

CI ValidationCI ValidationCI ValidationCI Validation● Load library

● $this->load->library('form_validation');● Setup Rules● Check the Validation

● $this->form_validation->run();● Show Errors

● Set error delimiters– $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

● show individual error– echo form_error('field name', '<div class="error">', '</div>');

Page 36: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 36

CI Validation – CI Validation – Setup RulesSetup RulesCI Validation – CI Validation – Setup RulesSetup Rules<input type='text' name='txt_judul' size='60' maxlength='200' />

$rules = array

(

array

(

'field' => 'txt_judul'

, 'label' => 'Judul'

, 'rules' => 'trim|required'

)

);

$this->form_validation->set_rules($rules);

Page 37: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 37

CI Validation – CI Validation – Setup RulesSetup Rules (cont.)(cont.)CI Validation – CI Validation – Setup RulesSetup Rules (cont.)(cont.)

● Rules ReferenceRules Description

required Returns FALSE if the form element is empty.

matches Returns FALSE if the form element does not match the one in the parameter.

min_length Returns FALSE if the form element is shorter then the parameter value.

max_length Returns FALSE if the form element is longer then the parameter value.

exact_length Returns FALSE if the form element is not exactly the parameter value.

greater_than Returns FALSE if the form element is less than the parameter value or not numeric.

less_than Returns FALSE if the form element is greater than the parameter value or not numeric.

alpha Returns FALSE if the form element contains anything other than alphabetical characters.

Rules Description

required Returns FALSE if the form element is empty.

matches Returns FALSE if the form element does not match the one in the parameter.

min_length Returns FALSE if the form element is shorter then the parameter value.

max_length Returns FALSE if the form element is longer then the parameter value.

exact_length Returns FALSE if the form element is not exactly the parameter value.

greater_than Returns FALSE if the form element is less than the parameter value or not numeric.

less_than Returns FALSE if the form element is greater than the parameter value or not numeric.

alpha Returns FALSE if the form element contains anything other than alphabetical characters.

Rules Description

alpha_numeric Returns FALSE if the form element contains anything other than alpha-numeric characters.

alpha_dash Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.

numeric Returns FALSE if the form element contains anything other than numeric characters.

integer Returns FALSE if the form element contains anything other than an integer.

decimal Returns FALSE if the form element is not exactly the parameter value.

is_natural Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.

is_natural_no_zero Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.

Rules Description

alpha_numeric Returns FALSE if the form element contains anything other than alpha-numeric characters.

alpha_dash Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.

numeric Returns FALSE if the form element contains anything other than numeric characters.

integer Returns FALSE if the form element contains anything other than an integer.

decimal Returns FALSE if the form element is not exactly the parameter value.

is_natural Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.

is_natural_no_zero Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.

Page 38: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 38

CI Validation – CI Validation – Setup RulesSetup Rules (cont.)(cont.)CI Validation – CI Validation – Setup RulesSetup Rules (cont.)(cont.)

● Rules Reference

Rules Description

valid_email Returns FALSE if the form element does not contain a valid email address.

valid_emails Returns FALSE if any value provided in a comma separated list is not a valid email.

valid_ip Returns FALSE if the supplied IP is not valid.

valid_base64 Returns FALSE if the supplied string contains anything other than valid Base64 characters.

Rules Description

valid_email Returns FALSE if the form element does not contain a valid email address.

valid_emails Returns FALSE if any value provided in a comma separated list is not a valid email.

valid_ip Returns FALSE if the supplied IP is not valid.

valid_base64 Returns FALSE if the supplied string contains anything other than valid Base64 characters.

Page 39: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 39

CI DatabaseCI DatabaseCI DatabaseCI Database● Load Database Class

● $this->load->database();● Running Query

● $this->db->query('your_sql_query_here');● Query Result

● as object– $qry->result();

● as array– $qry->result_array();

Page 40: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 40

CI Database – CI Database – Standard ExampleStandard ExampleCI Database – CI Database – Standard ExampleStandard Example$this->load->database();

$query = $this->db->query('SELECT name, title, email FROM my_table');

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

{

echo $row->title;

echo $row->name;

echo $row->email;

}

$this->load->database();

$query = $this->db->query('SELECT name, title, email FROM my_table');

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

{

echo $row['title'];

echo $row['name'];

echo $row['email'];

}

Page 41: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 41

CI Database – CI Database – Active RecordsActive RecordsCI Database – CI Database – Active RecordsActive Records

● Generic functions untuk mengelola koneksi ke database.

● Functions:● Selecting Data● Inserting Data● Updating Data● Deleting Data

Page 42: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 42

CI Database – CI Database – Active Records - SelectActive Records - SelectCI Database – CI Database – Active Records - SelectActive Records - Select

● $this->db->get();– $this->db->get('table_name');

● $this->db->select();– $this->db->select('title, content, date');

● $this->db->from();– $this->db->select('title, content, date');– $this->db->from('table_name');

● $this->db->where();● Simple

– $this->db->where('name', 'tahara');● Array

– $where = array('name' => 'tahara', 'website' => 'http://tahara.web.id');– $this->db->where( $where );

Page 43: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 43

CI Database – CI Database – Active Records - InsertActive Records - InsertCI Database – CI Database – Active Records - InsertActive Records - Insert

$data = array

(

'title' => 'My title' ,

'name' => 'My Name' ,

'date' => 'My date'

);

$this->db->insert('mytable', $data);

// INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

Page 44: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 44

CI Database – CI Database – Active Records - UpdateActive Records - UpdateCI Database – CI Database – Active Records - UpdateActive Records - Update

$data = array

(

'title' => $title,

'name' => $name,

'date' => $date

);

$this->db->where('id', $id);

$this->db->update('mytable', $data);

// UPDATE mytable

// SET title = '{$title}', name = '{$name}', date = '{$date}'

// WHERE id = $id

Page 45: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 45

CI Database – CI Database – Active Records - DeleteActive Records - DeleteCI Database – CI Database – Active Records - DeleteActive Records - Delete

$this->db->delete('mytable', array('id' => $id));

// DELETE FROM mytable WHERE id = $id

$this->db->where('id', $id);

$this->db->delete('mytable');

// DELETE FROM mytable WHERE id = $id

$tables = array('table1', 'table2', 'table3');

$this->db->where('id', '5');

$this->db->delete($tables);

Page 46: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 46

Workshop( Simple CI Application )

Page 47: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 47

PlanPlanPlanPlan● Analisa Database● Pembuatan Database dan Table● Instalasi Codeigniter 2● Start to Code!

Page 48: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 48

Analisa DatabaseAnalisa DatabaseAnalisa DatabaseAnalisa Database

Page 49: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 49

Pembuatan Database & TablePembuatan Database & TablePembuatan Database & TablePembuatan Database & Table● Database: workshop_ci

CREATE SCHEMA IF NOT EXISTS `workshop_ci` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;

USE `workshop_ci` ;

Page 50: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 50

Pembuatan Database & Table Pembuatan Database & Table (cont.)(cont.)Pembuatan Database & Table Pembuatan Database & Table (cont.)(cont.)

● Table: Category

DROP TABLE IF EXISTS `workshop_ci`.`category` ;

CREATE TABLE IF NOT EXISTS `workshop_ci`.`category`

(

`id` INT(5) UNSIGNED NOT NULL AUTO_INCREMENT ,

`name` VARCHAR(20) NULL ,

PRIMARY KEY (`id`)

)

ENGINE = InnoDB

DEFAULT CHARACTER SET = utf8

COLLATE = utf8_general_ci;

Page 51: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 51

Pembuatan Database & Table Pembuatan Database & Table (cont.)(cont.)Pembuatan Database & Table Pembuatan Database & Table (cont.)(cont.)

● Table: BooksDROP TABLE IF EXISTS `workshop_ci`.`books` ;

CREATE TABLE IF NOT EXISTS `workshop_ci`.`books` (

`id` INT(7) UNSIGNED NOT NULL AUTO_INCREMENT ,

`category_id` INT(5) UNSIGNED NOT NULL ,

`title` VARCHAR(200) NULL ,

`isbn` VARCHAR(30) NULL ,

PRIMARY KEY (`id`) ,

INDEX `fk_books_category` (`category_id` ASC) ,

CONSTRAINT `fk_books_category`

FOREIGN KEY (`category_id` )

REFERENCES `workshop_ci`.`category` (`id` )

ON DELETE NO ACTION

ON UPDATE CASCADE)

ENGINE = InnoDB

DEFAULT CHARACTER SET = utf8

COLLATE = utf8_general_ci;

Page 52: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 52

Instalasi Codeigniter 2Instalasi Codeigniter 2Instalasi Codeigniter 2Instalasi Codeigniter 2● Langkah – langkah:

● Download Codeigniter.● Extract pada folder “document_root” server.● Test Codeigniter welcome page.

Page 53: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 53

Instalasi Codeigniter 2 Instalasi Codeigniter 2 (cont.)(cont.)Instalasi Codeigniter 2 Instalasi Codeigniter 2 (cont.)(cont.)

● Download Codeigniter● http://codeigniter.com/downloads/

Page 54: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 54

Instalasi Codeigniter 2 Instalasi Codeigniter 2 (cont.)(cont.)Instalasi Codeigniter 2 Instalasi Codeigniter 2 (cont.)(cont.)

● Extract pada folder “document_root” server

Page 55: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 55

Instalasi Codeigniter 2 Instalasi Codeigniter 2 (cont.)(cont.)Instalasi Codeigniter 2 Instalasi Codeigniter 2 (cont.)(cont.)

● Test Codeigniter welcome page● http://localhost

Page 56: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 56

Start to Code! –Start to Code! – filefile: /application/: /application/configconfig/database.php/database.phpStart to Code! –Start to Code! – filefile: /application/: /application/configconfig/database.php/database.php

.

.

.

$db['default']['hostname'] = 'host_server';

$db['default']['username'] = 'mysql_user';

$db['default']['password'] = 'mysql_password';

$db['default']['database'] = 'mysql_database_name';

$db['default']['dbdriver'] = 'mysql';

.

.

.

Page 57: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 57

Start to Code! –Start to Code! – filefile: /application/: /application/configconfig/autoload.php/autoload.phpStart to Code! –Start to Code! – filefile: /application/: /application/configconfig/autoload.php/autoload.php

.

.

.

$autoload['helper'] = array('url', 'form');

.

.

.

Page 58: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 58

Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/kategori.php/kategori.phpStart to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/kategori.php/kategori.php

<?php

class Kategori extends CI_Controller {

public function __construct()

{

parent::__construct();

$this->load->database();

}

public function index()

{

$qry = $this->db->query('select * from category');

$view['data'] = $qry->result_array();

$this->load->view('kategori/list', $view);

}

public function tambah()

{

$this->load->view('kategori/form');

}

public function edit($prm_key = '')

{

if(trim($prm_key) != '')

{

$qry = $this->db->get_where

(

'category'

, array('id' => $prm_key)

);

$view['data'] = $qry->result_array();

$this->load->view('kategori/form', $view);

} else {

redirect(site_url().'/kategori');

}

}

public function hapus($prm_key = '') {

if(trim($prm_key) != '') {

$qry = $this->db->delete

(

'category'

, array

(

'id' => $prm_key

)

);

}

redirect(site_url().'/kategori');

}

Page 59: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 59

Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/kategori.php /kategori.php (cont.)(cont.)Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/kategori.php /kategori.php (cont.)(cont.)

public function simpan()

{

$this->load->library('form_validation');

$rules = array

(

array

(

'field' => 'txt_id'

, 'label' => 'ID'

, 'rules' => 'trim'

)

, array

(

'field' => 'txt_name'

, 'label' => 'Kategori'

, 'rules' => 'trim|required'

)

);

$this->form_validation->set_rules($rules);

$this->form_validation->set_error_delimiters('<code>', '</code>');

if($this->form_validation->run() == FALSE)

{

$this->load->view('kategori/form');

} else {

$qry = $this->db->get_where

(

'category'

, array('id' => $this->input->post('txt_id'))

);

$data = array

(

'name' => $this->input->post('txt_name')

);

if( count($qry->result()) == 0 )

{

$data = array_merge

(

array( 'id' => $this->input->post('txt_id') )

, $data

);

$this->db->insert('category', $data);

} else {

$this->db->update

(

'category'

, $data

, array('id' => $this->input->post('txt_id'))

);

}

redirect(site_url().'/kategori');

}

}

}

Page 60: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 60

Start to Code! –Start to Code! – filefile: /application/: /application/viewsviews/kategori/kategori/list.php/list.phpStart to Code! –Start to Code! – filefile: /application/: /application/viewsviews/kategori/kategori/list.php/list.php

<html>

<head>

<title>Master Kategori</title>

<link href='<?php echo base_url(); ?>resources/css/style.css' rel='stylesheet' type='text/css' />

<script>

function jsTambah() {

document.location = 'kategori/tambah';

}

</script>

</head>

<body>

<h1>Master Kategori Buku (View List)</h1>

<br />

<input type='button' name='btnTambah' value='Tambah' onClick='javascript: jsTambah();' />

<br /><br />

<table width='100%' align='center' cellspacing='0' cellpadding='0'>

<tr>

<th width='1%'>Kode</th>

<th>Kategori</th>

<th width='100'><i>perintah</i></th>

</tr>

<?php

foreach($data as $row) {

?>

<tr>

<td><?php echo $row['id']; ?></td>

<td><?php echo $row['name']; ?></td>

<td align='center'>

<a

href='<?php echo site_url(); ?>/kategori/edit/<?php echo $row['id']; ?>'

>Edit</a> |

<a href='<?php echo site_url(); ?>/kategori/hapus/<?php echo $row['id']; ?>'>Hapus</a>

</td>

</tr>

<?php

}

?>

</table>

</body>

</html>

Page 61: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 61

Start to Code! – Start to Code! – ScreenshotScreenshot: : Kategori (list)Kategori (list)Start to Code! – Start to Code! – ScreenshotScreenshot: : Kategori (list)Kategori (list)

Page 62: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 62

Start to Code! –Start to Code! – filefile: /application/: /application/viewsviews/kategori/kategori/form.php/form.phpStart to Code! –Start to Code! – filefile: /application/: /application/viewsviews/kategori/kategori/form.php/form.php

<html>

<head>

<title>Master Kategori</title>

<link href='<?php echo base_url(); ?>resources/css/style.css' rel='stylesheet' type='text/css' />

<script>

function jsView() {

document.location = '<?php echo site_url(); ?>/kategori';

}

</script>

</head>

<body>

<h1>Master Kategori Buku (Form)</h1>

<br />

<input type='button' name='btn_view' value='Kembali ke View' onClick='javascript: jsView();' />

<br /><br />

<?php echo form_open('kategori/simpan'); ?>

<table width='600' align='center' cellspacing='0' cellpadding='0'>

<tr>

<th align='right' width='20%'>ID</th>

<td>

<?php echo form_error('txt_id'); ?>

<input type='text' name='txt_id' size='3' maxlength='3' readOnly='readOnly' class='read_only'

value='<?php if(isset($data)) echo $data[0]['id']; else echo set_value('txt_id'); ?>' />

</td>

</tr>

<tr>

<th align='right'>Kategori*</th>

<td>

<?php echo form_error('txt_name'); ?>

<input type='text' name='txt_name' size='30' maxlength='30'

value='<?php if(isset($data)) echo $data[0]['name']; else echo set_value('txt_name'); ?>' />

</td>

</tr>

<tr>

<td colspan='2'>

<i>* - Wajib isi</i>

<div align='right'>

<input type='submit'

name='cmd_simpan'

value='Simpan' />

</div>

</td>

</tr>

</table>

</form>

</body>

</html>

Page 63: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 63

Start to Code! – Start to Code! – ScreenshotScreenshot: : Kategori (form)Kategori (form)Start to Code! – Start to Code! – ScreenshotScreenshot: : Kategori (form)Kategori (form)

Page 64: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 64

Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/buku.php/buku.phpStart to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/buku.php/buku.php

<?php

class Buku extends CI_Controller {

public function __construct()

{

parent::__construct();

$this->load->database();

}

public function index()

{

$qry = $this->db->query('select * from books');

$view['data'] = $qry->result_array();

$this->load->view('buku/list', $view);

}

public function tambah()

{

$data['kategori_combo'] = $this->_kategori_combo_generate();

$this->load->view('buku/form', $data);

}

public function edit($prm_key = '')

{

if(trim($prm_key) != '')

{

$view['kategori_combo'] = $this->_kategori_combo_generate();

$qry = $this->db->get_where

(

'books'

, array('id' => $prm_key)

);

$view['data'] = $qry->result_array();

$this->load->view('buku/form', $view);

} else {

redirect(site_url().'/buku');

}

}

public function hapus($prm_key = '') {

if(trim($prm_key) != '') {

$qry = $this->db->delete

(

'books'

, array

(

'id' => $prm_key

)

);

}

redirect(site_url().'/buku');

}

Page 65: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 65

Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/buku.php /buku.php (cont.)(cont.)Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/buku.php /buku.php (cont.)(cont.)

public function simpan()

{

$this->load->library('form_validation');

$rules = array

(

array

(

'field' => 'txt_id'

, 'label' => 'ID'

, 'rules' => 'trim'

)

, array

(

'field' => 'cmb_kategori'

, 'label' => 'Kategori'

, 'rules' => 'trim|required'

)

, array

(

'field' => 'txt_judul'

, 'label' => 'Judul'

, 'rules' => 'trim|required'

)

);

$this->form_validation->set_rules($rules);

$this->form_validation->set_error_delimiters('<code>', '</code>');

if($this->form_validation->run() == FALSE)

{

$this->load->view('buku/form');

} else {

$qry = $this->db->get_where

(

'books'

, array('id' => $this->input->post('txt_id'))

);

$data = array

(

'category_id' => $this->input->post('cmb_kategori')

, 'title' => $this->input->post('txt_judul')

, 'isbn' => $this->input->post('txt_isbn')

);

if( count($qry->result()) == 0 )

{

$data = array_merge

(

array( 'id' => $this->input->post('txt_id') )

, $data

);

$this->db->insert('books', $data);

} else {

$this->db->update

(

'books'

, $data

, array('id' => $this->input->post('txt_id'))

);

}

redirect(site_url().'/buku');

}

}

Page 66: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 66

Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/buku.php /buku.php (cont.)(cont.)Start to Code! –Start to Code! – filefile: /application/: /application/controllerscontrollers/buku.php /buku.php (cont.)(cont.)

private function _kategori_combo_generate()

{

$qry = $this->db->query('select * from category');

$result = $qry->result_array();

return $result;

}

}

Page 67: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 67

Start to Code! –Start to Code! – filefile: /application/: /application/viewsviews/buku/buku/list.php/list.phpStart to Code! –Start to Code! – filefile: /application/: /application/viewsviews/buku/buku/list.php/list.php

<html>

<head>

<title>Master Buku</title>

<link href='<?php echo base_url(); ?>resources/css/style.css' rel='stylesheet' type='text/css' />

<script>

function jsTambah() {

document.location = 'buku/tambah';

}

</script>

</head>

<body>

<h1>Master Buku (View List)</h1>

<br />

<input type='button' name='btnTambah' value='Tambah' onClick='javascript: jsTambah();' />

<br /><br />

<table width='100%' align='center' cellspacing='0' cellpadding='0'>

<tr>

<th width='1%'>Kode</th>

<th width='15%'>Kategori</th>

<th>Judul</th>

<th width='10%'>ISBN</th>

<th width='100'><i>perintah</i></th>

</tr>

<?php

foreach($data as $row) {

?>

<tr>

<td><?php echo $row['id']; ?></td>

<td><?php echo $row['category_id']; ?></td>

<td><?php echo $row['title']; ?></td>

<td><?php echo $row['isbn']; ?></td>

<td align='center'>

<a href='<?php echo site_url(); ?>/buku/edit/<?php echo $row['id']; ?>'>Edit</a> |

<a href='<?php echo site_url(); ?>/buku/hapus/<?php echo $row['id']; ?>'>Hapus</a>

</td>

</tr>

<?php

}

?>

</table>

</body>

</html>

Page 68: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 68

Start to Code! – Start to Code! – ScreenshotScreenshot: Buku: Buku (list) (list)Start to Code! – Start to Code! – ScreenshotScreenshot: Buku: Buku (list) (list)

Page 69: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 69

Start to Code! –Start to Code! – filefile: /application/: /application/viewsviews/buku/buku/form.php/form.phpStart to Code! –Start to Code! – filefile: /application/: /application/viewsviews/buku/buku/form.php/form.php

<html>

<head>

<title>Master Buku</title>

<link href='<?php echo base_url(); ?>resources/css/style.css' rel='stylesheet' type='text/css' />

<script>

function jsView() {

document.location = '<?php echo site_url(); ?>/buku';

}

</script>

</head>

<body>

<h1>Master Buku (Form)</h1>

<br />

<input type='button' name='btn_view' value='Kembali ke View' onClick='javascript: jsView();' />

<br /><br />

<?php echo form_open('buku/simpan'); ?>

<table width='600' align='center' cellspacing='0' cellpadding='0'>

<tr>

<th align='right' width='20%'>Kode<br /><small><i>(auto)</i></small></th>

<td>

<?php echo form_error('txt_id'); ?>

<input type='text' name='txt_id' size='3' maxlength='3' readOnly='readOnly' class='read_only'

value='<?php if(isset($data)) echo $data[0]['id']; else echo set_value('txt_id'); ?>' />

</td>

</tr>

<tr>

<th align='right'>Kategori*</th>

<td>

<?php echo form_error('cmb_kategori'); ?>

<select name='cmb_kategori'>

<?php

foreach ( $kategori_combo as $rows )

{

echo '<option value="'.$rows['id'].'">'.$rows['name'].'</option>';

}

?>

</select>

</td>

</tr>

Page 70: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 70

Start to Code! –Start to Code! – filefile: /application/: /application/viewsviews/buku/buku/form.php /form.php (cont.)(cont.)Start to Code! –Start to Code! – filefile: /application/: /application/viewsviews/buku/buku/form.php /form.php (cont.)(cont.)

<tr>

<th align='right'>Judul*</th>

<td>

<?php echo form_error('txt_judul'); ?>

<input type='text' name='txt_judul' size='60' maxlength='200'

value='<?php if(isset($data)) echo $data[0]['title']; else echo set_value('txt_judul'); ?>' />

</td>

</tr>

<tr>

<th align='right'>ISBN</th>

<td>

<?php echo form_error('txt_isbn'); ?>

<input type='text' name='txt_isbn' size='30' maxlength='30'

value='<?php if(isset($data)) echo $data[0]['isbn']; else echo set_value('txt_isbn'); ?>' />

</td>

</tr>

<tr>

<td colspan='2'>

<i>* - Wajib isi</i>

<div align='right'>

<input type='submit' name='cmd_simpan' value='Simpan' />

</div>

</td>

</tr>

</table>

</form>

</body>

</html>

Page 71: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 71

Start to Code! – Start to Code! – ScreenshotScreenshot: Buku: Buku (form) (form)Start to Code! – Start to Code! – ScreenshotScreenshot: Buku: Buku (form) (form)

Page 72: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 72

Start to Code! –Start to Code! – filefile: /resources/css/style.css: /resources/css/style.cssStart to Code! –Start to Code! – filefile: /resources/css/style.css: /resources/css/style.css

body {

background-color: #fff;

margin: 40px;

font-family: Lucida Grande, Verdana, Sans-serif;

font-size: 14px;

color: #4F5155;

}

a {

color: #003399;

background-color: transparent;

font-weight: normal;

}

h1 {

color: #444;

background-color: transparent;

border-bottom: 1px solid #D0D0D0;

font-size: 20px;

font-weight: bold;

margin: 24px 0 2px 0;

padding: 5px 0 6px 0;

}

code {

font-family: Monaco, Verdana, Sans-serif;

font-size: 12px;

background-color: #FF8181;

border: 1px solid #D0D0D0;

color: #002166;

display: block;

margin: 5px 0px;

padding: 5px;

}

table, th, td {

padding: 0px;

margin: 0px;

border: 1px solid #D0D0D0;

color: #002166;

}

th {

background-color: #f9f9f9;

}

td, th {

padding: 3px;

}

.read_only{

border: none;

}

Page 73: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 73

Love to Code?Love to Code?Love to Code?Love to Code?● Full EER:

Page 74: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 74

What's Next?What's Next?What's Next?What's Next?● Many controllers with single view.● Moving to AJAX based development with Web 2.0 technology.

● jQuery, Prototype + Scriptaculous, MooTools.● Learn how to use caching.

● server cache.● database cache.● view cache.

● Using template engine.● Smarty PHP Template Engine Framework.● Template Lite.

● and many more improvement...

Page 75: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 75

Resource

Page 76: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 76

ResourceResourceResourceResource● Abeysinghe, Samisa. “PHP Team

Development”, Packt Publishing, September 2010, Birmingham, UK.

● Griffiths, Adam. “Codeigniter 1.7 Professional Development”, Packt Publishing, April 2010, Birmingham, UK.

● CodeIgniter User Guide Version 2.0.2, 2011, “CodeIgniter User Guide”, http://codeigniter.com/user_guide/index.html, April 2011.

Page 77: Mvc With Codeigniter

rizky tahara shita - http://tahara.web.id 77

PenutupPenutupPenutupPenutup

Terima Kasih


Top Related