Bài 3: Lập trình nâng cao với CI4

Lập trình nâng cao CI4

Lập trình nâng cao với CodeIgniter 4 (CI4)

Trong bài viết này, chúng ta sẽ cùng khám phá CodeIgniter 4 nâng cao – loạt tính năng quan trọng giúp bạn xây dựng ứng dụng web chuyên nghiệp và an toàn hơn. Từ việc viết Middleware/Filter để kiểm soát request, thực hiện Validation dữ liệu cho form và API, đến quản lý Session & Cookie, upload và xử lý ảnh, thiết lập Pagination, gửi Email (SMTP) và đảm bảo bảo mật với CSRF, XSS, cho tới Error handling & Logging, tất cả sẽ được hướng dẫn chi tiết kèm ví dụ thực tế để bạn áp dụng ngay vào dự án của mình.


1. Middleware & Filter

Filter giúp chặn hoặc xử lý request trước khi vào Controller.

Tạo Filter:

php spark make:filter AuthFilter
namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (! session()->get('isLoggedIn')) {
            return redirect()->to('/login');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}

Đăng ký Filter:

app/Config/Filters.php

public $aliases = [
    'auth' => \App\Filters\AuthFilter::class,
];
public $globals = [
    'before' => ['csrf'],
];
public $filters = [
    'auth' => ['before' => ['dashboard/*']],
];

2. Validation (Form & API)

CI4 hỗ trợ validation mạnh mẽ.

Controller:

public function register()
{
    $rules = [
        'username' => 'required|min_length[3]|max_length[20]',
        'email'    => 'required|valid_email|is_unique[users.email]',
        'password' => 'required|min_length[6]',
    ];

    if (! $this->validate($rules)) {
        return view('register', [
            'validation' => $this->validator
        ]);
    }

    // Insert user
    $model = new UserModel();
    $model->save([
        'username' => $this->request->getPost('username'),
        'email'    => $this->request->getPost('email'),
        'password' => password_hash($this->request->getPost('password'), PASSWORD_BCRYPT)
    ]);

    return redirect()->to('/login');
}

 


3. Session & Cookie

CI4 hỗ trợ session driver (file, database, Redis).

// Set session
session()->set('isLoggedIn', true);

// Get session
if (session()->get('isLoggedIn')) { ... }

// Cookie
$response->setCookie('remember', 'yes', 3600);


4. Upload file & Xử lý ảnh

Upload:

$file = $this->request->getFile('avatar');
if ($file->isValid() && !$file->hasMoved()) {
    $file->move(WRITEPATH.'uploads');
}

Resize ảnh (Image Manipulation):

$image = \Config\Services::image()
    ->withFile(WRITEPATH.'uploads/'.$file->getName())
    ->resize(300, 300, true)
    ->save(WRITEPATH.'uploads/thumb_'.$file->getName());


5. Pagination

Trong Controller:

$model = new UserModel();
$data['users'] = $model->paginate(10);
$data['pager'] = $model->pager;

return view('users/list', $data);

Trong view:

<?= $pager->links() ?>

6. Gửi Email (SMTP)

app/Config/Email.php

public $protocol = 'smtp';
public $SMTPHost = 'smtp.gmail.com';
public $SMTPUser = '[email protected]';
public $SMTPPass = 'app-password';
public $SMTPPort = 587;
public $mailType = 'html';

Gửi mail:

$email = \Config\Services::email();
$email->setTo('[email protected]');
$email->setSubject('Welcome!');
$email->setMessage('Cảm ơn bạn đã đăng ký.');
$email->send();

7. Security

  • CSRF: Bật trong app/Config/Filters.php ('before' => ['csrf'])

  • XSS: Dùng esc() trong view:

<?= esc($user->name) ?>
  • Escape output: Luôn dùng esc() hoặc htmlspecialchars.


8. Error handling & Logging

  • Log: writable/logs/

  • Ghi log:

log_message('error', 'Có lỗi: {data}', ['data' => $info]);
  • Tùy chỉnh app/Config/Logger.php.


📚 Tài liệu tham khảo

Thành Nguyễn

Tôi là Thành, nên tôi đặt tên blog là Thành Nè, Thánh Né... là một coder cùi bắp (Code quèn). Chẳng giỏi viết lách, chỉ giỏi chém gió và có sở thích chia sẻ những kiến thức tôi đã từng...