Nasıl düzgün bir HTML sınıf oluştururum?

1 Cevap php

Biz tutarlı tüm HTML çıktısını tutmak böylece ben, PHP HTML sınıf üzerinde çalışıyorum. Ancak, bazı sorun mantığı etrafında başımı sarma yaşıyorum. PHP çalışıyorum, ama herhangi bir dilde cevap çalışacaktır.

Ben sınıf düzgün yuva etiketleri istiyorum, bu yüzden böyle arama yapabilmek istiyorum:

$html = new HTML;

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

Sınıf kodu dizileri ile perde arkasında çalışan ve veri kapalı haşhaş, veri bastırıyor. Ben <head> altında <html> için bir alt dizi oluşturmak için gereken eminim, ama ben oldukça mantığını çözemiyorum. Bu haliyle İşte HTML sınıfına gerçek kod:

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;
    }
}

Herhangi bir yardım büyük mutluluk duyacağız.

1 Cevap

Bu tüm bu aşağı geldiğinde, PHP için mevcut DOM kurucular birini kullanmak için basit olabilir, olabilir.

Makul görünmüyor ise; sadece çocuklar elemanları tutmak için sınıfın bir üyesi olarak bir dizi olan harikalar yapmalıdır.