Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用于创建对象集合的各种输入的设计模式_Php_Design Patterns_Factory Pattern - Fatal编程技术网

Php 用于创建对象集合的各种输入的设计模式

Php 用于创建对象集合的各种输入的设计模式,php,design-patterns,factory-pattern,Php,Design Patterns,Factory Pattern,假设我有以下简单的类 <?php class Variable { private $variableName; private $variableValue; public function __construct($name, $value) { $this->variableName = $name; $this->variableValue = $value; } } 另外,假设我正在使用一个

假设我有以下简单的类

<?php
class Variable
{
    private $variableName;
    private $variableValue;

    public function __construct($name, $value)
    {
        $this->variableName  = $name;
        $this->variableValue = $value;
    }
}
另外,假设我正在使用一个非常不一致的API来导入一组变量名和值。API返回JSON,但它实际上可能是任何东西

我说API是不一致的,因为根据您的URI,变量对象可能返回以下格式的
$raw
数据:

{  
    "variables" : [  
        {  
            "name" : "variable_one",
            "value" : "foo"
        },
        {
            "name" : "variable_two",
            "value" : "bar"
        }
    ]
}
{  
   "dataObject" : {  
      "variable_one" : "foo",
      "variable_two" : "bar"
   }
}
或者,
$raw
数据可以采用以下格式:

{  
    "variables" : [  
        {  
            "name" : "variable_one",
            "value" : "foo"
        },
        {
            "name" : "variable_two",
            "value" : "bar"
        }
    ]
}
{  
   "dataObject" : {  
      "variable_one" : "foo",
      "variable_two" : "bar"
   }
}
此外,这个API仍在成熟,我可以预见他们将来会对变量数据的
$raw
格式做出不可预测的更改

下面是我当前使用
$raw
数据来获取
变量
对象集合的解决方案:

<?php
    // Turn JSON into stdObject
    $variableData = json_decode($raw);

    // Collection object to hold the variables
    $variables = new Collection()


    if ( property_exists($variableData, 'variables') ) {
        foreach ( $variableData as $variable ) {

            // Use for the first type of JSON
            $variables->addItem(
                new Variable($variable->name, $variable->value)
            );

        }
    } else {
        foreach ($variableData as $key => $value) {

            // Use for the second type of JSON
            $variables->addItem(new Variable($key, $value);

        }
    }

为了避免if语句的混乱,可以使用Visitor模式。本质上,if语句的每个分支都包装在一个函数中。每个函数都有两个参数:一个“指令”和一个对象。如果函数“识别”了指令,它会对对象做一些事情。否则它会自动返回

您可以创建这些“访问者”函数的数组,并为输入数据中的每个元素循环它们

这是一个简单的解释(我正在打电话),但希望它能为你指明正确的方向