OOP (korzystne wykorzystanie)
za moje pytaniejak korzystać z OOP w korzystny sposób Jako przykład zakładam KOSZYK, do którego jego właściciel (Tom) mający określony ADRES (NY) może dodać ARTYKUŁY (Rower, Samochód). W końcu drukowany jest BILL zawierający wszystkie te informacje.
Moim problemem jest: jak poradzić sobie z gromadzeniem pożądanych informacji (tutaj: właściciel, miasto, ilość przedmiotów) z kilku obiektów? Ponieważ myślę, że głupotą jest robić to ręcznie, jak to zrobiono poniżej (patrz 4.), prawda? (nawet więcej, ponieważ ilość informacji wzrasta w rzeczywistości)
Więc jaki jest „czysty sposób” na tworzenie rachunku / gromadzenie informacji potrzebnych w tym przykładzie?
<?php
$a = new basket('Tom','NY');
$a->add_item("Bike",1.99);
$a->add_item("Car",2.99);
$b = new bill( $a );
$b->do_print();
1
class basket {
private $owner = "";
private $addr = "";
private $articles = array();
function basket( $name, $city ) {
// Constructor
$this->owner = $name;
$this->addr = new addresse( $city );
}
function add_item( $name, $price ) {
$this->articles[] = new article( $name, $price );
}
function item_count() {
return count($this->articles);
}
function get_owner() {
return $this->owner;
}
function get_addr() {
return $this->addr;
}
}
2.
class addresse {
private $city;
function addresse( $city ) {
// Constructor
$this->city = $city;
}
function get_city() {
return $this->city;
}
}
3.
class article {
private $name = "";
private $price = "";
function article( $n, $p ) {
// Constructor
$this->name = $n;
$this->price = $p;
}
}
4.
class bill {
private $recipient = "";
private $city = "";
private $amount = "";
function bill( $basket_object ) {
$this->recipient = $basket_object->get_owner();
$this->city = $basket_object->get_addr()->get_city();
$this->amount = $basket_object->item_count();
}
function do_print () {
echo "Bill for " . $this->recipient . " living in " . $this->city . " for a total of " . $this->amount . " Items.";
}
}