我使用DomDocument访问一个HTML页面并转换成一个对象,但是每次我都需要使用不同的标记搜索节点。我想要一个以逻辑名作为参数的方法,但是每个逻辑都有不同数量的参数。
public function foo(){
$this->findTag('bar', $parameters);
}
public function findTag($logic, $parameters){
foreach ($this->dom->getElementsByTagName($this->tag) as $node) {
$this->$logic($node, $parameters);
}
}
public function logic1($node, $foo, $bar){
//something with $foo and $bar
}
public function logic2($node, $fooBar){
//something with $fooBar
}这是个糟糕的方法?如何使用不同的标记,在需要从DomObject获得一些信息时,使其成为一个惟一的函数。
在@JustOnUnderMillions评论之后工作
class pei
{
public function classe($nome)
{
$this->findTag('logic1', $nome);
}
public function classe2($porta, $janela)
{
$this->findTag('logic2', $porta, $janela);
}
public function findTag($logic, ...$parameters)
{
$array = [1, 2, 3, 4];
print_r($parameters);
foreach ($array as $node) {
$this->$logic($node, $parameters);
}
}
public function logic1($node, $nome)
{
print_r($node);
print_r($nome);
}
public function logic2($node, $porta)
{
print_r($node);
print_r($porta[0]);
print_r($porta[1]);
}
}
(new pei)->classe('pablito');
(new pei)->classe2('janela1', 'janela2');这是最干净/最干燥的策略来编码这个吗?我想学习后,几个问题与重复。
发布于 2017-01-27 09:09:20
下面是我的一个例子,我从你的问题中学到的规则:
逻辑名作为参数,并使用不同的标记。
class pei
{
/**
* @param $logic array|string [logicname,tagname] or "logicname"
* @param $arguments the argument list for the logic
**/
public function findTag($logic,...$arguments)
{
if(is_array($logic)){
list($logic,$tag)=$logic;
} else {
$tag=$this->tag;//Note: your example dont show where this is coming from!?
}
if(!method_exists($this,$logic)){
throw new Exception("Logic '$logic' not found!");
}
$result=array();
//Note: Is also unclear where and how $this->dom is set!?
foreach ($this->dom->getElementsByTagName($tag) as $node) {
//here we expand the args to $arg0,$arg1,...
$result[]= $this->{$logic}($node,...$arguments);
}
return $result;
}
//logic definitions
public function logic1($node, $arg0){}
public function logic2($node, $arg0, $arg1){}
public function logic3($node, $arg0, $arg1, $arg2){}
}现在我们有一个方法可以根据参数设置委托给另一个方法。
$result = (new pei($Dom))->findTag('logic1','pablito');
$result = (new pei($Dom))->findTag('logic2','janela1', 'janela2');
$result = (new pei($Dom))->findTag(['logic2','tagname'],'janela1', 'janela2');findTag()方法。但这只是一个可以做什么的例子。我会以另一种方式这样做,目前我还不完全了解这里需要什么样的逻辑。我的示例只说明了如何处理和消除对不同参数的子方法的方法调用。
请记住,该示例缺少服务器,比如错误处理。
希望这能给出一个方向。
https://stackoverflow.com/questions/41856285
复制相似问题