lundi 23 janvier 2017

use always same foreach to call different methods with different number of parameters

I have two methods that iterage over the same structure, first searching for "div" tags and after searching for "tr" tags. They use the same foreach.

public function findClass($nome){
    foreach ($this->conteudo->getElementsByTagName($this->class) as $node) {
        if (preg_match("/" . $nome . "/", $node->getAttribute("class"))) {
            return $node;
        }
    }
}

public function separar($name, $tag){
    foreach ($this->conteudo->getElementsByTagName($this->class) as $node) {
        $aux = array_map($name, explode($tag, $node->textContent));
    }
    return $aux;
}

How make a method call the foreach and the next function with different number of parameters.

I try something like this but have problems in the number of parameters

public function findClass($nome)
{
    return $this->buscar('classe', $nome);
}

public function applyFuncToExplode($function, $tag){
    return $this->buscar('map', $function, $tag);
}

public function buscar($metodo, [$parameters]){
    foreach ($this->conteudo->getElementsByTagName($this->class) as $node) {
        $this->$metodo($node, [$parameters]);
    }
    $this->class = null;
}

public function classe($node, $nome){
    if (preg_match("/" . $nome . "/", $node->getAttribute("class"))) {
        return $node;
    }
}

public function map($node, $function, $tag){
    return array_map($function, explode($tag, $node->textContent));
}

Aucun commentaire:

Enregistrer un commentaire