Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace core;
- abstract class Controller{
- public $pageLayout = '/layout/main';
- public $pageTitle = '';
- public $pageMeta = [];
- public $pageParam = [];
- public function run($action, $params){
- $vars = [];
- $ref = new \ReflectionMethod($this, $action);
- foreach($ref->getParameters() as $param){
- $name=$param->getName();
- if(isset($params[$name]))
- {
- if($param->isArray())
- $vars[]=is_array($params[$name]) ? $params[$name] : array($params[$name]);
- elseif(!is_array($params[$name]))
- $vars[]=$params[$name];
- }
- elseif($param->isDefaultValueAvailable())
- $vars[]=$param->getDefaultValue();
- }
- call_user_func_array([$this, $action], $vars);
- }
- public function render($file, $vars = null, $return = false){
- $content = $this->renderPartial($file, $vars, true);
- $this->renderPartial($this->pageLayout, ['content'=>$content]);
- }
- private $_viewFolder;
- public function renderPartial($file, $vars = null, $return = false){
- if(str_start($file, '/')){
- // Если указана папка то запоминаем её
- $a = explode('/', trim($file, '/'));
- $oldfolder = $this->_viewFolder;
- $this->_viewFolder = $a[0];
- $file = DIR_VIEWS.$file.'.php';
- $output = $this->renderInternal($file, $vars, $return);
- $this->_viewFolder = $oldfolder;
- }else{
- if(!$this->_viewFolder){
- // По умолчанию папка по имени контролера
- $class = get_called_class();
- $this->_viewFolder = strtolower(substr($class, 11, strlen($class) - 21));
- }
- $file = $this->_viewFolder.'/'.$file;
- $file = DIR_VIEWS.$file.'.php';
- $output = $this->renderInternal($file, $vars, $return);
- }
- return $output;
- }
- private function renderInternal($_file, $_vars = null, $_return = false){
- if(is_array($_vars) && !empty($_vars))
- extract($_vars);
- extract(['this' => $this]);
- if($_return){
- ob_start();
- ob_implicit_flush(false);
- require($_file);
- return ob_get_clean();
- }else{
- require($_file);
- return true;
- }
- }
- public function renderJson($data = []){
- header('Content-Type: application/json');
- echo json_encode($data);
- $this->end();
- }
- public function renderJsonError($err_code, $msg = '', $data = []){
- header('Content-Type: application/json');
- header($_SERVER['SERVER_PROTOCOL'].' '.$err_code.' '.$msg, true, $err_code);
- echo json_encode($data);
- $this->end();
- }
- public function redirect($url){
- header('Location: '.$url);
- $this->end();
- }
- public function end(){
- App::instance()->end();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement