I am used to procedural PHP. However, I have a piece of code that needs to be repeated a lot. I was thinking of trying my hand at creating a class. All is going well and it is working, but I think it can be done better. Especially the function where I am creating the HTML. At the moment, I have a variable $html and I keep adding data to it. It feels clunky and I wanted to know if anyone knows of a better solution.
I have been spending hours on Google trying to find a better way of doing it. Has anyone got advice or a link to a good tutorial?
Thank you in advance. Here is the class.
class clerksection {
var $header;
var $post;
var $meta;
function __construct($post, $meta, $header) {
$this->post = $post;
$this->meta = $meta;
$this->header = $header;
}
//PHP magic methods to get values
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
//PHP magic methods to set values
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
function create_html () {
$repeat_group = get_post_meta( $this->post, $this->meta, true );
$uid = spl_object_hash($this);
$html = '<h2><strong>'. $this->header .'</strong></h2>';
$html .= '<div class="row">';
$i = 1;
foreach( (array) $repeat_group as $key => $value ) :
$html .= '<div class="col-lg-4 pd_left_15">';
$html .= '<div class="pd_btm_20">';
if (!empty($value['image'])) :
$html .= '<img src="' . $value['image'] . '" class="img-responsive"/>';
endif;
$html .= '<p class="clerk_thick"><strong>' . $value['title'] . '</strong></p>';
$html .= '<p class="dark_color clerk_thin"><strong>' . $value['name'] . '</strong>';
if (!empty($value['notes'])) :
$html .= '<a role="button" data-toggle="collapse" href="#' . $uid . $i . '" aria-expanded="false" aria-controls="' . $uid . $i . '">(more)</a>';
endif;
$html .= '</p>'; //.dark_color .clerk_thin
if (!empty($value['notes'])) :
$html .= '<p class="clerk_thin collapse" id="' . $uid . $i . '">' . $value['notes'] .'</p>';
endif;
if (!empty($value['phone'])) :
$html .= '<p class="clerk_thin"><i class="fa fa-phone dark_color"></i> ' . $value['phone'] . '</p>';
endif;
if (!empty($value['email'])) :
$html .= '<p class="clerk_thin"><i class="fa fa-envelope-o dark_color"></i> <a href="mailto:' . $value['email'] . '" target="_top"> ' . $value['email'] . '</a></p>';
endif;
$html .= '</div>'; //.pd_btm_20
$html .= '</div>'; //.col-lg-4 .pd_left_15
$i++;
endforeach;
$html .= '</div>'; //.row
return $html;
}
}
var
was fine back in the days of PHP4, but the current stable version is PHP7, 7.1 isn't too far off either. Declare properties and methods the correct way:public function __construct(){}
andprotected $property
. Also: don't rely on magic__set
and__get
if you can help it, use dedicated getters and setters. magic methods are slower, harder to test and more error prone – Elias Van Ootegem Jun 21 at 9:18