【问题标题】:Building chained function calls dynamically in PHP在 PHP 中动态构建链式函数调用
【发布时间】:2015-05-15 14:08:17
【问题描述】:

我使用 PHP(与 KirbyCMS)并且可以创建此代码:

$results = $site->filterBy('a_key', 'a_value')->filterBy('a_key2', 'a_value2');

这是一个包含两个filterBy 的链。它有效。

但是我需要动态构建这样的函数调用。有时可能是两个链式函数调用,有时是三个或更多。

这是怎么做到的?

也许你可以试试这段代码?

链只是一个随机数,可用于创建 1-5 条链。

for( $i = 0; $i < 10; $i ++ ) {
    $chains = rand(1, 5);
}

预期结果示例

示例一,只有一个函数调用

$results = $site->filterBy('a_key', 'a_value');

例子二,很多嵌套函数调用

$results = $site->filterBy('a_key', 'a_value')->filterBy('a_key2', 'a_value2')->filterBy('a_key3', 'a_value3')->filterBy('a_key4', 'a_value4')->filterBy('a_key5', 'a_value5')->filterBy('a_key6', 'a_value6');

【问题讨论】:

  • 你能用你的代码展示一个期望输出的例子吗?
  • 所以如果我理解它,你想多次使用 filterBy 函数来链接价值?因此,如果您将拥有链 4,您想使用 filterBy 4 次?每次都有参数 "a_key" 。 ($chain - 1)?
  • 对 Kirby 不太熟悉,但是将一个数组传递给 filterBy() 而不是将其链接六次不是更有意义吗?
  • 你不能用纯函数做到这一点,但你可以用方法,只要确保每个调用都返回$this
  • @JensTörnell 我可以,但会重复 :)

标签: php function object dynamically-generated kirby


【解决方案1】:
$chains = rand(1, 5)
$results = $site
$suffix = ''
for ( $i = 1; $i <= $chains; $i ++) {
    if ($i != 1) {
        $suffix = $i
    }
    $results = $results->filterBy('a_key' . $suffix, 'a_value' . $suffix)
}

如果您能够将'a_key1''a_value1' 传递给第一次调用filterBy 而不是'a_key''a_value',则可以通过删除$suffixif 块来简化代码并且只是附加$i

【讨论】:

    【解决方案2】:

    您不需要生成链接调用列表。您可以将每个调用的参数放在一个列表中,然后编写一个从列表中获取它们的类的新方法,并使用它们重复调用filterBy()

    我从您的示例代码中假设函数 filterBy() 返回 $this 或与 site 相同类的另一个对象。

    //
    // The code that generates the filtering parameters:
    
    // Store the arguments of the filtering here
    $params = array();
    
    // Put as many sets of arguments you need
    // use whatever method suits you best to produce them
    $params[] = array('key1', 'value1');
    $params[] = array('key2', 'value2');
    $params[] = array('key3', 'value3');
    
    
    //
    // Do the multiple filtering
    $site = new Site();
    $result = $site->filterByMultiple($params);
    
    
    //
    // The code that does the actual filtering
    class Site {
        public function filterByMultiple(array $params) {
            $result = $this;
            foreach ($params as list($key, $value)) {
                $result = $result->filterBy($key, $value);
            }
            return $result;
        }
    }
    

    如果filterBy() 返回$this,那么你不需要工作变量$result;调用$this-&gt;filterBy()return $this; 并删除其他出现的$result

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-13
      • 2012-07-17
      • 2012-01-30
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      相关资源
      最近更新 更多