Skip to content

Instantly share code, notes, and snippets.

@smgladkovskiy
Created October 20, 2010 08:16
Show Gist options
  • Save smgladkovskiy/636010 to your computer and use it in GitHub Desktop.
Save smgladkovskiy/636010 to your computer and use it in GitHub Desktop.
Modified Kohana 3 Controller_Template
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Базовый класс контроллера-шаблона
*
* @author avis <smgladkovskiy@gmail.com>
*/
abstract class Controller_Template extends Kohana_Controller_Template {
/**
* Шаблон страницы
*
* @var string
*/
public $template = 'frontend/template/main';
/**
* Название страницы по-умолчанию
*
* @var string
*/
public $page_title = '';
/**
* Обязательность авторизации для доступа к странице
*
* @var bool
*/
public $_auth_required = FALSE;
/**
* Ключ активного пункта меню по умолчанию (формируется автоматом в методе before())
*
* @var string
*/
protected $_active_menu_item = '';
/**
* Признак ajax-like запроса
*
* @var boolean
*/
protected $_ajax = FALSE;
/**
* Пред-обработка действия контроллера
*/
public function before()
{
parent::before();
// Проверка на запрос AJAX-типа
if (Request::$is_ajax OR $this->request !== Request::instance())
{
$this->_ajax = TRUE;
}
// Проверка на необходимость аутентификации
if ($this->_auth_required AND ! Auth::instance()->logged_in())
{
Session::instance()->set('url', $_SERVER['REQUEST_URI']);
Request::instance()->redirect('auth/login');
}
// вычисление ключа активного пункта меню по-умолчанию
$this->_active_menu_item = ($this->request->controller == 'error')
? Request::instance()->controller
: $this->request->controller;
if ($this->auto_render)
{
View::set_global('menu', Menu::instance());
View::set_global('controller', $this->request->controller);
// Инициализация значений шаблона по-умолчанию
$this->template->title_delimeter = ' :: '; // разделитель в заголовке страницы
$this->template->title = ''; // заголовок по-умолчанию
$this->template->page_title = ''; // заголовок страницы по-умолчанию
$this->template->styles = array(); // массив стилей
$this->template->scripts = array(); // массив скриптов
// определение браузера IE6 и выдача заглушки/строки с информацией для пользователя
/* $this->template->ie6 = (Cookie::get('ie6') === 'yes')
? View::factory('error/ie6/line')
: ''; */
$this->template->content = ''; // контент страницы
$this->template->counters = ''; // счётчики посещений
$this->template->active_menu_item = ''; // активный пункт меню
// профайлер
$this->template->debug = (Kohana::$environment == 'development'
OR Kohana::$environment == 'test')
? View::factory('profiler/stats') : '';
}
}
/**
* Пост-обработка действия контроллера
*/
public function after()
{
if ($this->auto_render)
{
// Формирование заголовка страницы на основе данных о page_title, title_delimeter и title
if($this->page_title)
{
if( ! $this->template->page_title)
$this->template->page_title = $this->page_title;
$this->template->title = $this->page_title
. $this->template->title_delimeter
. $this->template->title;
}
// Задача общих стилей
$styles = array(
'css/style.css' => 'all',
);
// Задача общих js скриптов
$scripts = array(
'js/jquery.min.js',
);
// Добавление всех скриптов и стилей в шаблон
$this->template->scripts = array_merge($this->template->scripts, $scripts);
$this->template->styles = array_merge($this->template->styles, $styles);
/*
* Добавление счётчиков
* @uses Counters
*/
//$this->template->counters = Counters::set();
}
if ($this->_ajax === FALSE AND $this->auto_render === TRUE)
{
// Передача в шаблон информацию об активном разделе меню
$this->template->active_menu_item = $this->_active_menu_item;
}
// При ajax запросе как ответ используется контент шаблона
if ($this->_ajax === TRUE)
{
$this->request->response = $this->template->content;
}
else
{
parent::after();
}
}
} // End Controller_Template
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment