3

I am mapping Field1 to Field2. The map object instantiates the field object and vice versa, creating an infinite loop.

This is in PHP.

class field {
  protected $maps; // mapCollection object. all the mappings of this field to others

}

class map {
  protected $field1; // field object
  protected $field2; // field object
}

class mapCollection {
  protected $maps; // array of map objects
}

The mappings and fieldsets are stored in a database where they each have a unique ID. So I decided to allow fetching them using their ids in the constructors.

class field {
  protected $maps; // map object
  public __construct($id = 0 ) {
    if(!empty($id) ) {
      $this->maps = // get mapsCollection. data from db
    }
  }

}

class map {
  protected $field1; // field object
  protected $field2; // field object
  public __construct($id = 0 ) {
    if(!empty($id) ) {
      $this->field1 = // get field1 data from db
      $this->field2 = // get field2 data from db
    }
  }
}

class mapCollection {
  protected $maps; // array of map objects
  public __construct($field_id) {
    // get maps from db by field id
    foreach($dbdata as $map_id) {
      $this->maps[] = new map($map_id); // instantiates new map, which instantiates new field, etc
    }
  }
}

How should I be doing this?

18
  • How about "don't use ORM".
    – mefisto
    Commented May 15, 2014 at 7:54
  • 1
    @teresko I have a mysql database. I have to access it somehow, right? Commented May 15, 2014 at 16:25
  • 1
    Sure. Write a data mapper. You do not need ORM to assess MySQL. Unless, of course, you cannot write any SQL.
    – mefisto
    Commented May 15, 2014 at 16:26
  • 1
    @teresko: What do you have against ORM's? :P Commented May 15, 2014 at 17:09
  • 1
    If all you have is a hammer, every problem looks like a nail.
    – mefisto
    Commented May 15, 2014 at 21:12

1 Answer 1

4

It is called a circular dependency. Typically the way you resolve them is you have an unbiased third party create both A and B then introduce them to one another. This should break the infinite loop and allow things to progress.

Another option is give both your field and map class a constructor that takes the other object as a parameter. Now only load from the database if you don't get what you are looking for passed in.

1
  • 1
    I'm thinking perhaps my third-party would use the "builder pattern." I guess I'll not have the circular dependencies in the constructor. The builder will (somehow?) know which objects to create and then throw them together. Voila. I'm new to design patterns. But my application is getting too complex for me to just keep hacking away at it without a grander scheme. Commented May 15, 2014 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.