Пишу не большой Product List с функциями CRUD. Реализовал это всё в процедурном стиле, сейчас переделываю на ООП вариант, и немножко подвис вопрос в голове, как ООП работает. Создал классы под каждый продукт их три штуки, в каждом классе описывается CRUD метод для своего продукта. Сделал общий родительский класс Product, туда добавил общие переменные для всех продуктов и унаследовал их. Создал ProductInterface, куда поместил контракты метод этих продуктов и родительский класс Product implements productInterface
, соответственно, классы-продукты получает эти методы, в IDE появились эти стрелки сбоку. Подскажите, как мне воспользоваться ООП дальше, чтобы увидеть его в действии.
Родительский класс Product.php
require_once 'Interface/ProductInterface.php';
class Product implements productInterface {
private $conn;
private $table_name = "Books";
public $id;
public $sku;
public $img;
public $name;
public $description;
public $price;
public function __construct($db){
$this->conn = $db;
}
public function readAll(){
$query = "SELECT * FROM " . $this->table_name . " ORDER BY id DESC";
$stmt = $this->conn->prepare( $query );
$stmt->execute();
return $stmt;
}
Интерфейс ProductInterface.php
interface productInterface
{
public function readAll();
public function readOne();
public function create();
public function delete();
}
И сам класс продукт допустим Books
require_once 'Product.php';
class books extends Product {
public $author;
public $weight;
// object properties
public function readAll(){
}
//query to read one book and all data of it by `id` from `book` table
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'];
}
// query to create new book
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;
}
}
// query for updating book and change book data in simple form
function update(){
$query = "UPDATE
" . $this->table_name . "
SET
sku = :sku,
name = :name,
author = :author,
price = :price,
weight = :weight,
description = :description
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->author=htmlspecialchars(strip_tags($this->author));
$this->weight=htmlspecialchars(strip_tags($this->weight));
$this->price=htmlspecialchars(strip_tags($this->price));
$this->description=htmlspecialchars(strip_tags($this->description));
$this->id=htmlspecialchars(strip_tags($this->id));
// bind parameters
$stmt->bindParam(':sku', $this->sku);
$stmt->bindParam(':author', $this->author);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':price', $this->price);
$stmt->bindParam(':weight', $this->weight);
$stmt->bindParam(':description', $this->description);
$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;
}
}
}
Может как-то можно наследовать эти методы что бы в каждом классе их не писать, методы readAll и delete вообще не отличаются кроме как таблица другая в базе.
Код реализацие метода readAll.
<?php
// read the books from the database
$books = new Books($db);
$stmt = $books->readAll();
while ($books = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($books);
echo "<div data-price='{$price}' class='item'>";
echo "<a href='book_id.php?id={$id}'><img class='product' src='UI/images/{$img}'></a> ";
echo "<div class='info'>";
echo "<h6 align='center'> <a href='book_id.php?id={$id}'></a>{$name}</h6> ";
echo "<p class='descroption'>ID number: {$id} </p>";
echo "<p class='descroption'>SKU number: {$sku} </p>";
echo "<p class='descroption'>Price: {$price} <i class='glyphicon-euro'></i></p>";
echo "<p class='descroption'>Weight: {$weight} kg</p>";
echo "</div>";
echo "</div>";
}
?>
Жду от вас конструктивной критики и советов.
Кофе для программистов: как напиток влияет на продуктивность кодеров?
Рекламные вывески: как привлечь внимание и увеличить продажи
Стратегії та тренди в SMM - Технології, що формують майбутнє сьогодні
Выделенный сервер, что это, для чего нужен и какие характеристики важны?
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
Напишите вес алгоритм как сделать поддержку русских букв на Fpdf на phpПереводил в afm все равно не работает
Работая с Doctrine2 я заметил, что с ее помощью очень удобно сохранять данные сущностей, однако с выборками нужно существенно повозитьсяПонятно,...