Trang chủ » Blog » [Thực hành] Ứng dụng quản lý khách hàng

[Thực hành] Ứng dụng quản lý khách hàng

bởi CodeGym | 26/12/2023 16:30 | Bài thực hành | Blog

Mục tiêu

Ứng dụng quản lý khách hàng

Luyện tập phát triển các ứng dụng quản lý sử dụng kiến trúc MVC.

Điều kiện

  • Nắm được kiến trúc MVC
  • Biết cách triển khai các ứng dụng quản lý sử dụng kiến trúc MVC

Mô tả- Ứng dụng quản lý khách hàng

Trong phần này, chúng ta sẽ phát triển một ứng dụng quản lý khách hàng. Ứng dụng có các chức năng chính sau:

  • Hiển thị danh sách khách hàng
  • Thêm một khách hàng mới
  • Sửa đổi thông tin của khách hàng
  • Xoá một khách hàng

Một khách hàng bao gồm các thành phần

  • id: Id của khách hàng
  • name: Tên của khách hàng
  • email: Email của khách hàng
  • address: Địa chỉ của khách hàng

Hướng dẫn

Triển khai kiến trúc MVC bằng cách định nghĩa các thành phần như sau:

Model:

  • Lớp Customer: Đại diện cho một khách hàng
  • Lớp CustomerDB: Chứa các phương thức để làm việc với CSDL

View:

  • File list.php: Hiển thị danh sách khách hàng, bao gồm: Tên, email, address của khách hàng
  • File add.php: Chứa form thêm một khách hàng mới
  • File edit.php: Chứa form chỉnh sửa một khách hàng
  • File delete.php: Chứa form để xoá một khách hàng
  • File view.php: Hiển thị nội dung chi tiết của một khách hàng

Controller:

  • Lớp CustomerController: Chứa các phương thức để xử lý các thao tác của người dùng

Ngoài ra, file index.php là file sẽ đón nhận tất các các request, phân loại theo các trang và chuyển request đến từng phương thức tương ứng của Controller.

Tạo Database

Tạo bảng customers bao gồm các cột:

  • id: integer – tự tăng
  • name: varchar
  • email: varchar
  • address: varchar
Chức năng 1: Thêm mới khách hàng

Bước 1: Tạo class DBConnection Model

Trong thư mục model tạo class DBConnection  để thực hiện kết nối cơ sở dữ liệu

File model/DBConnection.php

<?php
namespace Model;
use PDO;

class DBConnection
{
  public $dsn;
  public $user;
  public $password;

  public function __construct($dsn, $user, $password)
  {
      $this->dsn = $dsn;
      $this->password = $password;
      $this->user = $user;
  }

  public function connect(){
      return new PDO($this->dsn, $this->user, $this->password);
  }
}

Bước 2: Tạo Class Customer Model đại điện cho một khách hàng

<?php
namespace Model;

class Customer
{
  public $id;
  public $name;
  public $email;
  public $address;

  public function __construct($name, $email, $address)
  {
      $this->name = $name;
      $this->email = $email;
      $this->address = $address;
  }
}

Bước 3: Tạo phương thức create trong file model/CustomerDB thực hiện insert dữ liệu vào database

<?php
namespace Model;

class CustomerDB
{
  public $connection;

  public function __construct($connection)
  {
      $this->connection = $connection;
  }

  public function create($customer){
      $sql = "INSERT INTO 'customers'('name', 'email', 'address') VALUES (?, ?, ?)";
      $statement = $this->connection->prepare($sql);
      $statement->bindParam(1, $customer->name);
      $statement->bindParam(2, $customer->email);
      $statement->bindParam(3, $customer->address);
      return $statement->execute();
  }
}

Bước 4: Trong controller/CustomerController.php tạo 2 phương thức

  • Phương thức khởi tạo __construct() khai báo kết nối cơ sở dữ liệu
  • Phương thức add() trả về view add.php khi method là GET và thực hiện thêm mới khách hàng khi method là POST
<?php
namespace Controller;

use Model\Customer;
use Model\CustomerDB;
use Model\DBConnection;

class CustomerController
{

  public $customerDB;

  public function __construct()
  {
      $connection = new DBConnection("mysql:host=localhost;dbname=manage_customer", "root", "123456");
      $this->customerDB = new CustomerDB($connection->connect());
  }

  public function add()
  {
      if ($_SERVER['REQUEST_METHOD'] === 'GET') {
          include 'view/add.php';
      } else {

          $name = $_POST['name'];
          $email = $_POST['email'];
          $address = $_POST['address'];

          $customer = new Customer($name, $email, $address);
          $this->customerDB->create($customer);
          $message = 'Customer created';
          include 'view/add.php';
      }
  }
}

Bước 5: Tạo form thêm mới khách hàng

Nội dung file view/add.php

<?php
if(isset($message)){
  echo "<p class='alert-info'>$message</p>";
}
?>

<div class="col-12 col-md-12">
  <div class="row">
      <div class="col-12">
          <h1>Thêm mới khách hàng</h1>
      </div>
      <div class="col-12">
          <form method="post">
              <div class="form-group">
                  <label>Tên khách hàng</label>
                  <input type="text" class="form-control" name="name"  placeholder="Nhập tên" required>
              </div>
              <div class="form-group">
                  <label>Email</label>
                  <input type="email" class="form-control" name="email" placeholder="Nhập mail" required>
              </div>
              <div class="form-group">
                  <label>Địa chỉ</label>
                  <input type="text" class="form-control" name="address" placeholder="Nhập địa chỉ" required>
              </div>
              <button type="submit" class="btn btn-primary">Thêm mới</button>
              <button class="btn btn-secondary" onclick="window.history.go(-1); return false;">Hủy</button>
          </form>       
     </div>   
   </div> 
</div>

Bước 6: Điều hướng đến trang add trong trang index.php

<?php
require "model/DBConnection.php";
require "model/CustomerDB.php";
require "model/Customer.php";
require "controller/CustomerController.php";

use \Controller\CustomerController;
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Thêm mới khách hàng</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>

<div class="container">
  <div class="navbar navbar-default">
      <a class="navbar-brand" href="index.php">Customer management</a>
  </div>
  <?php
  $controller = new CustomerController();
  $page = isset($_REQUEST['page'])? $_REQUEST['page'] : NULL;
  switch ($page){
      case 'add':
          $controller->add();
          break;
     case 'delete':
          break;
      case 'edit':
          break;
      default:
          $controller->index();
          break;
  }
  ?>
</div>

</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</html>

Chạy http://localhost/management-customer-mvc/index.php?page=add  chạy và kiểm tra

Chức năng 2: Hiển thị danh sách khách hàng

Bước 1. Trong file model/CustomerDB.php viết hàm getAll() trả về tất cả khách hàng

public function getAll()
{
  $sql = "SELECT * FROM customer";
  $statement = $this->connection->prepare($sql);
  $statement->execute();
  $result = $statement->fetchAll();
  $customers = [];
  foreach ($result as $row) {
      $customer = new Customer($row['name'], $row['email'], $row['address']);
      $customer->id = $row['id'];
      $customers[] = $customer;
  }
  return $customers;
}

Bước 2: Trong file controller/CustomerController.php tạo hàm index gọi đến hàm getAll() và trả về view/list.php

public function index(){
  $customers = $this->customerDB->getAll();
  include 'view/list.php';
}

Bước 3: Tạo view/list.php hiển thị danh sách khách hàng

<h2>Danh sách khách hàng</h2>
<a href="./index.php?page=add">Thêm mới</a>
<table class="table">
  <thead>
  <tr>
      <th>STT</th>
      <th>Name</th>
      <th>Email</th>
      <th>Adress</th>
  </tr>
  </thead>
  <tbody>
  <?php foreach ($customers as $key => $customer): ?>
  <tr>
      <td><?php echo ++$key ?></td>
      <td><?php echo $customer->name ?></td>
      <td><?php echo $customer->email ?></td>
      <td><?php echo $customer->address ?>
  <?php endforeach; ?>
  </tbody>
