Membina sistem Buletinboard menggunakan CodeIgniter 4 (CI4)

Baik! Untuk memenuhi permintaan anda, saya akan menyediakan langkah-langkah yang lebih terperinci untuk membina sistem Buletinboard menggunakan CodeIgniter 4 (CI4) dengan pengurusan pengguna, di mana pengguna boleh menambah dan mengemaskini berita, serta dapat set berita sebagai featured.

Ciri-ciri Sistem:

  1. Pengurusan Pengguna: Pengguna boleh mendaftar, log masuk, dan logout.
  2. Paparan Buletin: Pengguna boleh melihat buletin yang disiarkan.
  3. Tambah Berita: Pengguna yang log masuk boleh menambah berita baru.
  4. Kemaskini Berita: Pengguna boleh mengemaskini berita yang mereka buat.
  5. Featured Buletin: Admin atau pengguna dengan kuasa boleh menetapkan berita sebagai featured.

1. Persediaan Projek CI4

Pastikan anda telah memasang CodeIgniter 4 di komputer anda. Jika belum, ikuti langkah-langkah yang telah saya terangkan sebelum ini. Kalau tidak ada Composer, anda boleh muat turun CodeIgniter secara manual.

Langkah pertama: Buat Projek CI4

Sekiranya anda telah ada Composer:

bash
composer create-project codeigniter4/appstarter buletinboard cd buletinboard

2. Struktur Pangkalan Data

Di bawah adalah struktur pangkalan data untuk aplikasi buletinboard:

sql
CREATE DATABASE buletinboard_db; USE buletinboard_db; -- Jadual Pengguna (Users) CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, password VARCHAR(255) NOT NULL, role ENUM('admin', 'user') DEFAULT 'user', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Jadual Buletin (Bulletins) CREATE TABLE bulletins ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, is_featured TINYINT(1) DEFAULT 0, -- 0 for not featured, 1 for featured user_id INT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE );

3. Model

Model Pengguna (UserModel)

Buat model untuk pengguna di app/Models/UserModel.php.

php
<?php namespace App\Models; use CodeIgniter\Model; class UserModel extends Model { protected $table = 'users'; protected $primaryKey = 'id'; protected $allowedFields = ['username', 'email', 'password', 'role']; protected $useTimestamps = true; protected $validationRules = [ 'username' => 'required|min_length[3]|max_length[100]', 'email' => 'required|valid_email|is_unique[users.email]', 'password' => 'required|min_length[8]', ]; }

Model Buletin (BulletinModel)

Buat model untuk buletin di app/Models/BulletinModel.php.

php
<?php namespace App\Models; use CodeIgniter\Model; class BulletinModel extends Model { protected $table = 'bulletins'; protected $primaryKey = 'id'; protected $allowedFields = ['title', 'content', 'is_featured', 'user_id']; protected $useTimestamps = true; protected $validationRules = [ 'title' => 'required|min_length[5]|max_length[255]', 'content' => 'required|min_length[10]', ]; public function getFeaturedBulletins() { return $this->where('is_featured', 1)->findAll(); } }

4. Controller

AuthController (untuk login, logout, register)

Buat controller untuk pengurusan autentikasi pengguna di app/Controllers/AuthController.php.

