how can I implement polymorphism using an abstract class for handling product saving, deleting, and showing for three different product types? there are three product types: DVD, Furniture, and Book
The below code is my product 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;
}
}
}
I use it inside my two controllers called AddProduct and Products:
Addproduct:
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;
}
}
}
}
Products:
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]);
}
}
I have to break down Product model into different classes per type with product model being their base class and one other important note is I should not use any conditional statement for handling product types
CodePudding user response:
Just create an abstract class, and extend from it. Then in your controller class, simply operatate on that class, instead of its children.
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;
}
}
CodePudding user response:
To implement polymorphism for handling product saving, deleting, and showing for three different product types (DVD, Furniture, and Book) is to use an abstract class with abstract methods for each of the mentioned operations.
Here is an example of how you can implement this in PHP:
abstract class Product {
abstract public function save();
abstract public function delete();
abstract public function show();
}
class DVD extends Product {
public function save() {
// Code to save a DVD product
}
public function delete() {
// Code to delete a DVD product
}
public function show() {
// Code to show a DVD product
}
}
class Furniture extends Product {
public function save() {
// Code to save a Furniture product
}
public function delete() {
// Code to delete a Furniture product
}
public function show() {
// Code to show a Furniture product
}
}
class Book extends Product {
public function save() {
// Code to save a Book product
}
public function delete() {
// Code to delete a Book product
}
public function show() {
// Code to show a Book product
}
}
In this example, the Product class is an abstract class that defines the abstract methods save(), delete(), and show(). These methods must be implemented by any concrete subclass of Product, such as DVD, Furniture, or Book.
You can then use these concrete classes in your code to perform the corresponding operations on each type of product:
$dvd = new DVD();
$dvd->save();