@alxeewldmr
Спам-модератор в ASKFM

Как в родительском классе указать не сколько таблиц для методов?

Пишу не большой 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;
        }
    }

}


Как объединить и реализовать эти общие методы в этих классах?
  • Вопрос задан
  • 143 просмотра
Пригласить эксперта
Ответы на вопрос 1
qonand
@qonand
Software Engineer
Если правильно понимаю у Вас две проблемы:
1. Вы не знаете как считывать данные из параметров дочерних классов и подставлять их в Ваши запросы.
2. Вы не знаете как заполнить данными параметры дочерних классов полученными из SQL-запроса
За подобного рода преобразования должны отвечать дочерние классы, а родительские класс должен только использовать эти преобразования. Соответственно Вам нужно создать два абстрактных метода реализующих для каждого потомка свои механизмы преобразования.

P.S. почитайте про паттерн Active Record, по сути дела Вы пытаетесь его повторить в некой своей интерпретации
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
YCLIENTS Москва
от 200 000 до 350 000 ₽
Ведисофт Екатеринбург
от 25 000 ₽
ИТЦ Аусферр Магнитогорск
от 100 000 до 160 000 ₽