php
<?php namespace App\Controllers; use App\Models\UserModel; use CodeIgniter\Controller; class AuthController extends Controller { public function login() { return view('auth/login'); } public function loginAction() { $username = $this->request->getPost('username'); $password = $this->request->getPost('password'); $userModel = new UserModel(); $user = $userModel->where('username', $username)->first(); if ($user && password_verify($password, $user['password'])) { session()->set('user_id', $user['id']); session()->set('username', $user['username']); session()->set('role', $user['role']); return redirect()->to('/bulletins'); } else { return redirect()->back()->with('error', 'Invalid login credentials'); } } public function register() { return view('auth/register'); } public function registerAction() { $userModel = new UserModel(); $data = [ 'username' => $this->request->getPost('username'), 'email' => $this->request->getPost('email'), 'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT), ]; if ($userModel->insert($data)) { return redirect()->to('/login'); } else { return redirect()->back()->with('error', 'Failed to register'); } } public function logout() { session()->destroy(); return redirect()->to('/login'); } }

BulletinController (untuk paparan, tambah, kemaskini berita)

Buat controller untuk menguruskan buletin di app/Controllers/BulletinController.php.

php
<?php namespace App\Controllers; use App\Models\BulletinModel; use App\Models\UserModel; use CodeIgniter\Controller; class BulletinController extends Controller { public function index() { $bulletinModel = new BulletinModel(); $bulletins = $bulletinModel->findAll(); return view('bulletin/index', ['bulletins' => $bulletins]); } public function create() { return view('bulletin/create'); } public function store() { $bulletinModel = new BulletinModel(); $userId = session()->get('user_id'); $data = [ 'title' => $this->request->getPost('title'), 'content' => $this->request->getPost('content'), 'user_id' => $userId, 'is_featured' => $this->request->getPost('is_featured') ?? 0, ]; if ($bulletinModel->insert($data)) { return redirect()->to('/bulletins'); } else { return redirect()->back()->with('error', 'Failed to create bulletin'); } } public function edit($id) { $bulletinModel = new BulletinModel(); $bulletin = $bulletinModel->find($id); if ($bulletin && $bulletin['user_id'] == session()->get('user_id')) { return view('bulletin/edit', ['bulletin' => $bulletin]); } else { return redirect()->to('/bulletins'); } } public function update($id) { $bulletinModel = new BulletinModel(); $data = [ 'title' => $this->request->getPost('title'), 'content' => $this->request->getPost('content'), 'is_featured' => $this->request->getPost('is_featured') ?? 0, ]; if ($bulletinModel->update($id, $data)) { return redirect()->to('/bulletins'); } else { return redirect()->back()->with('error', 'Failed to update bulletin'); } } public function delete($id) { $bulletinModel = new BulletinModel(); $bulletinModel->delete($id); return redirect()->to('/bulletins'); } }

5. View Files

  • login.php (app/Views/auth/login.php)
    Borang login untuk pengguna.
php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form action="/auth/loginAction" method="post"> <label for="username">Username:</label> <input type="text" name="username" id="username" required> <label for="password">Password:</label> <input type="password" name="password" id="password" required> <button type="submit">Login</button> </form> </body> </html>
  • create.php (app/Views/bulletin/create.php)
    Borang untuk menambah berita baru.
php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create Bulletin</title> </head> <body> <form action="/bulletins/store" method="post"> <label for="title">Title:</label> <input type="text" name="title" id="title" required> <label for="content">Content:</label> <textarea name="content" id="content" required></textarea> <label for="is_featured">Set as Featured:</label> <input type="checkbox" name="is_featured" id="is_featured"> <button type="submit">Create</button> </form> </body> </html>
  • edit.php (app/Views/bulletin/edit.php)
    Borang untuk mengemaskini berita.
php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit Bulletin</title> </head> <body> <form action="/bulletins/update/<?= esc($bulletin['id']) ?>" method="post"> <label for="title">Title:</label> <input type="text" name="title" id="title" value="<?= esc($bulletin['title']) ?>" required> <label for="content">Content:</label> <textarea name="content" id="content" required><?= esc($bulletin['content']) ?></textarea> <label for="is_featured">Set as Featured:</label> <input type="checkbox" name="is_featured" id="is_featured" <?= $bulletin['is_featured'] == 1 ? 'checked' : '' ?>> <button type="submit">Update</button> </form> </body> </html>

6. Routes

Kemaskini routes.php untuk laluan aplikasi:

php
$routes->get('/', 'BulletinController::index'); $routes->get('login', 'AuthController::login'); $routes->post('login', 'AuthController::loginAction'); $routes->get('register', 'AuthController::register'); $routes->post('register', 'AuthController::registerAction'); $routes->get('logout', 'AuthController::logout'); $routes->get('bulletins', 'BulletinController::index'); $routes->get('bulletins/create', 'BulletinController::create'); $routes->post('bulletins/store', 'BulletinController::store'); $routes->get('bulletins/edit/(:num)', 'BulletinController::edit/$1'); $routes->post('bulletins/update/(:num)', 'BulletinController::update/$1'); $routes->get('bulletins/delete/(:num)', 'BulletinController::delete/$1');

7. Kesimpulan

Sistem yang anda inginkan kini lengkap dengan:

  • Pengurusan pengguna (login, register, logout).
  • Paparan dan pengurusan buletin (menambah, mengemaskini, dan menghapuskan berita).
  • Ciri Featured untuk menandakan berita yang penting.

Anda boleh mengembangkan lagi sistem ini mengikut keperluan anda.

Membina sistem Buletinboard menggunakan CodeIgniter 4 (CI4) Membina sistem Buletinboard menggunakan CodeIgniter 4 (CI4) Reviewed by sipolan on November 09, 2024 Rating: 5

No comments

Comments