/
index.php
195 lines (151 loc) · 6.82 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<?php
class ShopProduct implements Chargeable {
private $id;
private $title;
private $producerMainName;
private $producerFirstName;
protected $price;
private $discount;
function __construct($title, $firstName, $mainName, $price){
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
function setId($id){
$this->id = $id;
}
function getProducerFirstNmae(){
return $this->producerFirstName;
}
function getProducerMainName(){
return $this->producerMainName;
}
function setDiscount($num){
$this->discount = $num;
}
function getDiscount(){
return $this->discount;
}
function getTitle(){
return $this->title;
}
function getPrice(){
return ($this->price - $this->discount);
}
function getProducer(){
return $this->producerFirstName.' '.$this->producerMainName;
}
function getSummaryLine(){ // выводим общую базовую информацию
$base = "$this->title ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
return $base;
}
public static function getInstance($id, PDO $pdo){ // ФАБРИКА которая находит товар в БД по id и создаёт обьект нужного типа
$stmt = $pdo->prepare("SELECT * FROM products WHERE id=?"); // подготавливаем выборку по id
$result = $stmt->execute([$id]); // выполняем
$row = $stmt->fetch(); // получаем результат
if(empty($row)){ // проверяем не пуста ли строка
return null;
}
if($row['type'] == "book"){ // проверяем "тип"
$product = new BookProduct( $row['title'],
$row['firstname'],
$row['mainname'],
$row['price'],
$row['numpages']);
}else if($row['type'] == "cd"){ // проверяем "тип"
$product = new CDProduct( $row['title'],
$row['firstname'],
$row['mainname'],
$row['price'],
$row['playlength']);
}else{ // если неизвесный "тип", то применяем родительский класс ShopProduct
$product = new ShopProduct( $row['title'],
$row['firstname'],
$row['mainname'],
$row['price']);
}
$product->setId($row['id']); // назначаем id согласно id из БД
$product->setDiscount($row['discount']); // назначаем скидку согласно скидке из БД
return $product; // возвращаем полученый обьект нужного нам класса
}
}
interface Chargeable { // интерфейс, все классы которые его наследуют, обязаны иметь описанные в нём методы
public function getPrice();
}
class CDProduct extends ShopProduct {
private $playLenght;
public static $coverUrl = "http://";
function __construct($title, $firstName, $mainName, $price, $playLenght){
parent::__construct($title, $firstName, $mainName, $price);
$this->playLength = $playLenght;
}
function getPlayLength(){
return $this->playLength;
}
function getSummaryLine(){
$base = parent::getSummaryLine();
$base .= ": Время звучания - ". $this->playLength;
return $base;
}
}
class BookProduct extends ShopProduct{
private $numPages;
function __construct($title, $firstName, $mainName, $price, $numPages){
parent::__construct($title, $firstName, $mainName, $price);
$this->numPages = $numPages;
}
function getNumberOfPages(){
return $this->numPages;
}
function getSummaryLine(){
$base = parent::getSummaryLine();
$base .= ": ". $this->numPages." стр.";
return $base;
}
function getPrice(){
return $this->price;
}
}
abstract class ShopProductWriter{ // абстрактный класс для сбора обьектов и вывода базовой информации
protected $products = [];
public function addProduct(ShopProduct $shopProduct){ // принимаем обьект класса ShopProduct (или класса который его расширяет)
$this->products[] = $shopProduct; // и дописываем этот обьёкт в массив
}
abstract public function write(); // абстрактный метод (который должен быть реализован классе который его наследует)
}
class XmlProductWriter extends ShopProductWriter { // выводит свойства обьекта в виде XML
public function write(){
$str = '<?xml version="1.0" encoding="UTF-8"?>';
$str .= '<products>';
foreach($this->products as $shopProduct){
$str .= "\t<product title=\"{$shopProduct->getTitle()}\" >";
$str .= "\t\t<summary>";
$str .= "\t\t{$shopProduct->getSummaryLine()}";
$str .= "\t\t</summary>";
$str .= "\t</product>";
}
$str .= "</products>";
print $str;
}
}
class TextProductWriter extends ShopProductWriter { // выводит свойства обьекта в виде текста
public function write(){
$str = "<br>Товары:<br>";
foreach($this->products as $shopProduct){
$str .= $shopProduct->getSummaryLine();
$str .= "<br>";
}
print $str;
}
}
echo "<pre>";
$pdo = new PDO('mysql:host=localhost;dbname=matt','root',''); // инициализируем PDO
$obj = ShopProduct::getInstance(1, $pdo); // создание нового обьекта через фабрику, достаём из БД по id
$cd = new CDProduct('Harakiri', 'Serj', 'Tankian', 100, 120); // создание новго обьекта через конструктор
$text = new TextProductWriter(); // новый обьект класса TextProductWriter()
$text->addProduct($cd); // добавляем в массив обьект $cd
$text->addProduct($obj); // добавляем в массив обьект $obj
$text->write(); // выводим свойства обьектов из массива
echo "</pre>";