Я работаю над HTML-классом в PHP, чтобы мы могли поддерживать согласованность всех наших 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;
}
}
Любая помощь будет принята с благодарностью.