</table>

Bước 4: Điều hướng cho ứng dụng trong file index.php

<?php
$controller = new CustomerController();
$page = isset($_REQUEST['page'])? $_REQUEST['page'] : NULL;
switch ($page){
  case 'add':
      $controller->add();
      break;
 case 'delete':
      break;
  case 'edit':
      break;
  default:
      $controller->index();
      break;
}
?>

Chạy http://localhost/management-customer-mvc/ để xem kết quả

Chức năng 3: Xóa một khách hàng

Bước 1: Tạo hàm get() để lấy ra khách hàng theo id và hàm delete() trong file model/CustomerDB để xóa một khách hàng

public function get($id){
  $sql = "SELECT * FROM customer WHERE id = ?";
  $statement = $this->connection->prepare($sql);
  $statement->bindParam(1, $id);
  $statement->execute();
  $row = $statement->fetch();
  $customer = new Customer($row['name'], $row['email'], $row['address']);
  $customer->id = $row['id'];
  return $customer;
}

public function delete($id){
  $sql = "DELETE FROM customer WHERE id = ?";
  $statement = $this->connection->prepare($sql);
  $statement->bindParam(1, $id);
  return $statement->execute();
}

Bước 2: Trong file controller/CustomerController.php tạo hàm delete để gọi đến hàm delete trong model

public function delete()
{
  if ($_SERVER['REQUEST_METHOD'] === 'GET') {
      $id = $_GET['id'];
      $customer = $this->customerDB->get($id);
      include 'view/delete.php';
  } else {
      $id = $_POST['id'];
      $this->customerDB->delete($id);
      header('Location: index.php');
  }
}

Bước 3: Tạo view/delete.php

<h1>Bạn chắc chắn muốn xóa khách hàng này?</h1>
<h3><?php echo $customer->name; ?></h3>
<form action="./index.php?page=delete" method="post">
  <input type="hidden" name="id" value="<?php echo $customer->id; ?>"/>
  <div class="form-group">
      <input type="submit" value="Delete" class="btn btn-danger"/>
      <a class="btn btn-default" href="index.php">Cancel</a>
  </div>
</form>

Bước 4: Cập nhật view/list.php để gọi đến hàm delete() khách hàng

<h2>Danh sách khách hàng</h2>
<a href="./index.php?page=add">Thêm mới</a>
<table class="table">
  <thead>
  <tr>
      <th>STT</th>
      <th>Name</th>
      <th>Email</th>
      <th>Adress</th>
      <th></th>
  </tr>
  </thead>
  <tbody>
  <?php foreach ($customers as $key => $customer): ?>
  <tr>
      <td><?php echo ++$key ?></td>
      <td><?php echo $customer->name ?></td>       
      <td><?php echo $customer->email ?></td>       
      <td><?php echo $customer->address ?></td>       
      <td> <a href="./index.php?page=delete&id=<?php echo $customer->id; ?>" class="btn btn-warning btn-sm">Delete</a></td>   
  <?php endforeach; ?>   
</tbody> 
</table>

Bước 5: Điều hướng đến trang delete khi người dùng ấn xóa khách hàng trong file index.php

<?php
$controller = new CustomerController();
$page = isset($_REQUEST['page'])? $_REQUEST['page'] : NULL;
switch ($page){
  case 'add':
      $controller->add();
      break;
  case 'delete':
      $controller->delete();
      break;
  case 'edit':
      break;
  default:
      $controller->index();
      break;
}
Chức năng 4: Update một khách hàng

Bước 1: Tạo hàm update() trong file model/CustomerDB để update thông tin khách hàng

