views:

51

answers:

1

I have an object that loads an instance of another object in a method.

$survey   = new survey;

$question = new question($survey);

$question->load($question_id);

class question  {

public function __construct(&$survey)
{   
    $this->survey = $survey;
}   

public function load ($id)
{   
    // now a question is loaded
    // want to load the survey that this question is in
    $this->survey->load($this->get('survey_id')); // ** survey_id is a field in the questions table
    // now $this->survey object has all the info about the survey this question is in
}   

private function get($name)
{   
    // returns $name, if isset() from array that load() sets
}    }

This is frying my brain, though, because it seems like $survey should come into $question already being a complete object. But, how do I do that, if I don't know what survey_id to load until I'm in the object? I am revamping a site and the most complex part is littered with this issue. TIA - Hans.

+1  A: 

Edit: I just noticed you mentioned that you're encountering this in existing code. What I've said below may still apply to solving your problem, but it might not actually be of immediate constructive use. :) Unfortunately we'd need to see a lot more code to help you with your problem, as what you've shown us so far is bizarre.


You seem to have constructed your classes inside out.

Surveys are normally defined as sets of questions.

Therefore, shouldn't your Survey class contain and reference Questions, not the other way around?

You can store their relationship in a link table, which will allow Surveys to look up their Questions, while also allowing Questions to look up which Surveys they're in. Create accessor methods in each class to look up the dependency in the link table and return either IDs for the objects, or objects themselves. This method makes the objects less closely tied together.

(Extending this to users answering questions, things get more interesting. If I was doing this, I'd create a class for each user's Response (each user gets one Response), which contains Answers. The Response references the Survey, the Answers each reference a Question.)

This probably isn't a case where dependency injection is applicable. DI is most often used when the actual class of the object being passed may change, or when an outside force can control what object can be passed in. Do you ever expect that Surveys will contain things that aren't Questions? Or that Questions will ever exist inside something that isn't a Survey? Or that a force outside of either something related to Surveys or Questions will manipulate a Question? If you answered "no" to these, then DI is probably not what you want here.

Charles
Okay, thanks. That helps a lot. I'll think about building it the other direction and passing $questions in the other direction.
Hans