tags:

views:

47

answers:

3

I have a class called Report. I have several classes that inherit from report, ClientReport, ClientVisitReport...

class Report {
    ...
    public function load($id) {
        ...
    }
}

class ClientReport extends Report {
    ...
    public function load($id) {
       parent::load($id);
       ...
    }
}

class ClientVisitReport extends Report {
    ...
    public function load($id) {
        parent::load($id);
        ...
    }
}

I want to be able to call the proper constructor from the id I give to the load method. Each id has its own class of report.

Basically I'm asking how I could do this :

$reportObject = new Report(); // reportObject is a Report
$reportObject->load(15678); // report 15678 is a ClientReport, $reportObject is now a ClientReport

How do I do that ? I may be wrong in my design, is there a better way to do what I want ?

+3  A: 

You might want to look into the AbstractFactory pattern. One of it's purposes is to

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

There is PHP examples at the bottom of the linked page.

Gordon
@Gordon: +1 for AbstractFactory pattern :)
Sarfraz
A: 

Changing the class the class of an object doesn't sound like a good idea (, if even possible. It's not in most of the languages.)

I would use the Prototype design pattern for this, along with a hash map to store the report numbers/types.

So the code in the end would be:

$reportObject = $reportTypes[15678]->clone();

See this for more details and examples.

shinjin
*(further reading)* http://sourcemaking.com/design_patterns/prototype
Gordon
A: 

One way that could help is to have a ReportLoader class where you keep the Load behavior and decide on the type of the report object you are going to create. This way The report will have reporting responsibility and Loader will have loading the correct data into the correct object responsibility.

derdo