In PHP how can I follow the DRY (don't repeat yourself) principle in this piece of code? The 2 classes in question share an awful lot of code.
<?php
interface iSelect
{
public static function display();
}
class CountrySelect implements iSelect {
static $template = 'select_template.php';
public static function display() {
if ( class_exists( 'View' ) ) {
// Get the full path to the template file.
$templatePath = dirname( __FILE__ ) . '/' . static::$template;
$viewData = array(
"options" => '_countries',
"optionsText" => 'name',
"optionsValue" => 'geonameId',
"value" => 'selectedCountry',
"caption" => 'Country'
);
// Return the rendered HTML
return View::render( $templatePath, $viewData );
}
else {
return "You are trying to render a template, but we can't find the View Class";
}
}
}
class RegionSelect implements iSelect {
static $template = 'select_template.php';
public static function display() {
if ( class_exists( 'View' ) ) {
// Get the full path to the template file.
$templatePath = dirname( __FILE__ ) . '/' . static::$template;
$viewData = array(
"options" => '_regions',
"optionsText" => 'name',
"optionsValue" => 'name',
"value" => 'selectedCity',
"caption" => 'Region'
);
// Return the rendered HTML
return View::render( $templatePath, $viewData );
}
else {
return "You are trying to render a template, but we can't find the View Class";
}
}
}
?>
The code in question is for php templating. Here is the template:
<div class="form-group col-sm-6">
<div class="select">
<span class="arr"></span>
<select data-bind="options: <? echo $options ?>,
optionsText: '<? echo $optionsText ?>',
optionsValue: '<? echo $optionsValue ?>',
value: <? echo $value ?>,
optionsCaption: '<? echo $caption ?>'">
</select>
</div>
</div>
Here is the View.php which takes the $ViewData
and the $template
file and then renders it:
<?php
/** View.php **/
class View {
/**
* -------------------------------------
* Render a Template.
* -------------------------------------
*
* @param $filePath - include path to the template.
* @param null $viewData - any data to be used within the template.
* @return string -
*
*/
public static function render( $filePath, $viewData = null ) {
// Was any data sent through?
( $viewData ) ? extract( $viewData ) : null;
ob_start();
include ( $filePath );
$template = ob_get_contents();
ob_end_clean();
return $template;
}
}
?>