| 1 |
<?php |
| 2 |
/** |
| 3 |
* Base view class. |
| 4 |
* |
| 5 |
* @package Calotes\Base |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Calotes\Base; |
| 9 |
|
| 10 |
/** |
| 11 |
* Base class for all views. |
| 12 |
*/ |
| 13 |
class View extends Component { |
| 14 |
|
| 15 |
|
| 16 |
/** |
| 17 |
* Holds the blocks used in the view. |
| 18 |
* |
| 19 |
* @var array |
| 20 |
*/ |
| 21 |
public $blocks = array(); |
| 22 |
|
| 23 |
/** |
| 24 |
* Holds parameters that can be passed to the view. |
| 25 |
* |
| 26 |
* @var array |
| 27 |
*/ |
| 28 |
public $params = array(); |
| 29 |
|
| 30 |
/** |
| 31 |
* The template file in which this view should be rendered. |
| 32 |
* |
| 33 |
* @var null |
| 34 |
*/ |
| 35 |
public $layout = null; |
| 36 |
|
| 37 |
/** |
| 38 |
* The file contains content of this view, relative path. |
| 39 |
* |
| 40 |
* @var null |
| 41 |
*/ |
| 42 |
public $view_file = null; |
| 43 |
|
| 44 |
/** |
| 45 |
* The folder contains view files, absolute path. |
| 46 |
* |
| 47 |
* @var null |
| 48 |
*/ |
| 49 |
private $base_path = null; |
| 50 |
|
| 51 |
/** |
| 52 |
* Constructor to set the base path of the view. |
| 53 |
* |
| 54 |
* @param mixed $base_path The base path of the view. |
| 55 |
*/ |
| 56 |
public function __construct( $base_path ) { |
| 57 |
$this->base_path = $base_path; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Render a view file. This will be used to render a whole page. |
| 62 |
* If a layout is defined, then we will render layout + view. |
| 63 |
* |
| 64 |
* @param string $view The name of the view file to render. |
| 65 |
* @param array $params An optional array of parameters to pass to the view file. |
| 66 |
* |
| 67 |
* @return string |
| 68 |
*/ |
| 69 |
public function render( $view, $params = array() ) { |
| 70 |
$view_file = $this->base_path . DIRECTORY_SEPARATOR . $view . '.php'; |
| 71 |
if ( is_file( $view_file ) ) { |
| 72 |
$content = $this->render_php_file( $view_file, $params ); |
| 73 |
|
| 74 |
return $content; |
| 75 |
} |
| 76 |
|
| 77 |
return ''; |
| 78 |
} |
| 79 |
|
| 80 |
/** |
| 81 |
* Renders a PHP file and returns its output. |
| 82 |
* |
| 83 |
* @param string $file The path to the PHP file to render. |
| 84 |
* @param array $params An optional array of parameters to pass to the PHP file. |
| 85 |
* |
| 86 |
* @return string The output of the rendered PHP file. |
| 87 |
*/ |
| 88 |
private function render_php_file( $file, $params = array() ) { |
| 89 |
ob_start(); |
| 90 |
ob_implicit_flush( false ); |
| 91 |
foreach ( $params as $key => $value ) { |
| 92 |
$$key = $value; |
| 93 |
} |
| 94 |
require $file; |
| 95 |
|
| 96 |
return ob_get_clean(); |
| 97 |
} |
| 98 |
} |
| 99 |
|