-->
Riedayme Pengetahuan untuk Mempelajari Pemrograman khususnya pada Website, Mobile dan Desktop saya tuliskan disini.
Riedayme
Riedayme

Membuat Rest Client di CodeIgniter 3

Sebelumnya saya sudah membuat rest server dengan codeigniter 3, kali ini saya membuat rest client menggunakan codeigniter 3 agar lebih lengkap studi kasusnya.


Langkah Pertama yang dilakukan

Disini saya akan menggunakan file project rest server dan menggunakan file project multi bahasa jadi nanti ada dua file project yang satu project rest server yang satu lagi project rest client. disini saya pisah kode projectnya agar bisa membedakan mana rest server dan rest client.
Silahkan download kedua file project dari tutorial diatas. kemudian melakukan konfigurasi file project rest server dan multi bahasa agar namanya tidak sama
  • extract file project rest server rubah nama folder daily_codeigniter menjadi rest_server (pastikan extractnya di dalam folder htdocs milik xampp)
  • rubah juga $config['base_url'] yang ada di dalam file config.php dan ganti urlnya menjadi http://localhost/rest_server/
  • kemudian mengimport database yang ada didalam folder project rest server (kalau mengikuti tutorial sebelumya tidak usah buat database karena sudah ada)
  • extract file project multi bahasa rubah nama folder daily_codeigniter menjadi rest_client (pastikan extractnya di dalam folder htdocs milik xampp)
  • rubah juga $config['base_url'] yang ada di dalam file config.php dan ganti urlnya menjadi http://localhost/rest_client/

Langkah Kerja

1. Install Composer, Install Guzzle, Konfigurasi Composer di CodeIgniter 3

Disini saya akan menggunakan library guzzle yang akan membantu melakukan request ke rest server dan tentunya sangat mudah penggunaannya.
  • Pertama download composer dan install
  • Kemudian Install Guzzle didalam folder project daily_codeigniter dengan cara
    • buka cmd (untuk os windows)
    • masuk kedalam path folder project daily_codeigniter kemudian masukan perintah 
    • composer require guzzlehttp/guzzle:~6.0
    • kemudian tekan enter untuk menjalankan perintahnya
  • Kemudian melakukan konfigurasi file config.php (pathnya daily_codeigniter/application/config/config.php)
  • rubah $config['composer_autoload'] = FALSE;
  • menjadi $config['composer_autoload'] = 'vendor/autoload.php';

2. Membuat Controller

  • Buat file controller dengan nama Quote_Post.php didalam folder app (pathnya daily_codeigniter/application/controller/app/Quote_Post.php)
  • isi dengan kode ini 
<?php  
defined('BASEPATH') OR exit('no direct script access allowed');

class Quote_Post extends MY_App 
{

    public $title = 'Post Quote';
    public $redirect = 'app/quote_post';

    public function __construct(){
        parent::__construct();

        $this->load->model('app/M_Quote_Post');
    }

    public function index(){

        $data['title'] = $this->lang->line('post_quote');
        $data['data_quote'] = $this->M_Quote_Post->read_data(); 

        // echo json_encode($data['data_quote']);
        // exit;
        
        $this->load->view('app/quote_post/index',$data);
    }

    public function create()
    {

        $data['title'] = $this->lang->line('post_quote_create');
        $data['update'] = false;
        $this->load->view('app/quote_post/form',$data);
    }

    public function process_create()
    {      

        # process insert
        if ($this->M_Quote_Post->insert_data() == true) {

            # set session
            $this->session->set_flashdata('create', true);

            # redirect
            redirect($this->redirect);
        } else {
            #failed insert post
        }

    }

    public function update($identity)
    {

        $data['title'] = $this->lang->line('post_quote_update');
        $data['update'] = true;
        $data['data_quote'] = $this->M_Quote_Post->get_data_update($identity); 

        $this->load->view('app/quote_post/form',$data);
    }

    public function process_update($identity)
    {      

        # process update
        if ($this->M_Quote_Post->update_data($this->input->post(),$identity) == true) {

            # set session
            $this->session->set_flashdata('edit', true);

            # redirect
            redirect($this->redirect);
        } else {
            #failed insert post
        }

    }    

