mauzilla
mauzilla

Reputation: 3592

Passing properties from a child object to the parent PHP

I've worked with cakePHP in the past and liked the way they built their model system. I want to incorporate their idea of handling validation between extended models.

Here is an example:

 class users extends model {
     var $validation = array(
         "username" => array(
             "rule" => "not_empty"
         ),
         "password" => array(
             "rule" => "valid_password"
         )
     );

     public function create_user() {
         if($this->insert() == true) {
             return true;
         }
     }
 }



 class model {

     public function insert() {
         if(isset($this->validation)) {
             // Do some validation checks before we insert the value in the database
         }
         // Continue with the insert in the database
     }
 }

The problem with the this is that model has no way of getting the validation rules as it's the parent class. Is there a way I can pass the $validation property to the parent class without explicitely passing the validation rules through say the create_user() method as a parameter?

EDIT:

Also, avoiding passing it via the __construct() method to the parent class. Is there another way of doing this which would not cause a lot of extra code within my users class but get the model class to do most of the work (if not all?)

Upvotes: 1

Views: 938

Answers (2)

haim770
haim770

Reputation: 49133

Create a new abstract method in the model class named: isValid() that each derived class will have to implement, then call that method during the insert() function.

model class:

class model {

 abstract protected function isValid();

 public function insert() {
     if($this->isValid())) { // calls concrete validation function

     }
     // Continue with the insert in the database
 }

}

user class:

class users extends model {
 var $validation = array(
     "username" => array(
         "rule" => "not_empty"
     ),
     "password" => array(
         "rule" => "valid_password"
     )
 );

 protected function isValid() {
    // perform validation here
    foreach ($this->validation) { //return false once failed }

    return true;
 }

 public function create_user() {
     if($this->insert() == true) {
         return true;
     }
 }
}

Upvotes: 0

juco
juco

Reputation: 6342

If the instance is a $user, you can simply refer to $this->validation in model::insert().

It would seem that model should also be abstract in this case, preventing instantiation and perhaps confusion.

Upvotes: 1

Related Questions