public function update($id, $customer){
  $sql = "UPDATE customer SET name = ?, email = ?, address = ? WHERE id = ?";
  $statement = $this->connection->prepare($sql);
  $statement->bindParam(1, $customer->name);
  $statement->bindParam(2, $customer->email);
  $statement->bindParam(3, $customer->address);
  $statement->bindParam(4, $id);
  return $statement->execute();
}

Bước 2: Trong file controller/CustomerController.php tạo hàm edit để gọi đến hàm update trong model

public function edit()
{
  if ($_SERVER['REQUEST_METHOD'] === 'GET') {
      $id = $_GET['id'];
      $customer = $this->customerDB->get($id);
      include 'view/edit.php';
  } else {
      $id = $_POST['id'];
      $customer = new Customer($_POST['name'], $_POST['email'], $_POST['address']);
      $this->customerDB->update($id, $customer);
      header('Location: index.php');
  }
}

Bước 3: Tạo view/edit.php

<h2>Cập nhật thông tin khách hàng</h2>
<form method="post" action="./index.php?page=edit">
  <input type="hidden" name="id" value="<?php echo $customer->id; ?>"/>
  <div class="form-group">
      <label>Name</label>
      <input type="text" name="name" value="<?php echo $customer->name; ?>" class="form-control"/>
  </div>
  <div class="form-group">
      <label>Email</label>
      <textarea name="email" class="form-control"><?php echo $customer->email; ?></textarea>
  </div>
  <div class="form-group">
      <label>Address</label>
      <textarea name="address" class="form-control"><?php echo $customer->address; ?></textarea>
  </div>
  <div class="form-group">
      <input type="submit" value="Update" class="btn btn-primary"/>
      <a href="index.php" class="btn btn-default">Cancel</a>
  </div>
</form>

Bước 4: Thêm link update thông tin khách hàng tại tranh danh sách khách hàng

<h2>Danh sách khách hàng</h2>
<a href="./index.php?page=add">Thêm mới</a>
<table class="table">
  <thead>
  <tr>
      <th>STT</th>
      <th>Name</th>
      <th>Email</th>
      <th>Adress</th>
      <th></th>
      <th></th>
  </tr>
  </thead>
  <tbody>
  <?php foreach ($customers as $key => $customer): ?>
  <tr>
      <td><?php echo ++$key ?></td>
      <td><?php echo $customer->name ?></td>
      <td><?php echo $customer->email ?></td>
      <td><?php echo $customer->address ?></td>
      <td> <a href="./index.php?page=delete&id=<?php echo $customer->id; ?>" class="btn btn-warning btn-sm">Delete</a></td>
      <td> <a href="./index.php?page=edit&id=<?php echo $customer->id; ?>" class="btn btn-sm">Update</a></td>
  <?php endforeach; ?>
  </tbody>
</table>

Chạy ứng dụng và quan sát kết quả.

Như vậy chúng ta đã hoàn thành được các tính năng cơ bản của ứng dụng quản lý khách hàng.

Qua bài tập trên chúng ta đã luyện tập:

  • Luyện tập thực hành với MVC
  • Luyện tập chức năng thêm, sửa, xóa đơn giản

Mã nguồn đầy đủ của ứng dụng có thể tham khảo ở đây: https://github.com/codegym-vn/php-management-customer-mvc/

Trên đây CodeGym đã cùng với bạn luyện tập phát triển các ứng dụng quản lý sử dụng kiến trúc MVC. Hãy chụp ảnh màn hình và nộp bài thực hành của bạn trên CodeGymX để cùng nhau luyện tập nhé!

Download - Giáo trình thuật toán

4 + 11 =

Tags:

0 Lời bình

Gửi Lời bình

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

BÀI VIẾT LIÊN QUAN

BẠN MUỐN HỌC LẬP TRÌNH?

GỌI NGAY

098 953 44 58

Đăng ký tư vấn lộ trình học lập trình

Đăng ký tư vấn, định hướng lộ trình học và giải đáp các thắc mắc về ngành nghề – Miễn phí – Online.

5 + 3 =

TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM
TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM