1

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

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

这是一个有两个的链条filterBy。有用。

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

这是怎么做的?

也许你可以玩这个代码?

chain 只是一个随机数,可用于创建 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');
4

2 回答 2

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'and传递'a_value1'给第一次调用filterBy而不是'a_key'and 'a_value',则可以通过删除$suffixandif块并仅附加来简化代码$i

于 2015-05-15T14:24:27.193 回答
1

您不需要生成链接调用列表。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->filterBy()andreturn $this;并删除$result.

于 2015-05-15T14:26:18.173 回答