2013-03-19 105 views
1

我已经和cakePHP一起工作过,并且喜欢他们构建模型系统的方式。我想将他们的想法在扩展模型之间进行处理。将子对象的属性传递给父对象PHP

下面是一个例子:

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 
    } 
} 

与这里的问题是,模型没有得到验证规则,因为它的父类的方法。有没有一种方法可以将$ validation属性传递给父类,而无需通过将create_user()方法作为参数来明确地传递验证规则?

编辑:

此外,避免了经由__construct()方法的父类传递给它。是否有另外一种方法可以做到这一点,这不会在我的用户类中导致大量额外的代码,但让模型类可以完成大部分工作(如果不是全部?)

回答

1

如果实例是$user,您可以请参阅model::insert()中的$this->validation

在这种情况下,看起来model也应该是abstract,防止实例化并且可能混淆。

0

model类中创建一个新的抽象方法,该类名为:isValid()每个派生类必须实现,然后在insert()函数期间调用该方法。

model类:

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 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; 
    } 
} 
}