0

私は PHP で HTML クラスに取り組んでいるので、すべての HTML 出力の一貫性を保つことができます。ただし、ロジックに頭を悩ませています。私は PHP で作業していますが、どの言語の回答でも機能します。

クラスにタグを適切にネストさせたいので、次のように呼び出せるようにしたいです。

$html = new HTML;

$html->tag("html");
$html->tag("head");
$html->close();
$html->tag("body");
$html->close();
$html->close();

クラス コードはバックグラウンドで配列を使用して動作し、データをプッシュし、データをポップします。<head>下にサブ配列を作成する必要があることは確かですが<html>、ロジックがよくわかりません。HTMLクラスの実際のコードは次のとおりです。

class HTML {

    /**
     * internal tag counter
     * @var int
     */ 
    private $t_counter = 0;

    /** 
     * create the tag
     * @author Glen Solsberry
     */
    public function tag($tag = "") {
        $this->t_counter = count($this->tags); // this points to the actual array slice
        $this->tags[$this->t_counter] = $tag; // add the tag to the list
        $this->attrs[$this->t_counter] = array(); // make sure to set up the attributes
        return $this;
    }   

    /**
     * set attributes on a tag
     * @author Glen Solsberry
     */ 
    public function attr($key, $value) {
        $this->attrs[$this->t_counter][$key] = $value;

        return $this;
    }

    public function text($text = "") {
        $this->text[$this->t_counter] = $text;

        return $this;
    }

    public function close() {
        $this->t_counter--; // update the counter so that we know that this tag is complete

        return $this;
    }

    function __toString() {
        $tag = $this->t_counter + 1;

        $output = "<" . $this->tags[$tag];
        foreach ($this->attrs[$tag] as $key => $value) {
            $output .= " {$key}=\"" . htmlspecialchars($value) . "\"";
        }
        $output .= ">";
        $output .= $this->text[$tag];
        $output .= "</" . $this->tags[$tag] . ">";

        unset($this->tags[$tag]);
        unset($this->attrs[$tag]);
        unset($this->text[$tag]);

        $this->t_counter = $tag;

        return $output;
    }
}

どんな助けでも大歓迎です。

4

1 に答える 1

2

結局のところ、PHP 用の既存の DOM コンストラクターの 1 つを使用する方が簡単かもしれません。

それが合理的でないと思われる場合。子要素を保持するためのクラスのメンバーとして配列を持つだけで、驚くべきことが起こるはずです。

于 2009-07-13T20:46:04.067 に答える