| 1 |
<?php |
| 2 |
/** |
| 3 |
* Author: Hoang Ngo |
| 4 |
*/ |
| 5 |
|
| 6 |
namespace Calotes\Base; |
| 7 |
|
| 8 |
class View extends Component { |
| 9 |
const EVENT_BEFORE_RENDER = 'beforeRender', EVENT_AFTER_RENDER = 'afterRender'; |
| 10 |
|
| 11 |
/** |
| 12 |
* @var array |
| 13 |
*/ |
| 14 |
public $blocks = array(); |
| 15 |
/** |
| 16 |
* @var array |
| 17 |
*/ |
| 18 |
public $params = array(); |
| 19 |
/** |
| 20 |
* Template file this view should render in |
| 21 |
* |
| 22 |
* @var null |
| 23 |
*/ |
| 24 |
public $layout = null; |
| 25 |
/** |
| 26 |
* The file contains content of this view, relative path |
| 27 |
* |
| 28 |
* @var null |
| 29 |
*/ |
| 30 |
public $view_file = null; |
| 31 |
|
| 32 |
/** |
| 33 |
* @var array |
| 34 |
*/ |
| 35 |
protected $_cache_stack = array(); |
| 36 |
/** |
| 37 |
* The folder contains view files, absolute path |
| 38 |
* |
| 39 |
* @var null |
| 40 |
*/ |
| 41 |
private $_base_path = null; |
| 42 |
|
| 43 |
public function __construct( $base_path ) { |
| 44 |
$this->_base_path = $base_path; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Render a view file, this will be use to render a whole page, if a layout defined, then we will render layout + view |
| 49 |
* |
| 50 |
* @param $view |
| 51 |
* @param array $params |
| 52 |
* |
| 53 |
* @return string |
| 54 |
*/ |
| 55 |
public function render( $view, $params = array() ) { |
| 56 |
$this->trigger( self::EVENT_BEFORE_RENDER ); |
| 57 |
$view_file = $this->_base_path . DIRECTORY_SEPARATOR . $view . '.php'; |
| 58 |
if ( is_file( $view_file ) ) { |
| 59 |
$content = $this->render_php_file( $view_file, $params ); |
| 60 |
$this->trigger( self::EVENT_AFTER_RENDER ); |
| 61 |
|
| 62 |
return $content; |
| 63 |
} else { |
| 64 |
echo $view_file; |
| 65 |
} |
| 66 |
|
| 67 |
return false; |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* @param $file |
| 72 |
* @param array $params |
| 73 |
* |
| 74 |
* @return string |
| 75 |
*/ |
| 76 |
private function render_php_file( $file, $params = array() ) { |
| 77 |
ob_start(); |
| 78 |
ob_implicit_flush( false ); |
| 79 |
extract( $params, EXTR_OVERWRITE ); |
| 80 |
require $file; |
| 81 |
|
| 82 |
return ob_get_clean(); |
| 83 |
} |
| 84 |
|
| 85 |
/** |
| 86 |
* Starting a cache block |
| 87 |
*/ |
| 88 |
public function begin_cache( $id ) { |
| 89 |
ob_start(); |
| 90 |
$this->_cache_stack[ $id ] = null; |
| 91 |
} |
| 92 |
|
| 93 |
/** |
| 94 |
* @param $id |
| 95 |
* |
| 96 |
* @return string |
| 97 |
*/ |
| 98 |
public function end_cache( $id ) { |
| 99 |
$cached = ob_get_clean(); |
| 100 |
$this->_cache_stack[ $id ] = $cached; |
| 101 |
|
| 102 |
return $cached; |
| 103 |
} |
| 104 |
|
| 105 |
/** |
| 106 |
* Get cache content cached |
| 107 |
* |
| 108 |
* @param $id |
| 109 |
* |
| 110 |
* @return mixed|null |
| 111 |
*/ |
| 112 |
public function get_cache( $id ) { |
| 113 |
return isset( $this->_cache_stack[ $id ] ) ? $this->_cache_stack[ $id ] : null; |
| 114 |
} |
| 115 |
} |
| 116 |
|