Как в родительском классе указать не сколько таблиц для методов? Пишу не большой Product List с функциями CRUD. Реализовал это всё в процедурном стиле, сейчас переделываю на ООП вариант. Есть родительский класс в нем указаны методы CRUD, и общие параметры дочерних классов! Каждый дочерний класс работает со своей таблицей, + у них есть свои дополнительные параметры характерны только им. Как реализовать все CRUD методы в родительском классе.
Родительский класс Product.php class Product implements ProductInterface {
private $conn;
protected $table_name;
public $id;
public $sku;
public $img;
public $name;
public $description;
public $price;
public function __construct($db){
$this->conn = $db;
$this->table_name = "Books";
}

public function readAll(){
$query = "SELECT * FROM " . $this->table_name . " ORDER BY id DESC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
function readOne(){
$query = "SELECT sku, name, img, author, price, weight, description FROM " . $this->table_name . "
WHERE id = ? LIMIT 0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//data that will be executed in `book_id`
$this->sku = $row['sku'];
$this->name = $row['name'];
$this->img = $row['img'];
$this->author = $row['author'];
$this->description = $row['description'];
$this->weight = $row['weight'];
$this->price = $row['price'];
}
function create(){
//query for creating new book in table
$query = "INSERT INTO " . $this->table_name . " (sku, name, author, description, price, weight)" .
"VALUES ('{$this->sku}','{$this->name}','{$this->author}','{$this->description}','{$this->price}','{$this->weight}');";
$stmt = $this->conn->prepare($query);
// posted values
$this->sku=htmlspecialchars(strip_tags($this->sku));
$this->name=htmlspecialchars(strip_tags($this->name));
$this->author=htmlspecialchars(strip_tags($this->author));
$this->description=htmlspecialchars(strip_tags($this->description));
$this->price=htmlspecialchars(strip_tags($this->price));
$this->weight=htmlspecialchars(strip_tags($this->weight));
// bind values
$stmt->bindParam(":sku", $this->sku);
$stmt->bindParam(":name", $this->name);
$stmt->bindParam(":author", $this->author);
$stmt->bindParam(":description", $this->description);
$stmt->bindParam(":price", $this->price);
$stmt->bindParam(":weight", $this->weight);
if($stmt->execute()){
return true;
}else{
return false;
}
}
function delete(){
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
if($result = $stmt->execute()){
return true;
}else{
return false;
}
}
}
В родительском методе сейчас методы характерны для класса books.php в этом классе остались только параметрыrequire_once 'Product.php';
class books extends Product {
public $author;
public $weight;
Но есть ещё два класса с продуктами dvd и furniture, с такими же методами CRUD только дополнительно со своими параметрами.class dvd extends Product {
// database connection and table name
private $conn;
protected $table_name = "dvd";
// object properties
public $capacity;
public function __construct($db){
$this->conn = $db;
}
//query to read all notes from `dvd` table
function readAll(){
$query = "SELECT * FROM " . $this->table_name . " ORDER BY id DESC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
//query to read one dvd and all data of it by `id` from `dvd` table
function readOne(){
$query = "SELECT sku, name, img, price, description, capacity FROM " . $this->table_name . "
WHERE id = ? LIMIT 0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//data that will be executed in `dvd_id`
$this->sku = $row['sku'];
$this->name = $row['name'];
$this->img = $row['img'];
$this->description = $row['description'];
$this->price = $row['price'];
$this->capacity = $row['capacity'];
}
// query to create new dvd
function create(){
//query for creating new book in table
$query = "INSERT INTO `dvd` (scu, name, description, price, capacity)" .
"VALUES ('{$this->sku}','{$this->name}','{$this->description}','{$this->price}','{$this->capacity}');";
$stmt = $this->conn->prepare($query);
// posted values
$this->sku=htmlspecialchars(strip_tags($this->sku));
$this->name=htmlspecialchars(strip_tags($this->name));
$this->description=htmlspecialchars(strip_tags($this->description));
$this->price=htmlspecialchars(strip_tags($this->price));
$this->capacity=htmlspecialchars(strip_tags($this->capacity));
// bind values
$stmt->bindParam(":sku", $this->sku);
$stmt->bindParam(":name", $this->name);
$stmt->bindParam(":description", $this->description);
$stmt->bindParam(":price", $this->price);
$stmt->bindParam(":capacity", $this->capacity);
if($stmt->execute()){
return true;
}else{
return false;
}
}
// query for updating dvd and change dvd data in simple form
function update(){
$query = "UPDATE
" . $this->table_name . "
SET
sku = :sku,
name = :name,
description = :description,
price = :price,
capacity = :capacity
WHERE
id = :id";
$stmt = $this->conn->prepare($query);
// posted values that user can change
$this->sku=htmlspecialchars(strip_tags($this->sku));
$this->name=htmlspecialchars(strip_tags($this->name));
$this->description=htmlspecialchars(strip_tags($this->description));
$this->price=htmlspecialchars(strip_tags($this->price));
$this->capacity=htmlspecialchars(strip_tags($this->capacity));
$this->id=htmlspecialchars(strip_tags($this->id));
// bind parameters
$stmt->bindParam(':sku', $this->sku);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':description', $this->description);
$stmt->bindParam(':price', $this->price);
$stmt->bindParam(':capacity', $this->capacity);
$stmt->bindParam(':id', $this->id);
// execute the query
if($stmt->execute()){
return true;
}
return false;
}
//query to delete the product by id
function delete(){
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->id);
if($result = $stmt->execute()){
return true;
}else{
return false;
}
}
}
Как объединить и реализовать эти общие методы в этих классах?

21 Авг 2019 в 07:00
157 +1
0
Ответы
1

Для объединения и реализации общих методов CRUD в родительском классе и дочерних классах, можно использовать принцип наследования и переопределения методов в дочерних классах.

В родительском классе Product, определите все общие методы CRUD с общими параметрами и основной логикой. Затем в дочерних классах Books, DVD, Furniture переопределите только те методы, которые имеют особенности для каждого конкретного класса.

Вот как можно переопределить методы в дочерних классах:

class Books extends Product {
public $author;
public $weight;
public function __construct($db){
parent::__construct($db);
$this->table_name = "Books";
}
// Методы для Books
}
class DVD extends Product {
public $capacity;
public function __construct($db){
parent::__construct($db);
$this->table_name = "DVD";
}
// Методы для DVD
}
class Furniture extends Product {
public $dimensions;
public function __construct($db){
parent::__construct($db);
$this->table_name = "Furniture";
}
// Методы для Furniture
}

Таким образом, общие методы CRUD будут наследоваться от родительского класса Product, а дочерние классы будут иметь возможность переопределить только те методы, которые отличаются от общих. Такой подход позволит вам избежать дублирования кода и эффективно организовать структуру вашего приложения.

20 Апр в 13:09
Не можешь разобраться в этой теме?
Обратись за помощью к экспертам
Название заказа не должно быть пустым
Введите email
Бесплатные доработки
Гарантированные бесплатные доработки
Быстрое выполнение
Быстрое выполнение от 2 часов
Проверка работы
Проверка работы на плагиат
Интересные статьи из справочника
Поможем написать учебную работу
Название заказа не должно быть пустым
Введите email
Доверьте свою работу экспертам
Разместите заказ
Наша система отправит ваш заказ на оценку 90 161 автору
Первые отклики появятся уже в течение 10 минут
Прямой эфир