Cari Halaman

Pengenalan CodeIgniter 3

Sarah Johnson
1 January 0001
4-5 jam

Pengenalan CodeIgniter 3 - Framework PHP yang Stabil

CodeIgniter 3 adalah framework PHP yang telah teruji dan banyak digunakan dalam pengembangan aplikasi web. Mari kita mulai dengan dasar-dasar CodeIgniter 3.

Apa itu CodeIgniter 3?

CodeIgniter 3 adalah framework PHP open-source yang mengikuti pola MVC (Model-View-Controller) dan dirancang untuk pengembangan aplikasi web yang cepat dan efisien.

Keunggulan CodeIgniter 3

  • Lightweight: Framework yang ringan dan cepat
  • MVC Pattern: Struktur yang terorganisir
  • Active Record: Database abstraction layer
  • Form Validation: Built-in form validation
  • Security: CSRF protection, XSS filtering
  • Session Management: Flexible session handling
  • Caching: Multiple cache backends
  • CLI Tools: Command-line interface
  • Stable: Framework yang telah teruji

Persiapan Development Environment

1. System Requirements

1
2
3
4
# PHP >= 5.6 (recommended PHP 7.4+)
# MySQL/PostgreSQL/SQLite
# Apache/Nginx web server
# Composer (optional but recommended)

2. Download CodeIgniter 3

1
2
3
4
5
# Download dari website resmi
# https://codeigniter.com/download

# Atau menggunakan Composer
composer create-project codeigniter/framework my-ci3-app

3. Setup Project

1
2
3
4
5
6
7
# Extract ke direktori web server
# Set permissions
chmod -R 755 application/
chmod -R 755 system/

# Configure database
# Edit application/config/database.php

Struktur Direktori CodeIgniter 3

1. Directory Structure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
my-ci3-app/
├── application/          # Application code
│   ├── config/          # Configuration files
│   ├── controllers/     # Controller classes
│   ├── models/          # Model classes
│   ├── views/           # View files
│   ├── libraries/       # Custom libraries
│   ├── helpers/         # Helper functions
│   └── language/        # Language files
├── system/              # Framework core
├── user_guide/          # Documentation
└── index.php            # Front controller

2. Configuration Files

 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
// application/config/config.php
$config['base_url'] = 'http://localhost/my-ci3-app/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
$config['charset'] = 'UTF-8';
$config['enable_hooks'] = FALSE;
$config['subclass_prefix'] = 'MY_';
$config['composer_autoload'] = FALSE;
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
$config['allow_get_array'] = TRUE;
$config['log_threshold'] = 0;
$config['log_path'] = '';
$config['log_file_extension'] = '';
$config['log_file_permissions'] = 0644;
$config['log_date_format'] = 'Y-m-d H:i:s';
$config['error_views_path'] = '';
$config['cache_path'] = '';
$config['encryption_key'] = '';
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
$config['standardize_newlines'] = FALSE;
$config['global_xss_filtering'] = FALSE;
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
$config['compress_output'] = FALSE;
$config['time_reference'] = 'local';
$config['rewrite_short_tags'] = FALSE;
$config['proxy_ips'] = '';

MVC Pattern

1. Model

 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
<?php
// application/models/User_model.php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends CI_Model {
    
    public function __construct() {
        parent::__construct();
        $this->load->database();
    }
    
    public function get_all_users() {
        $query = $this->db->get('users');
        return $query->result();
    }
    
    public function get_user_by_id($id) {
        $query = $this->db->get_where('users', array('id' => $id));
        return $query->row();
    }
    
    public function create_user($data) {
        return $this->db->insert('users', $data);
    }
    
    public function update_user($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update('users', $data);
    }
    
    public function delete_user($id) {
        $this->db->where('id', $id);
        return $this->db->delete('users');
    }
}

2. View

 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
<!-- application/views/users/index.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Users List</title>
    <link rel="stylesheet" href="<?= base_url('assets/css/style.css') ?>">
</head>
<body>
    <div class="container">
        <h1>Users List</h1>
        
        <a href="<?= site_url('users/create') ?>" class="btn btn-primary">Add New User</a>
        
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($users as $user): ?>
                <tr>
                    <td><?= $user->id ?></td>
                    <td><?= $user->name ?></td>
                    <td><?= $user->email ?></td>
                    <td>
                        <a href="<?= site_url('users/edit/'.$user->id) ?>" class="btn btn-sm btn-warning">Edit</a>
                        <a href="<?= site_url('users/delete/'.$user->id) ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</body>
</html>

3. Controller

 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
<?php
// application/controllers/Users.php
defined('BASEPATH') OR exit('No direct script access allowed');

class Users extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->library('form_validation');
    }
    
    public function index() {
        $data['users'] = $this->user_model->get_all_users();
        $data['title'] = 'Users List';
        
        $this->load->view('templates/header', $data);
        $this->load->view('users/index', $data);
        $this->load->view('templates/footer');
    }
    
    public function create() {
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        
        if ($this->form_validation->run() === FALSE) {
            $data['title'] = 'Create User';
            $this->load->view('templates/header', $data);
            $this->load->view('users/create');
            $this->load->view('templates/footer');
        } else {
            $data = array(
                'name' => $this->input->post('name'),
                'email' => $this->input->post('email'),
                'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
                'created_at' => date('Y-m-d H:i:s')
            );
            
            $this->user_model->create_user($data);
            $this->session->set_flashdata('success', 'User created successfully');
            redirect('users');
        }
    }
    
    public function edit($id) {
        $data['user'] = $this->user_model->get_user_by_id($id);
        
        if (empty($data['user'])) {
            show_404();
        }
        
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        
        if ($this->form_validation->run() === FALSE) {
            $data['title'] = 'Edit User';
            $this->load->view('templates/header', $data);
            $this->load->view('users/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $update_data = array(
                'name' => $this->input->post('name'),
                'email' => $this->input->post('email'),
                'updated_at' => date('Y-m-d H:i:s')
            );
            
            $this->user_model->update_user($id, $update_data);
            $this->session->set_flashdata('success', 'User updated successfully');
            redirect('users');
        }
    }
    
    public function delete($id) {
        $user = $this->user_model->get_user_by_id($id);
        
        if (empty($user)) {
            show_404();
        }
        
        $this->user_model->delete_user($id);
        $this->session->set_flashdata('success', 'User deleted successfully');
        redirect('users');
    }
}

Database Operations

1. Database Configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// application/config/database.php
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'my_ci3_app',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

2. Active Record Examples

Modul Sebelumnya
Modul Selanjutnya

Progress Seri

Lanjutkan pembelajaran Anda

1/11
Modul
9%
Sedang Berjalan