    public function delete($identity)
    {

        if ($this->M_Quote_Post->delete_data($identity)) {
            # set session
            $this->session->set_flashdata('delete', true);

            # redirect
            redirect($this->redirect);
        }else {
             #failed send delete

            redirect($this->redirect);
        }

    }

    public function process_batch()
    {

        # get action
        $action =$this->input->post('action');

        
        if ($action == 'delete_batch') {

            if ($this->M_Quote_Post->delete_data_batch()) {
                # set session
                $this->session->set_flashdata('delete', true);

                redirect($this->redirect);
            }else {

                redirect($this->redirect);
            }        
        }

    }
}

3. Membuat Model

  • Buat file model dengan nama M_Quote_Post.php didalam folder app (pathnya daily_codeigniter/application/models/app/Quote_Post.php)
  • isi dengan kode ini
<?php  
defined('BASEPATH') OR exit('no direct script access allowed');

# define guzzle
use GuzzleHttp\Client;

class M_Quote_Post extends CI_Model 
{

    private $client;
    private $auth;    
    private $app_key;
    private $storage_path = 'storage/';

    public function __construct(){
        parent::__construct();

        $this->auth = ['admin','admin'];
        $this->app_key = 'admin';

        $this->client = new Client([
            'base_uri' => 'http://localhost/rest_server/api/quote_post/',
            'auth' => $this->auth,
            'query' => ['APP_KEY' => $this->app_key],
            ]);
    }

    public function read_data(){

        $curent_page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;    
        $get_display = $this->input->get('display');
        $display = !empty($get_display) ? $get_display : 5;

        $data = ['query' => ['order_by' => 'id','order_type' => 'DESC','limit' => $display,'index' => $curent_page, 'APP_KEY' => $this->app_key]];

        $read_data = $this->client->request('GET','read_all', $data);

        if ($read_data->getStatusCode() == '200') {

            $result = json_decode($read_data->getBody()->getContents(), TRUE);

            if ($result['status'] == 'failed') {
                return array(
                    'content' => false,
                    'pagination' => false,
                    'total_pagination' => '0'
                    );
            }else {

                $this->load->model('_Pagination');
                $get_pagination = $this->_Pagination->pagination(@$result['row_count'],$display,base_url('app/quote_post/index'),4);

                $result = array(
                    'content' => (!empty($result['content'])) ? $result['content'] : false,
                    'pagination' => $get_pagination['pagination']->create_links(),
                    'total_pagination' => $get_pagination['total_pagination']
                    );

                return $result;
            }
            

        }else {
            return false;
        }        
    }

    public function insert_data(){

        $data = $this->input->post();

        # create image
        $image = $this->__upload_file($data);

        # send data
        $insert_data = $this->client->request('POST', 'post', $this->__all_column($data,$image));

        if ($insert_data->getStatusCode() == '200') {
            $result = json_decode($insert_data->getBody()->getContents(), TRUE);

            if ($result['status'] == 'success') {
                $status =  true;
            }else{
                $status =  false;
            }
        }else {
            $status = false;
        }

        #delete temp file
        unlink($image);

        if ($status) {
            return true;
        }else{
            return false;
        }

    }

    public function get_data_update($identity) {

        $data = ['query' => ['key' => 'id', 'value' => $identity, 'APP_KEY' => $this->app_key]];

        $read_data = $this->client->request('GET','read_by', $data);
        
        if ($read_data->getStatusCode() == '200') {
            $result = json_decode($read_data->getBody()->getContents(), TRUE);

            if ($result['status'] == 'failed') {
                return false;
            }else {

                $data = $result['content'];

                return array(
                    'id' => $data['id'],
                    'title' => $data['title'],
                    'slug' => $data['slug'],
                    'image' => $data['image'],
                    'image_thumbnail' => $data['image_thumbnail'],
                    'time' => $data['time'],
                    'updated' => $data['updated'],
                    'category' => $data['category'],
                    'content' => $data['content'],
                    'views' => $data['views'],
                    'status' => $data['status'],
                    );
            }
        }else {
            return false;
        }  

    }

    public function update_data($data,$identity){

        # create image
        $image = $this->__upload_file($data);     

        $put_data = $this->__all_column($data,$image,$identity);

        # send data
        $update_data = $this->client->request('POST', 'update', $put_data);

        if ($update_data->getStatusCode() == '200') {
            $result = json_decode($update_data->getBody()->getContents(), TRUE);

            if ($result['status'] == 'success') {
                $status =  true;
            }else{
                $status =  false;
            }
        }else {
            $status = false;
        }

        #delete temp file
        unlink($image);

        if ($status) {
            return true;
        }else{
            return false;
        }

    }    


    public function delete_data($identity){

        # build data
        $data = ['query' => ['key' => 'id', 'value' => $identity, 'APP_KEY' => $this->app_key]];

        # send request
        $delete_data = $this->client->request('GET', 'delete_by', $data);

        if ($delete_data->getStatusCode() == '200') {

            $result = json_decode($delete_data->getBody()->getContents(), TRUE);

            if ($result['status'] == 'failed') {
                return false;
            }else {
                return true;
            }
        }else {
            return false;
        }   
    }

    public function delete_data_batch(){

        # build data
        $id_array = $this->input->post('id');

        $data = ['form_params' => ['key' => 'id', 'value' => $id_array, 'APP_KEY' => $this->app_key]];

        # send request
        $delete_data = $this->client->request('DELETE', 'delete_batch', $data);

        if ($delete_data->getStatusCode() == '200') {

            $result = json_decode($delete_data->getBody()->getContents(), TRUE);

            if ($result['status'] == 'failed') {
                return false;
            }else {
                return true;
            }
        }else {
            return false;
        }   

    }



    /**
     * logic process
     */
    
    public function __upload_file($data){

        // disable this because if the image update alyaws update image
        if (empty($_FILES['image']['name'])) {            
            return 'noimage';
        }

        #load library upload
        $this->load->library('upload');        

        $config_upload = [
        'upload_path' => $this->storage_path,
        'allowed_types' =>'jpg|png|ico',
        ];

        $this->upload->initialize($config_upload);

        if($this->upload->do_upload('image')){

            $result = array('image' => $this->upload->data());
            $path_image = $this->storage_path.$result['image']['file_name'];
            return $path_image;
        }else {
            return 'failed';
        }

    }

    public function __all_column($data,$image,$identity = false){

        $prepare_data = [
        'multipart' => [  
        [
        'name' => 'key',
        'contents' => 'id'
        ],         
        [
        'name' => 'value',
        'contents' => $identity
        ],                   
        [
        'name' => 'title',
        'contents' => strip_tags($data['title'])
        ],
        [
        'name' => 'slug',
        'contents' => strip_tags($data['slug'])
        ],
        [
        'name' => 'time',
        'contents' => date('Y-m-d H:i:s')
        ],
        [
        'name' => 'updated',
        'contents' => date('Y-m-d H:i:s')
        ],
        [
        'name' => 'category',
        'contents' => $data['category']
        ],
        [
        'name' => 'content',
        'contents' => strip_tags($data['content'])
        ],
        [
        'name' => 'views',
        'contents' => 0
        ],
        [
        'name' => 'status',
        'contents' => strip_tags($data['status'])
        ],
        [
        'name' => 'APP_KEY',
        'contents' => $this->app_key
        ]
        ]];

        if ($image == 'noimage') {
            $data = $prepare_data;
        }else {
            $data = array_merge_recursive($prepare_data,
                [
                'multipart' => [
                [
                'name' => 'image',
                'filename' => $image,
                'contents' => file_get_contents($image)
                ]
                ]]);
        }

        return $data;
    }

}
  • buat file model dengan nama _Pagination.php (pathnya daily_codeigniter/application/models/_Pagination.php)
  • isi dengan kode ini
<?php  
defined('BASEPATH') OR exit('no direct script access allowed');

class _Pagination extends CI_Model 
{

    public function pagination($count_bp,$max_result,$url,$segment,$display_pages = TRUE)
    {

        # load library
        $this->load->library('pagination');

        # setup config for pagination
        $config['base_url'] = $url;
        $config['total_rows'] = $count_bp;
        $config['per_page'] = $max_result;
        $config["uri_segment"] = $segment;
        $config['use_page_numbers'] = FALSE;
        $config['display_pages'] = $display_pages;
        $choice = $config["total_rows"] / $config["per_page"];

        # this is for show all number of pagination i disable because this is so longer result if have many post
        #$config["num_links"] = floor($choice);

        $config["num_links"] = 1;

        # setup for pagination style
        $config['first_link']       = $this->lang->line('first');
        $config['last_link']        = $this->lang->line('last');
        $config['next_link']        = $this->lang->line('next');
        $config['prev_link']        = $this->lang->line('prev');        

        $config['full_tag_open']    = '<nav class="c-pagination u-justify-right u-mt-medium"> <ul class="c-pagination__list">';
        $config['attributes'] = array('class' => 'c-pagination__link');
        $config['full_tag_close']   = '</ul> </nav>';

        $config['num_tag_open']     = '<li class="c-pagination__item">';
        $config['num_tag_close']    = '</li>';

        $config['cur_tag_open']     = '<li class="c-pagination__item"><span class="is-active c-pagination__link">';
        $config['cur_tag_close']    = '</span></li>';

        $config['next_tag_open']    = '<li class="c-pagination__item news">';
        $config['next_tagl_close']  = '<span aria-hidden="true">&raquo;</span></li>';

        $config['prev_tag_open']    = '<li class="c-pagination__item">';
        $config['prev_tagl_close']  = 'Next</li>';

        $config['first_tag_open']   = '<li class="c-pagination__item">';
        $config['first_tagl_close'] = '</li>';

        $config['last_tag_open']    = '<li class="c-pagination__item">';
        $config['last_tagl_close']  = '</li>';


         # set config for pagination
        return array(
            'pagination' => $this->pagination->initialize($config),
            'total_pagination' => (!empty($count_bp) ? $count_bp : '0')
            );                 


    }      

}

4. Membuat View

  • Buat folder quote_post didalam folder app (pathnya daily_codeigniter/application/views/app/quote_post)
  • Buat file index.php didalam folder quote_post (pathnya daily_codeigniter/application/views/app/quote_post/index.php)
  • isi dengan kode ini
<?php $this->load->view('app/_layouts/header'); ?>
<?php $this->load->view('app/_layouts/sidebar'); ?>

<form class="container-fluid u-p-zero" action="<?php echo base_url('app/quote_post/process_batch') ?>" method="POST">
    <div class="row">
        <div class="col-md-12">

            <div class="c-card c-card--responsive h-100vh u-p-zero">
                <div class="c-card__header c-card__header--transparent o-line">
                    <a class="c-btn--custom c-btn--small c-btn c-btn--info" href="<?php echo base_url('app/quote_post/create') ?>">
                        <i class="fa fa-plus"></i>
                    </a>           
                </div>
                <div class="c-card__body">

                    <?php $this->load->view('app/_layouts/alert'); ?>

                    <div class="c-toolbar u-mb-medium u-p-zero">

                        <h3 class="c-toolbar__title u-mr-auto u-pt-small u-pb-small"><?php echo $this->lang->line('total_data').$data_quote['total_pagination'] ?></h3>

                        <button type="submit" class="c-btn--custom c-btn--small c-btn c-btn--danger btn-action" name="action" value="delete_batch">
                            <i class="fa fa-trash"></i>
                        </button> 

                    </div>

                    <div class="c-table-responsive">

                        <table class="c-table c-table--zebra" style="display: table;">
                            <thead class="c-table__head">
                                <tr class="c-table__row">
                                    <th class="c-table__cell c-table__cell--head"><?php echo $this->lang->line('title'); ?></th>
                                    <th class="c-table__cell c-table__cell--head"><?php echo $this->lang->line('status'); ?></th>
                                    <th class="c-table__cell c-table__cell--head"><?php echo $this->lang->line('tools'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($data_quote['content']): ?>
                                    <?php foreach ($data_quote['content'] as $quote): ?>
                                        <input type="hidden" name="id[]" value="<?php echo $quote['id'] ?>">
                                        <tr class="c-table__row">
                                            <td class="c-table__cell break-word">
                                                <div class="o-media__img u-mr-xsmall">
                                                    <a target="_blank" href="<?php echo $quote['image_thumbnail'] ?>"><img width="60" src="<?php echo $quote['image_thumbnail'] ?>" alt="<?php echo $quote['title'] ?>"/></a>
                                                </div>
                                                <div class="o-media__body">
                                                    <?php echo $quote['title'] ?> 
                                                    <span class="u-block u-text-mute u-text-xsmall"><?php echo $quote['category'] ?></span>
                                                </div>
                                            </td>
                                            <td class="c-table__cell break-word">
                                                <div class="o-media__body">
                                                    <?php echo $quote['status'] ?> 
                                                </div>
                                            </td>
                                            <td class="c-table__cell">
                                                <a class="c-btn c-btn--info c-btn--custom" href="<?php echo base_url('app/quote_post/update/'.$quote['id']) ?>">
                                                    <i class="fa fa-edit"></i>
                                                </a>
                                                <a class="c-btn c-btn--danger c-btn--custom action-delete" href="<?php echo base_url('app/quote_post/delete/'.$quote['id']) ?>">
                                                    <i class="fa fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach ?>
                                <?php else: ?>
                                    <tr>
                                        <td class="c-table__cell u-text-center" colspan="8">No Content</td>
                                    </tr>
                                <?php endif ?>
                            </tbody>
                        </table>

                    </div>
                    <?php echo $data_quote['pagination']; ?>

                </div>
            </div>
        </div>
    </div>
</form>

<?php $this->load->view('app/_layouts/footer'); ?>
  • Buat file form.php didalam folder quote_post (pathnya daily_codeigniter/application/views/app/quote_post/form.php)
  • isi dengan kode ini
<?php $this->load->view('app/_layouts/header'); ?>
<?php $this->load->view('app/_layouts/sidebar'); ?>


<div class="container-fluid">   
    <div class="row">

        <div class="col-12">
            <form action="<?php echo ($update == true) ? base_url('app/quote_post/process_update/'.$data_quote['id']) : base_url('app/quote_post/process_create') ?>" class="row" method="post" enctype="multipart/form-data">

                <div class="col-12 col-xl-9 col-lg-9 u-p-zero">

                    <div class="c-card c-card--responsive h-100vh u-p-zero">
                        <div class="c-card__header c-card__header--transparent o-line">
                            <button class="c-btn c-btn--info" name="publish" type="submit" title="publish">
                                <i class="fa fa-save" aria-hidden="true"></i>
                            </button>
                            <div class="u-ml-auto" style="max-width: 150px">
                                <label><input value="Published" name="status" type="radio" <?php echo (!empty($data_quote['status'])) ? ($data_quote['status'] == 'Published') ? 'checked' : '' : 'checked'?>>Published</label>
                                <label><input value="Draft" name="status" type="radio" <?php echo (!empty($data_quote['status'])) ? ($data_quote['status'] == 'Draft') ? 'checked' : '' : '' ?>>Draft</label>
                            </div>
                        </div>
                        <div class="c-card__body u-p-small">

                            <div class="c-field u-mb-small">
                                <label class="c-field__label" for="input13">Title : </label>
                                <input autofocus="" autocomplete="off" value="<?php echo (!empty($data_quote['title']) ? $data_quote['title'] : '') ?>" required="" class="c-input" name="title" id="title" type="text" placeholder="title">
                            </div>

                            <div class="c-field u-mb-small">
                                <label class="c-field__label" for="input13">Slug : </label>
                                <input name="slug_old" type="hidden" value="<?php echo (!empty($data_quote['slug']) ? $data_quote['slug'] : '') ?>">
                                <input autocomplete="off" value="<?php echo (!empty($data_quote['slug']) ? $data_quote['slug'] : '') ?>" class="c-input" name="slug" id="slug" type="text" placeholder="Slug">
                            </div>    

                            <div class="c-field u-mb-small">
                                <label class="c-field__label" for="input13">Image : </label>
                                <?php if (!empty($data_quote['image_thumbnail'])): ?>
                                    <img width="100px" src="<?php echo (!empty($data_quote['image_thumbnail']) ? $data_quote['image_thumbnail'] : '') ?>" alt="Image">
                                <?php endif ?>
                                <input required="" autofocus="" autocomplete="off" class="c-input" name="image" id="image" type="file" placeholder="image">
                            </div>

                            <div class="c-field u-mb-small">
                                <label class="c-field__label" for="input13">category : </label>
                                <input autofocus="" autocomplete="off" value="<?php echo (!empty($data_quote['category']) ? $data_quote['category'] : '') ?>" required="" class="c-input" name="category" id="category" type="text" placeholder="category">
                            </div>

                            <div class="c-field u-mb-small">
                                <label class="c-field__label" for="input13">Content : </label>
                                <textarea rows="5" autofocus="" autocomplete="off" required="" class="c-input" name="content" id="content" type="text" placeholder="Quote"><?php echo (!empty($data_quote['content']) ? $data_quote['content'] : '') ?></textarea>
                            </div>  

                        </div>

                    </div>                

                </div>

            </form>

        </div>

    </div>
</div>

<?php $this->load->view('app/_layouts/footer'); ?>

5. Membuat Menu

  • buka file nav.php (pathnya daily_codeigniter/application/views/app/_layouts/nav.php)
  • ganti isi kode didalamnya menjadi kode dibawah ini
<li class="c-sidebar__item">
    <a class="c-sidebar__link <?php if($this->uri->segment(1)=="app" and empty($this->uri->segment(2)) or $this->uri->segment(2) == 'dashboard'){echo "is-active";}?>" href="<?php echo base_url('app/dashboard') ?>">
        <i class="fa fa-fire u-mr-xsmall"></i>Dashboard
    </a>
</li>

<h4 class="c-sidebar__title"><?php echo $this->lang->line('first_app'); ?></h4>

<li class="c-sidebar__item">
    <a class="c-sidebar__link <?php if($this->uri->segment(2)=='quote_post' or $this->uri->segment(2)=='quote_post' and $this->uri->segment(3) == 'create' ){echo "is-active";}?>" href="<?php echo base_url('app/quote_post') ?>">
        <i class="fa fa-fire u-mr-xsmall"></i><?php echo $this->lang->line('post_quote'); ?>
    </a>
</li>

6. Membuat Multi Bahasa

  • ganti isi file app_lang.php yang berada didalam folder indonesia dengan kode ini
<?php
$lang['welcome_message'] = 'Selamat Datang di';
$lang['first_app'] = 'Aplikasi Pertama';
$lang['post_quote'] = 'Data Quote';
$lang['data_quote'] = 'Isi Quote';

$lang['total_data'] = 'Jumalah Data : ';
$lang['title'] = 'Judul';
$lang['status'] = 'Status';
$lang['tools'] = 'Alat';

$lang['post_quote_create'] = 'Buat Quote';
$lang['post_quote_update'] = 'Update Quote';
  • ganti isi file app_lang.php yang berada didalam folder english dengan kode ini
<?php
$lang['welcome_message'] = 'Welcome to';
$lang['first_app'] = 'Firs App';
$lang['post_quote'] = 'Data Quote';
$lang['data_quote'] = 'Content Quote';

$lang['total_data'] = 'Total Data : ';
$lang['title'] = 'Title';
$lang['status'] = 'Status';
$lang['tools'] = 'Tools';

$lang['post_quote_create'] = 'Create Quote';
$lang['post_quote_update'] = 'Update Quote';
  • buat file paging_lang.php didalam folder indonesia dan isi kode ini
<?php  

$lang['next'] = 'Selanjutnya';
$lang['prev'] = 'Sebelumnya';
$lang['first'] = 'Pertama';
$lang['last'] = 'Terakhir';
  • buat file paging_lang.php didalam folder english dan isi kode ini
<?php  

$lang['next'] = 'Next';
$lang['prev'] = 'Prev';
$lang['first'] = 'First';
$lang['last'] = 'Last';

7. Mencoba Rest Client

  • buka aplikasinya http://localhost/rest_client/app/quote_post
  • dan coba untuk melakukan perintah create, update, delete

Tampilan Rest Client Menggunakan Web

0 Komentar
CodeIgniter

Artikel Terkait

Komentar