Setting Up Multiple Classes to Represent Real-World Objects
PHP: If I have a customer class, and the customer can have a car and an invoice, and I want to have separate car and invoice classes, what is the most efficient way of setting them up?
So, I have three different clas开发者_如何学运维ses:
customer.class.php
customer_car.class.php
customer_invoice.class.php
What's the best way to set up the relationship/initialization between the three classes? A customer can have a car or an invoice. I want to keep the code separated so that its easy to maintain.
$customer = new customer();
$car = $customer->newCar();
$invoice = $customer->newInvoice();
?
Here is just an idea as it may be structure differently to reflect your business logics...
Have 3 seperate classes customer
, car
and invoice
.
Customers
can can zero to many cars
to them.
Customer
can have zero to many invoices
to them.
An invoice
may belong to 1 and only 1 customer
and able to have 1 to many cars
.
Illustration of a customer class:
class Customer
{
var $cars = array();
var $invoices = array();
function Customer() { }
function OwnCar($car)
{
$cars[] = $car;
}
function OwnInvoice($invoice)
{
$invoices[] = $invoice;
}
}
Illustration of usage:
$customerA = new Customer();
$carA = new Car();
$invoiceA = new Invoice($customerA, array($carA));
$customerA->OwnCar($carA);
$customerA->OwnInvoice($invoiceA);
Note: Illustration code is in PHP4, where you may feel free (also recommanded) to develop with PHP5 syntax.
why not
$customer = new customer();
$car = new car();
$invoice = new invoice();
$car->SetOwner($customer);
$invoice->SetCustomer($customer);
Think about adding a new item, such as Payment
. How much additional work is necessary with your approach vs. mine. This sounds like a homework problem, so I won't spell it out.
None of the three classes are related at all. so the simple answer is in the question. Create two variables within the customer class that can hold a car class and an invoice class.
Remember within OOP use the ISA HASA relationships in other words the customer is not a car nor an invoice but the customer has a car and an invoice so in both cases it matches HASA.
The customer ISA person though so you could extend the customer class from a person class.
class customer extends person {
private $invoice; // variable to hold invoice
private $car; // variable to hold car
...
}
DC
精彩评论