anijam
anijam

Reputation: 351

communication between instances of classes

I have a loop that creates 1-* instances of classes. All classes are a child class of one abstract class, so they all respond the same, though they do different things. This loop runs 3 times: create, validate, run. However, I'm running into business logic between the classes. If is created, cannot run. If is created, must run. Currently, all these checks are in the loop itself and it's getting messy and making it less flexible than my original idea.

Q: Is there any way to move the business logic INTO the class's validation function?

class Parent{
    abstract function validate();
    abstract function run();
}

class A extends Parent{
    function validate(){/*validation*/}
    function run(){/*what A does*/}
}

class B extends Parent{
    function isClassAthere(){}
    function validate(){
       // validation
       if($this->isClassAthere()) return FALSE; // this is the one I want
    }
    function run(){/*what B does*/}
}

class C extends Parent{
    function isClassBthere(){}
    function validate(){
       // validation
       if($this->isClassBthere()) return TRUE;
    }
    function run(){/*what C does*/}
}

all called by

foreach( $classnames as $index=>$name ){
    $instances[$index] = new $name();
    if(!$instances[$index]->validate()) return FALSE;
    // Business logic is here, I want to move it to validate()
}
foreach( $instances as $instance ){
    $instance->run();
}

Upvotes: 0

Views: 547

Answers (2)

willoller
willoller

Reputation: 7330

Maybe you should move the validation out of the classes. If you separate the concerns into objects which do work, and objects which tell them to do work, then you may have what you want.

class A{}

class B{}

class ABValidator{
    public function validate($instances = array())
}

ABValidator::validate(array(
    new A(),
    new B(),
));

Upvotes: 1

lordvlad
lordvlad

Reputation: 5347

you could try and save all created instances as static properties of the parent class

class B{
  // static properties are accessible
  // though no instance of the class
  // has been created yet
  static public instances = array();

  // php magic function __construct
  // gets called every time an object
  // of this class gets created
  public function __construct(){
    B::instances[] = $this;
  }
  ..
}

class C{
  ...
  public function validate(){
    // as said before, B::instances
    // is available, even if there is no
    // object of class B.
    return ( count(B::instances) > 0 ) ? true : false;
  }

Upvotes: 2

Related Questions