views:

96

answers:

1

I have a search class that I am using to fetch results from two different sources and combine them together. The Search class is the parent and has two children A and B which extend Search.

In the Search class, I have a method called fetch() which instantiates the two child objects to get their results. It looks something like this:

public function fetch(){
  $a = new A($this);
  $a_results = $a->fetch();

  $b = new B($this);
  $b_results = $b->fetch();

  // code to combine the results here
}

The constructor of class A and B both look like this:

class A extends Search
{
    public function __construct(Search $search){
      parent::__construct($search->category, $search->offset, $search->keywords...);
    }

It feels like I'm doing something wrong in that I'm passing a parent object to a child and then creating another parent object with the exact same data. Is there a better way to set this up?

I have it set this way because some parts of my application need to access class A and B directly, rather than through the parent Search class.

+2  A: 

Use composition, for example have the Search class to have an array of sources, where each source is an instance of a Source class where you define what's common to a source and pass the parameters for each A and B sources.

The idea here, in case it's not clear, is for the Source class to return the data from the sources and let the Search class do the search. How practical or efficient this is depends on the actual source and way of searching

class Search {
    private $sources = array();

    public Search($p1,$p2,$p3,$p4) {
        //Use proper parameters to define the sources
        $sources[] = new Source("A",$p1,$p2,$p3,$p4);
        $sources[] = new Source("B",$p1,$p2,$p3,$p4);
    }
    public function fetch() {
        foreach ($source in $sources) {
             $results[] = $source->fetch();
        }
        combine($results);
    }
}


class Source {
    //Whatever you need to define the source
    public function fetch() {
        //Fetch from the proper source
    }
    public Source($name,$p1,$p2,$p3,$p4) {
         //Store the parameters to be able to operate
    }
}
Vinko Vrsalovic