2009-07-13 11 views
0

私はPHPのHTMLクラスで作業していますので、すべてのHTML出力の一貫性を保つことができます。しかし、私はロジックの周りに私の頭をラッピングするいくつかの問題を抱えています。私はPHPで作業していますが、どの言語でも答えがうまくいきます。HTMLクラスを正しく作成するにはどうすればよいですか?

は、私はクラスに適切に巣タグをしたいので、私はこのように呼び出すことができるようにしたい:クラスのコードは、データをポップ、アレイと舞台裏で働いて、そして上のデータをプッシュされ

$html = new HTML; 

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

オフ。私は<html>の下に<head>を持つためにサブアレイを作成する必要があると確信していますが、ロジックを理解することはできません。それはスタンドとしてここ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; 
    } 
} 

任意の助けをいただければ幸いです。

+1

HTMLドキュメントをXMLのように構築し、この関数を使ってhttp://no.php.net/manual/en/domdocument.savehtml.phpにシリアライズできます。 –

答えて

2

PHPに既存のDOMコンストラクタのいずれかを使用する方が簡単になるかもしれません。

これは妥当ではないと思われる場合。子要素を保持するクラスのメンバーとして配列を持つだけで不思議に思うはずです。

+0

いくつかのDOMコンストラクタへのリンクを投稿できますか? php.netからのものはほとんどがXMLのために(限られた研究で)見える –

+1

PHPに組み込まれたDOMモジュールは、XMLとHTMLの両方をサポートしています。特に、DOMDocument :: saveHTML()関数をチェックしてください。 http://us.php.net/manual/en/book.dom.php –