【问题标题】:Passing properties from a child object to the parent PHP将属性从子对象传递给父 PHP
【发布时间】:2013-03-19 22:01:44
【问题描述】:

我过去曾使用 cakePHP,并且喜欢他们构建模型系统的方式。我想结合他们在扩展模型之间处理验证的想法。

这是一个例子:

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

this 的问题是模型无法获取验证规则,因为它是父类。有没有一种方法可以将 $validation 属性传递给父类,而无需通过 create_user() 方法作为参数显式传递验证规则?

编辑:

另外,避免通过 __construct() 方法将其传递给父类。是否有另一种方法不会在我的用户类中导致大量额外代码但让模型类完成大部分工作(如果不是全部?)

【问题讨论】:

    标签: php oop class inheritance


    【解决方案1】:

    如果实例是$user,则可以在model::insert()中简单引用$this->validation

    在这种情况下,model 似乎也应该是 abstract,从而防止实例化并可能造成混淆。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2021-10-18
        • 2018-09-17
        • 1970-01-01
        • 2021-06-28
        • 2015-10-27
        • 2018-01-15
        • 2019-10-27
        • 1970-01-01
        相关资源
        最近更新 更多