Action
Package | framework.engine |
---|---|
Inheritance | abstract class Action » LsObject |
Subclasses | ActionAdmin, ActionAjax, ActionBlog, ActionBlogs, ActionComments, ActionContent, ActionError, ActionIndex, ActionLogin, ActionMy, ActionPeople, ActionPersonalBlog, ActionPlugin, ActionProfile, ActionProperty, ActionRegistration, ActionRss, ActionSearch, ActionSettings, ActionStream, ActionSubscribe, ActionTag, ActionTalk, ActionUserfeed |
Since | 1.0 |
Source Code | /framework/classes/engine/Action.class.php |
От этого класса наследуются все экшены в движке. Предоставляет базовые метода для работы с параметрами и шаблоном при запросе страницы в браузере.
Protected Properties
Property | Type | Description | Defined By |
---|---|---|---|
_aBehaviors | Список поведений в виде готовых объектов, формируется автоматически | LsObject | |
aBehaviors | array | Список поведений | LsObject |
aParams | array | Список параметров из URL | Action |
aParamsEventMatch | array | Список совпадений по регулярному выражению для евента | Action |
aRegisterEvent | array | Список зарегистрированных евентов | Action |
aRegisterEventExternal | array | Список евентов, которые нужно обрабатывать внешним обработчиком | Action |
sActionTemplate | string|null | Шаблон экшена | Action |
sCurrentAction | null|string | Текущий экшен | Action |
sCurrentEvent | string|null | Текущий евент | Action |
sCurrentEventName | string|null | Имя текущий евента | Action |
sDefaultEvent | string|null | Дефолтный евент | Action |
Public Methods
Method | Description | Defined By |
---|---|---|
ActionCall() | Позволяет запускать не публичные методы экшена через объект | Action |
ActionCallExists() | Проверяет метод экшена на существование | Action |
ActionGet() | Возвращает свойство объекта экшена | Action |
ActionSet() | Устанавливает свойство объекта экшена | Action |
AddBehaviorHook() | Добавляет хук поведения | LsObject |
AttachBehavior() | Присоединяет поведение к объекту | LsObject |
DetachBehavior() | Отсоединяет поведение от объекта | LsObject |
EventShutdown() | Выполняется при завершение экшена, после вызова основного евента | Action |
ExecEvent() | Запускает евент на выполнение | Action |
GetActionClass() | Получить каталог с шаблонами экшена(совпадает с именем класса) | Action |
GetBehavior() | Возвращает объект поведения по его имени | LsObject |
GetBehaviors() | Возвращает все объекты поведения | LsObject |
GetCurrentEventName() | Возвращает имя евента | Action |
GetDefaultEvent() | Получает евент по умолчанию | Action |
GetParam() | Получает параметр из URL по его номеру, если его нет то null | Action |
GetParams() | Получает список параметров из УРЛ | Action |
GetTemplate() | Получить шаблон | Action |
Init() | Абстрактный метод инициализации экшена | Action |
RemoveBehaviorHook() | Удаляет хук поведения | LsObject |
RunBehaviorHook() | Запускает хук поведения на выполнение | LsObject |
SetDefaultEvent() | Устанавливает евент по умолчанию | Action |
SetParam() | Установить значение параметра(эмуляция параметра в URL). | Action |
__call() | Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля | LsObject |
__clone() | При клонировании сбрасываем поведения | LsObject |
__construct() | Конструктор | Action |
__get() | Обработка доступа к объекты поведения | LsObject |
Protected Methods
Method | Description | Defined By |
---|---|---|
AddEvent() | Добавляет евент в экшен | Action |
AddEventPreg() | Добавляет евент в экшен, используя регулярное выражение для евента и параметров | Action |
EventErrorDebug() | Выводит отладочную информацию в стандартном сообщении | Action |
EventNotFound() | Вызывается в том случаи если не найден евент который запросили через URL | Action |
GetEventMatch() | Возвращает элементы совпадения по регулярному выражению для евента | Action |
GetParamEventMatch() | Возвращает элементы совпадения по регулярному выражению для параметров евента | Action |
PrepareBehaviors() | Инициализация поведений | LsObject |
RegisterEvent() | Абстрактный метод регистрации евентов. | Action |
RegisterEventExternal() | Регистрируем внешние обработчики для евентов | Action |
SetTemplate() | Устанавливает какой шаблон выводить | Action |
SetTemplateAction() | Устанавливает какой шаблон выводить | Action |
Property Details
Список параметров из URL
/action/event/param0/param1/../paramN/
Список совпадений по регулярному выражению для евента
Список зарегистрированных евентов
Список евентов, которые нужно обрабатывать внешним обработчиком
Шаблон экшена
See Also
Текущий экшен
Текущий евент
Имя текущий евента Позволяет именовать экшены на основе регулярных выражений
Дефолтный евент
See Also
Method Details
public mixed ActionCall(string $sCall)
| ||
$sCall | string | |
{return} | mixed |
public function ActionCall($sCall)
{
$aArgs = func_get_args();
unset($aArgs[0]);
return call_user_func_array(array($this, $sCall), $aArgs);
}
Позволяет запускать не публичные методы экшена через объект
public bool ActionCallExists(string $sCall)
| ||
$sCall | string | |
{return} | bool |
public function ActionCallExists($sCall)
{
return method_exists($this, $sCall);
}
Проверяет метод экшена на существование
public mixed ActionGet(string $sVar)
| ||
$sVar | string | |
{return} | mixed |
public function ActionGet($sVar)
{
return $this->$sVar;
}
Возвращает свойство объекта экшена
public void ActionSet(string $sVar, null|mixed $mValue=NULL)
| ||
$sVar | string | |
$mValue | null|mixed |
public function ActionSet($sVar, $mValue = null)
{
$this->$sVar = $mValue;
}
Устанавливает свойство объекта экшена
protected void AddEvent(string $sEventName, string $sEventFunction)
| ||
$sEventName | string | Название евента |
$sEventFunction | string | Какой метод ему соответствует |
protected function AddEvent($sEventName, $sEventFunction)
{
$this->AddEventPreg("/^{$sEventName}$/i", $sEventFunction);
}
Добавляет евент в экшен По сути является оберткой для AddEventPreg(), оставлен для простоты и совместимости с прошлыми версиями ядра
See Also
protected void AddEventPreg()
|
protected function AddEventPreg()
{
$iCountArgs = func_num_args();
if ($iCountArgs < 2) {
throw new Exception("Incorrect number of arguments when adding events");
}
$aEvent = array();
/**
* Последний параметр может быть массивом - содержать имя метода и имя евента(именованный евент)
* Если указан только метод, то имя будет равным названию метода
*/
$aNames = (array)func_get_arg($iCountArgs - 1);
$aEvent['method'] = $aNames[0];
/**
* Определяем наличие внешнего обработчика евента
*/
$aEvent['external'] = null;
$aMethod = explode('::', $aEvent['method']);
if (count($aMethod) > 1) {
$aEvent['method'] = $aMethod[1];
$aEvent['external'] = $aMethod[0];
}
if (isset($aNames[1])) {
$aEvent['name'] = $aNames[1];
} else {
$aEvent['name'] = $aEvent['method'];
}
if (!$aEvent['external']) {
if (!method_exists($this, $aEvent['method'])) {
throw new Exception("Method of the event not found: " . $aEvent['method']);
}
}
$aEvent['preg'] = func_get_arg(0);
$aEvent['params_preg'] = array();
for ($i = 1; $i < $iCountArgs - 1; $i++) {
$aEvent['params_preg'][] = func_get_arg($i);
}
$this->aRegisterEvent[] = $aEvent;
}
Добавляет евент в экшен, используя регулярное выражение для евента и параметров
protected void EventErrorDebug()
|
protected function EventErrorDebug()
{
if (Config::Get('sys.debug.action_error')) {
$aTrace = debug_backtrace(false);
$aCaller = array_shift($aTrace);
$aCallerSource = array_shift($aTrace);
$aPathinfo = pathinfo($aCaller['file']);
$sMsg = $aPathinfo['basename'] . ' [' . $aCallerSource['class'] . $aCallerSource['type'] . $aCallerSource['function'] . ': ' . $aCaller['line'] . ']';
$this->Message_AddErrorSingle($sMsg, 'System error');
if ($this->Viewer_GetResponseAjax()) {
return true;
} else {
return Router::Action('error', '500');
}
} else {
if ($this->Viewer_GetResponseAjax()) {
$this->Message_AddErrorSingle('System error');
return true;
} else {
return Router::Action('error', '500');
}
}
}
Выводит отладочную информацию в стандартном сообщении Этим методом можно завершать выполнение евента в случае системной ошибки, например, не удалось найти топик по его ID при голосовании в ajax обработчике
protected string EventNotFound()
| ||
{return} | string |
protected function EventNotFound()
{
return Router::Action('error', '404');
}
Вызывается в том случаи если не найден евент который запросили через URL По дефолту происходит перекидывание на страницу ошибки, это можно переопределить в наследнике
See Also
public void EventShutdown()
|
public function EventShutdown()
{
}
Выполняется при завершение экшена, после вызова основного евента
public mixed ExecEvent()
| ||
{return} | mixed |
public function ExecEvent()
{
$this->sCurrentEvent = Router::GetActionEvent();
if ($this->sCurrentEvent == null) {
$this->sCurrentEvent = $this->GetDefaultEvent();
Router::SetActionEvent($this->sCurrentEvent);
}
foreach ($this->aRegisterEvent as $aEvent) {
if (preg_match($aEvent['preg'], $this->sCurrentEvent, $aMatch)) {
$this->aParamsEventMatch['event'] = $aMatch;
$this->aParamsEventMatch['params'] = array();
foreach ($aEvent['params_preg'] as $iKey => $sParamPreg) {
if (preg_match($sParamPreg, $this->GetParam($iKey, ''), $aMatch)) {
$this->aParamsEventMatch['params'][$iKey] = $aMatch;
} else {
continue 2;
}
}
$this->sCurrentEventName = $aEvent['name'];
if ($aEvent['external']) {
if (!isset($this->aRegisterEventExternal[$aEvent['external']])) {
throw new Exception("External processing for event not found: " . $aEvent['external']);
}
}
$this->Hook_Run("action_event_" . strtolower($this->sCurrentAction) . "_before",
array('event' => $this->sCurrentEvent, 'params' => $this->GetParams()));
/**
* Проверяем на наличие внешнего обработчика евента
*/
if ($aEvent['external']) {
$sEventClass = $this->Plugin_GetDelegate('event',
$this->aRegisterEventExternal[$aEvent['external']]);
$oEvent = new $sEventClass;
$oEvent->SetActionObject($this);
$oEvent->Init();
if (!$aEvent['method']) {
$result = $oEvent->Exec();
} else {
$result = call_user_func_array(array($oEvent, $aEvent['method']), array());
}
} else {
$result = call_user_func_array(array($this, $aEvent['method']), array());
}
$this->Hook_Run("action_event_" . strtolower($this->sCurrentAction) . "_after",
array('event' => $this->sCurrentEvent, 'params' => $this->GetParams()));
return $result;
}
}
return $this->EventNotFound();
}
Запускает евент на выполнение Если текущий евент не определен то запускается тот которые определен по умолчанию(default event)
public string GetActionClass()
| ||
{return} | string |
public function GetActionClass()
{
return Router::GetActionClass();
}
Получить каталог с шаблонами экшена(совпадает с именем класса)
See Also
public null|string GetCurrentEventName()
| ||
{return} | null|string |
public function GetCurrentEventName()
{
return $this->sCurrentEventName;
}
Возвращает имя евента
public string GetDefaultEvent()
| ||
{return} | string |
public function GetDefaultEvent()
{
return $this->sDefaultEvent;
}
Получает евент по умолчанию
protected string|null GetEventMatch(int|null $iItem=NULL)
| ||
$iItem | int|null | Номер совпадения |
{return} | string|null |
protected function GetEventMatch($iItem = null)
{
if ($iItem) {
if (isset($this->aParamsEventMatch['event'][$iItem])) {
return $this->aParamsEventMatch['event'][$iItem];
} else {
return null;
}
} else {
return $this->aParamsEventMatch['event'];
}
}
Возвращает элементы совпадения по регулярному выражению для евента
public mixed GetParam(int $iOffset, $default=NULL)
| ||
$iOffset | int | Номер параметра, начинается с нуля |
$default | ||
{return} | mixed |
public function GetParam($iOffset, $default = null)
{
$iOffset = (int)$iOffset;
return isset($this->aParams[$iOffset]) ? $this->aParams[$iOffset] : $default;
}
Получает параметр из URL по его номеру, если его нет то null
protected string|null GetParamEventMatch(int $iParamNum, int|null $iItem=NULL)
| ||
$iParamNum | int | Номер параметра, начинается с нуля |
$iItem | int|null | Номер совпадения, начинается с нуля |
{return} | string|null |
protected function GetParamEventMatch($iParamNum, $iItem = null)
{
if (!is_null($iItem)) {
if (isset($this->aParamsEventMatch['params'][$iParamNum][$iItem])) {
return $this->aParamsEventMatch['params'][$iParamNum][$iItem];
} else {
return null;
}
} else {
if (isset($this->aParamsEventMatch['event'][$iParamNum])) {
return $this->aParamsEventMatch['event'][$iParamNum];
} else {
return null;
}
}
}
Возвращает элементы совпадения по регулярному выражению для параметров евента
public array GetParams()
| ||
{return} | array |
public function GetParams()
{
return $this->aParams;
}
Получает список параметров из УРЛ
public string GetTemplate()
| ||
{return} | string |
public function GetTemplate()
{
if (is_null($this->sActionTemplate)) {
$this->SetTemplateAction(strtolower($this->sCurrentEvent));
}
return $this->sActionTemplate;
}
Получить шаблон Если шаблон не определен то возвращаем дефолтный шаблон евента: actions/Action{Action}/{event}.tpl
abstract public void Init()
|
abstract public function Init();
Абстрактный метод инициализации экшена
abstract protected void RegisterEvent()
|
abstract protected function RegisterEvent();
Абстрактный метод регистрации евентов. В нём необходимо вызывать метод AddEvent($sEventName,$sEventFunction)
protected void RegisterEventExternal(string $sEventName, string|array $sExternalClass)
| ||
$sEventName | string | |
$sExternalClass | string|array |
protected function RegisterEventExternal($sEventName, $sExternalClass)
{
$this->aRegisterEventExternal[$sEventName] = $sExternalClass;
}
Регистрируем внешние обработчики для евентов
public void SetDefaultEvent(string $sEvent)
| ||
$sEvent | string | Имя евента |
public function SetDefaultEvent($sEvent)
{
$this->sDefaultEvent = $sEvent;
}
Устанавливает евент по умолчанию
public void SetParam(int $iOffset, string $value)
| ||
$iOffset | int | Номер параметра, но по идеи может быть не только числом |
$value | string |
public function SetParam($iOffset, $value)
{
Router::SetParam($iOffset, $value);
$this->aParams = Router::GetParams();
}
Установить значение параметра(эмуляция параметра в URL). После установки занова считывает параметры из роутера - для корректной работы
protected void SetTemplate(string $sTemplate)
| ||
$sTemplate | string | Путь до шаблона относительно общего каталога шаблонов |
protected function SetTemplate($sTemplate)
{
$this->sActionTemplate = $sTemplate;
}
Устанавливает какой шаблон выводить
protected void SetTemplateAction(string $sTemplate)
| ||
$sTemplate | string | Путь до шаблона относительно каталога шаблонов экшена |
protected function SetTemplateAction($sTemplate)
{
$aDelegates = $this->Plugin_GetDelegationChain('action', $this->GetActionClass());
$sActionTemplatePath = $sTemplate . '.tpl';
foreach ($aDelegates as $sAction) {
if (preg_match('/^(Plugin([\w]+)_)?Action([\w]+)$/i', $sAction, $aMatches)) {
$sTemplatePath = $this->Plugin_GetDelegate('template',
'actions/Action' . ucfirst($aMatches[3]) . '/' . $sTemplate . '.tpl');
if (empty($aMatches[1])) {
$sActionTemplatePath = $sTemplatePath;
} else {
$sTemplatePath = Plugin::GetTemplatePath($sAction) . $sTemplatePath;
if (is_file($sTemplatePath)) {
$sActionTemplatePath = $sTemplatePath;
break;
}
}
}
}
$this->sActionTemplate = $sActionTemplatePath;
}
Устанавливает какой шаблон выводить
public void __construct(string $sAction)
| ||
$sAction | string | Название экшена |
public function __construct($sAction)
{
parent::__construct();
$this->RegisterEvent();
$this->sCurrentAction = $sAction;
$this->aParams = Router::GetParams();
}
Конструктор