我喜欢使用 MooTools JavaScript 库创建 HTML 元素。它简单、快速,而且用于创建元素的 JavaScript 代码非常漂亮。这让我开始思考——为什么我不用 PHP 来做这件事?当您构建像我一样多的动态 CMS 类网站时,您最终不得不使用一堆 if/else 逻辑来操作单个 HTML 元素属性,并且代码开始变得难看。
我花了大约半个小时来拼凑以下 PHP 类。它体积小,易于使用,并且生成漂亮的代码——就像 Moo!
PHP
/* creates an html element, like in js */ class html_element { /* vars */ var $type; var $attributes; var $self_closers; /* constructor */ function html_element($type,$self_closers = array('input','img','hr','br','meta','link')) { $this->type = strtolower($type); $this->self_closers = $self_closers; } /* get */ function get($attribute) { return $this->attributes[$attribute]; } /* set -- array or key,value */ function set($attribute,$value = '') { if(!is_array($attribute)) { $this->attributes[$attribute] = $value; } else { $this->attributes = array_merge($this->attributes,$attribute); } } /* remove an attribute */ function remove($att) { if(isset($this->attributes[$att])) { unset($this->attributes[$att]); } } /* clear */ function clear() { $this->attributes = array(); } /* inject */ function inject($object) { if(@get_class($object) == __class__) { $this->attributes['text'].= $object->build(); } } /* build */ function build() { //start $build = '<'.$this->type; //add attributes if(count($this->attributes)) { foreach($this->attributes as $key=>$value) { if($key != 'text') { $build.= ' '.$key.'="'.$value.'"'; } } } //closing if(!in_array($this->type,$this->self_closers)) { $build.= '>'.$this->attributes['text'].'</'.$this->type.'>'; } else { $build.= ' />'; } //return it return $build; } /* spit it out */ function output() { echo $this->build(); } }
课程非常简单。当您实例化该类时,您将元素类型提供给它。
创建元素后,您可以使用 get() 检索值并使用 set()
(key and value OR array key=>value) 设置值。你可以去掉指定的
使用 remove() 的属性或使用 clear() 的所有属性键=>值。你可以注射
使用 inject() 将 html_elements 转换为其他 html_elements。您可以获得原始 HTML
使用 build() 构建元素,或者您可以使用 output() 函数来回显
HTML。 重要:使用“文本”属性在元素内添加文本/HTML。
使用示例
/* test case - simple link */ $my_anchor = new html_element('a'); $my_anchor->set('href','https://davidwalsh.name'); $my_anchor->set('title','David Walsh Blog'); $my_anchor->set('text','Click here!'); $my_anchor->output(); //<a href="https://davidwalsh.name" title="David Walsh Blog">Click here!</a> /* test case - br tag */ echo '<pre>'; $my_anchor = new html_element('br'); $my_anchor->output(); //<br /> /* test case - sending an array to set */ echo '<pre>'; $my_anchor = new html_element('a'); $my_anchor->set('href','https://davidwalsh.name'); $my_anchor->set(array('href'=>'http://cnn.com','text'=>'CNN')); $my_anchor->output(); //<a href="http://cnn.com">CNN</a> /* test case - injecting another element */ echo '<pre>'; $my_image = new html_element('img'); $my_image->set('src','cnn-logo.jpg'); $my_image->set('border','0'); $my_anchor = new html_element('a'); $my_anchor->set(array('href'=>'http://cnn.com','title'=>'CNN')); $my_anchor->inject($my_image); $my_anchor->output(); //<a href="http://cnn.com" title="CNN"><img src="cnn-logo.jpg" border="0" /></a>
对这门课有什么想法吗?分享它们!