1

假设我有一堂课……

类主{

    $prop1 = 2;
    $prop2 = 23;
    ...
    $prop42 = "什么";

    函数 __construct($arg_array) {
        foreach ($arg_array as $key => $val) {
            $this->$key = $val;
            }
        }
    }

说我创造和反对......

$attributes = array("prop1"=>1, "prop2"=>35235, "prop3"=>"test");
$o = new Main($attributes);

如果不由用户提供,则提供默认属性值是显而易见的。但是,如果我想对用户提供的对象属性值实施任意限制怎么办?如果我想强制$prop1int,不小于 1,不大于 5 怎么办。并且,$prop42类型string,不小于 'A',不大于 'Z'?为此,使用任何可能的语言功能或技巧,使脚本尽可能简短和甜美,最干净的方法是什么?

我被困在__construct()根据这样构建的规则数组检查提供的值...

$allowable = 数组(
    “prop1” => 数组(
        '类型' => 'int',
        'allowable_values' => 数组(
            '分钟' => 1,
            '最大' => 5
            )
        ),
    “prop2” => 数组(
        '类型' => 'int',
        'allowable_values' => 数组(
            1、
            235,
            37,
            392,
            13,
            409,
            3216
            )
        ),
    ...
    “prop42” => 数组(
        '类型' => '字符串',
        'allowable_values' => 数组(
            'min' => 'A',
            '最大' => 'Z'
            )
        )
    );

正如您所看到的prop2,我的验证功能开始变得非常混乱,因为我不仅要考虑范围,还要考虑允许值的列表。使用验证代码和这个规则数组,我的脚本变得相当庞大。

问题是,我如何构建我的类或类属性或验证代码或脚本的任何其他方面,使其尽可能简短,以允许属性范围和值强制执行?是否有语言功能或技巧可以更优雅地处理这个问题?我是否已经到达了一堵砖墙,这种语言的极限?是否有其他语言的示例可以轻松实现这一点,可以提供一些线索?

4

2 回答 2

1

getter 和 setter

class Main {
  private $prop1;
  private $prop2;
  private $prop3;

  public function __construct( $p1 , $p2 , $p3 )
  {
    $this->setProp1($p1);
    $this->setProp2($p2);
    $this->setProp3($p3);
  }

  public function setProp1($p1)
  {
    // conditional checking for prop1
    if(!$ok) throw new Exception('problem with prop1');
    $this->prop1 = $p1;
  }

  //.. and so on
}
于 2010-07-02T02:16:08.680 回答
0

前几天我遇到了类似的问题。这是我要做的:

   private $props;
   private $rules; 

   function __construct($params) {

      // or you can get the rules from another file, 
      // or a singleton as I suggested

      $this->rules = array (array('type' => 'range', 'min' => 10, 'max' => 20), 
        array('type' => 'in_set', 'allowed' => array(1,2,3)));

      for ($i=0; $i<count($params); $i++) {

         if ($this->check($params[$i], $this->rules($i))
            $this->props[$i] = $params[$i];
         else
            throw new Exception('Error adding prop ' . $i);
      }

   }


   function check($value, $rule) {
      switch($rule['type']) {
         case 'range':
            return ($rule['min'] <= $value && $value <= $rule['max']);  

         case 'in_set':
            return (in_array($value, $rule['allowed']));

         // and so on
      }
   }

如果你有很多参数,你可以使用一个数组并遍历它。如果您的验证规则总是相同的,您可以将它们放在一个单独的文件中,然后将其加载到您的构造函数或其他任何东西中。

编辑:顺便说一句,在 PHP 中测试类型确实没有意义。这既不是很可靠,也没有必要。

编辑2:您可以使用Singleton,而不是使用带有规则的全局变量:

于 2010-07-02T02:27:42.180 回答