Understanding how to inject object dependencies
Posted
by Hans
on Stack Overflow
See other posts from Stack Overflow
or by Hans
Published on 2010-06-12T01:03:39Z
Indexed on
2010/06/12
1:13 UTC
Read the original article
Hit count: 397
php
|dependency-injection
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 $response 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.
© Stack Overflow or respective owner