簡體   English   中英

如何使用抽象 class 實現多態性,用於在 php 中獲取、保存和刪除三種不同的產品類型

[英]how to implement polymorphism using abstract class for getting, saving and deleting three different product types in php

如何使用抽象 class 實現多態性來處理三種不同產品類型的產品保存、刪除和顯示? 共有三種產品類型DVDFurnitureBook

下面的代碼是我的產品 model

class Product
{
private $db;

public function __construct()
{
    $this->db = new Database;
}

public function getProducts()
{
    $this->db->query("SELECT * FROM products ORDER BY ID ASC");
    return $this->db->__get('resultSet');
}

public function findProductsBysku($data)
{

    $this->db->query('SELECT * FROM products WHERE sku = :sku');
    //Bind values
    $this->db->bind(':sku', $data['sku']);

    //get products
    return $this->db->__get('resultSet');

}

public function insertProducts($data)
{

    $this->db->query('INSERT INTO products (sku, name, price, size, height, width, length, weight) VALUES (:sku, :name, :price, :size, :height, :width, :length, :weight)');
    // Bind values
    $this->db->__set(':sku', $data['sku']);
    $this->db->__set(':name', $data['name']);
    $this->db->__set(':price', $data['price']);
    $this->db->__set(':size', $data['size']);
    $this->db->__set(':height', $data['height']);
    $this->db->__set(':width', $data['width']);
    $this->db->__set(':length', $data['length']);
    $this->db->__set(':weight', $data['weight']);
    // execute
    if ($this->db->execute()) {
        $response = array("message" => "The product added", "ResultStatus" => 200);
        return json_encode($response);
    }
}

public function deleteProduct($id)
{
    $this->db->query('DELETE FROM products WHERE id = :id');
    // Bind values
    $this->db->bind(':id', $id);
    // Execute
    if ($this->db->execute()) {
        return true;
    } else {
        return false;
    }
  }
}

我在名為AddProductProducts的兩個控制器中使用它:

添加產品

 class Addproduct extends Controller
{
public $productModel;
public function __construct()
{

    $this->productModel = $this->model('Product');

}

public function index()
{
    /* Allow cors */
    header('Access-Control-Allow-Origin: *');

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        $data = [
            'sku' => $_POST['sku'],
            'name' => $_POST['name'],
            'price' => $_POST['price'],
            'size' => $_POST['size'],
            'height' => $_POST['height'],
            'width' => $_POST['width'],
            'length' => $_POST['length'],
            'weight' => $_POST['weight']
        ];

        /* Find product by sku */
        $productsBysku = $this->productModel->findProductsBysku($data);
        /* Check if product already exist */
        if (count($productsBysku) > 0) {
            $response = array("message" => "The product already exist", "ResultStatus" => 500);
            echo json_encode($response);
        } else {
            /* insert product */
            $res = $this->productModel->insertProducts($data);
            echo $res;
        }

    }

  }
 }

產品:

class Products extends Controller
 {
  public $productModel;
  public function __construct()
{
    $this->productModel = $this->model('Product');
}

public function index($id)
{
    /* Allow cors */
    header('Access-Control-Allow-Origin: *');

    //load products
    $products = $this->productModel->getProducts();
    $this->view('pages/index', ['Products' => $products]);

}

public function MassDelete() {
    /* Allow cors */
    header('Access-Control-Allow-Origin: *');

    //handle mass delete request
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $ids = $_POST['id'];
        foreach ($ids as $id) {
            $this->productModel->deleteProduct($id);
        }
    }

    //load products
    $products = $this->productModel->getProducts();
    $this->view('pages/index', ['Products' => $products]);
    
   }
 }

我必須將產品 model 分解為每種類型的不同類別,產品 model 是它們的基礎 class,另一個重要說明是我不應該使用任何條件語句來處理產品類型

只需創建一個抽象 class,並從中擴展。 然后在你的 controller class 中,簡單地操作那個 class,而不是它的孩子。

abstract class Product {
    public function __construct(
        private string $sku,
        private string $name
    ) {}

    public function getSku(): string
    {
        return $this->sku;
    }
}

class DVDProduct extends Product {
    public function __construct(
        private string $sku,
        private string $name,
        private float $rottenTomatosRating
    ) {
        parent::__construct($sku, $name);
    }

    public function getRottenTomatosRating(): float
    {
        return $this->rottenTomatosRating;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM