Bài 5: Tích hợp & Công cụ trong CI4

Tích hợp & Công cụ trong CI4

Bài viết này hướng dẫn bạn cách tích hợp & sử dụng các công cụ trong CI4.

1. Sử dụng Composer packages

CI4 hỗ trợ Composer để quản lý thư viện giống Laravel.

  • Ví dụ cài PHPMailer:

    composer require phpmailer/phpmailer
  • Gọi trong controller:

    use PHPMailer\PHPMailer\PHPMailer;
    
    $mail = new PHPMailer(true);
    $mail->setFrom('[email protected]', 'MyApp');
    $mail->addAddress('[email protected]');
    $mail->Subject = "Test email";
    $mail->Body = "Hello from CI4!";
    $mail->send();

➔ Composer giúp tận dụng được hệ sinh thái PHP (Stripe, Firebase, Guzzle…).


2. GuzzleHTTP client (call external API)

  • Cài đặt:

    composer require guzzlehttp/guzzle
  • Gọi API từ controller:

    use GuzzleHttp\Client;
    
    $client = new Client();
    $res = $client->get('https://jsonplaceholder.typicode.com/posts/1');
    $data = json_decode($res->getBody(), true);
    
    return $this->response->setJSON($data);

➔ Rất hữu ích khi bạn cần gọi API của bên thứ 3 (Stripe, PayPal, Cloudflare…).


3. Queue Job (RabbitMQ, Redis, hoặc simulate trong CI4)

CI4 không có queue built-in như Laravel, nhưng có thể tích hợp.

  • Cách simulate đơn giản: tạo bảng jobs trong DB, lưu các task → cronjob sẽ chạy php spark jobs:run.

  • Ví dụ code:

    // JobModel.php
    class JobModel extends Model {
        protected $table = 'jobs';
        protected $allowedFields = ['type', 'payload', 'status'];
    }
    
    // Add job
    $jobModel = new JobModel();
    $jobModel->insert([
        'type' => 'send_email',
        'payload' => json_encode(['to' => '[email protected]']),
        'status' => 'pending'
    ]);
  • Worker chạy cronjob:

    $jobs = $jobModel->where('status', 'pending')->findAll();
    foreach ($jobs as $job) {
        // xử lý email
        $jobModel->update($job['id'], ['status' => 'done']);
    }

➔ Nếu muốn chuyên nghiệp hơn, dùng Redis Queue hoặc RabbitMQ.


4. Cache (File, Redis, Memcached)

CI4 hỗ trợ nhiều driver cache (file, redis, memcached).

  • Cấu hình: app/Config/Cache.php hoặc .env:

    cache.handler = file 
    cache.backupHandler = dummy

  • Sử dụng:

    $cache = \Config\Services::cache();
    
    // Lưu cache 5 phút
    $cache->save('username', 'Thanh', 300);
    
    // Lấy cache
    echo $cache->get('username');
    
    // Xóa cache
    $cache->delete('username');

➔ Với Redis/Memcached thì chỉ cần đổi handler trong config.


5. Debugging (Kint & Debug Toolbar)

  • CI4 tích hợp sẵn Kint (d(), dd()) để dump dữ liệu.

    d($variable); 
    dd($userData);
  • Debug Toolbar: khi CI_ENVIRONMENT = development, thanh debug xuất hiện dưới cùng trang → xem query, logs, routes…

➔ Giúp dev debug cực nhanh.


6. Unit Test với PHPUnit

CI4 tích hợp PHPUnit.

  • Tạo test:

    php spark make:test UserTest
  • File tests/app/Models/UserTest.php

    use CodeIgniter\Test\CIUnitTestCase;
    
    class UserTest extends CIUnitTestCase
    {
        public function testUserCreation()
        {
            $user = model('UserModel');
            $id = $user->insert(['name' => 'Thanh']);
            $this->assertIsInt($id);
        }
    }

  • Chạy test:

    ./vendor/bin/phpunit

➔ Testing giúp dự án CI4 maintain dễ dàng hơn.


7. Event & Listener trong CI4

CI4 có hệ thống event giống Laravel.

  • Định nghĩa trong app/Config/Events.php

    use App\Listeners\SendWelcomeEmail;
    
    Events::on('user_registered', [SendWelcomeEmail::class, 'handle']);
  • Listener:

    namespace App\Listeners;
    
    class SendWelcomeEmail {
        public function handle($data) {
            // logic gửi email
            log_message('info', "Email sent to {$data['email']}");
        }
    }

     

  • Gọi event trong Controller:

    Events::trigger('user_registered', ['email' => '[email protected]']);

➔ Cách này tách biệt logic → code sạch & dễ mở rộng.

“Xem thêm: Hướng dẫn cài đặt CI4 cơ bản

Avatar photo