/base/Controller.php
PHP | 145 lines | 69 code | 18 blank | 58 comment | 5 complexity | a83ac9ecfa4e5619176d8e490c01b5ef MD5 | raw file
- <?php
- /**
- * Базовый контроллер приложения. Основная задача которого
- * обеспечивать логику подключения вьюх и передача в них параметров.
- * Кроме всего прочего, инкапсулирует глобальные переменные, так какие
- * мета-теги, тайтл.
- *
- * @author B.Pavel <kiliman6aro@gmail.com>
- * @copyright 2016
- */
- namespace core\base;
- abstract class Controller
- {
- public $id;
- public $layout = '@app/views/layouts/main';
- public $title;
- public $metaTags = [];
- public function runAction($id, $params = [])
- {
- $methodName = 'action'.ucfirst($id);
- if(method_exists($this, $methodName)){
- return call_user_func_array([$this, $methodName], empty($params) ? [] : $params);
- }
- throw new ActionNotFound(sprintf('Не найден метод %s в контроллере %s', $id, $this->id));
- }
- /**
- * Подключает и отображает файл. Можно указывать имя файла, или
- * алиас к нему @app/views/templates/layouts/index.view
- * @param $file string полный или относительный путь к файлу с его именем
- * @param array $params параметры
- * @param bool|false $output результат отображения будет на экране или в переменной
- * @return bool|string
- * @throws FileNotFoundException
- * @throws InvalidParamException
- */
- public function render($file, $params = [], $output = true)
- {
- if(strpos($file, '@') !== false){
- $path = \Core::getPathOfAlias($file);
- }else{
- $path = $this->getViewPath().DIRECTORY_SEPARATOR.$file;
- }
- if($output){
- $this->display($path, $params);
- return true;
- }
- return $this->renderFile($path, $params);
- }
- /**
- * Синоним для self::render($file, $params = [], $output = false). Что
- * бы более явно изобразить намерения разработчика. Буферизирует вывод
- * вьюхи и возвращает
- * @param $file
- * @param array $params
- * @return bool|string
- */
- public function renderPartial($file, $params = [])
- {
- return $this->render($file, $params, false);
- }
- /**
- * Генерирует шаблон из файла и возвращает результат.
- * @param $file
- * @param array $params
- * @return string
- */
- protected function renderFile($file, $params = [])
- {
- ob_start();
- ob_implicit_flush(false);
- $this->linkFile($file, $params);
- return ob_get_clean();
- }
- /**
- * Непосредственно подключает файл и распаковывает переменные
- * @param $file
- * @param $params
- * @throws FileNotFoundException
- */
- protected function linkFile($file, $params)
- {
- //присвоить расширение по умолчанию если его нет
- $file = $file.'.php';
- if(!file_exists($file)){
- throw new FileNotFoundException(sprintf("Не найден файл %s", $file));
- }
- extract($params, EXTR_OVERWRITE);
- require $file;
- }
- /**
- * Отображает главный шаблон, который определен в текущем контроллере,
- * и ложит в переменную content содержимое внутреннего шаблона. Если
- * главный шаблон не определен в поле текущего контроллера, то вложенный
- * шаблон, будет отображен самостоятельно
- * @param $file
- * @param array $params
- * @return bool
- * @throws FileNotFoundException
- * @throws InvalidParamException
- */
- protected function display($file, $params = [])
- {
- if(empty($this->layout)){
- $this->linkFile($file, $params);
- return true;
- }
- $content = $this->renderFile($file, $params);
- $path = strpos($this->layout, '@') !== false ? \Core::getPathOfAlias($this->layout) : $this->layout;
- $params = [
- 'content' => $content,
- 'title' => $this->title,
- 'metaTags' => $this->metaTags
- ];
- $this->linkFile($path, $params);
- }
- /**
- * Возвращает путь к каталогу с вьюхами. По умолчанию каталог
- * с вьюхами находится в app, а подкаталогом является id текущего
- * контроллера
- * @return string
- * @throws InvalidParamException
- */
- protected function getViewPath()
- {
- return \Core::getPathOfAlias('@app').DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.$this->id;
- }
- }