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

Hide inherited properties

PropertyTypeDescriptionDefined 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

Hide inherited methods

MethodDescriptionDefined 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

Hide inherited methods

MethodDescriptionDefined 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

aParams property
protected array $aParams;

Список параметров из URL

/action/event/param0/param1/../paramN/

aParamsEventMatch property
protected array $aParamsEventMatch;

Список совпадений по регулярному выражению для евента

aRegisterEvent property
protected array $aRegisterEvent;

Список зарегистрированных евентов

aRegisterEventExternal property
protected array $aRegisterEventExternal;

Список евентов, которые нужно обрабатывать внешним обработчиком

sActionTemplate property
protected string|null $sActionTemplate;

Шаблон экшена

sCurrentAction property
protected null|string $sCurrentAction;

Текущий экшен

sCurrentEvent property
protected string|null $sCurrentEvent;

Текущий евент

sCurrentEventName property
protected string|null $sCurrentEventName;

Имя текущий евента Позволяет именовать экшены на основе регулярных выражений

sDefaultEvent property
protected string|null $sDefaultEvent;

Дефолтный евент

See Also

Method Details

ActionCall() method
public mixed ActionCall(string $sCall)
$sCall string
{return} mixed
Source Code: /framework/classes/engine/Action.class.php#115 (show)
public function ActionCall($sCall)
{
    
$aArgs func_get_args();
    unset(
$aArgs[0]);
    return 
call_user_func_array(array($this$sCall), $aArgs);
}

Позволяет запускать не публичные методы экшена через объект

ActionCallExists() method
public bool ActionCallExists(string $sCall)
$sCall string
{return} bool
Source Code: /framework/classes/engine/Action.class.php#129 (show)
public function ActionCallExists($sCall)
{
    return 
method_exists($this$sCall);
}

Проверяет метод экшена на существование

ActionGet() method
public mixed ActionGet(string $sVar)
$sVar string
{return} mixed
Source Code: /framework/classes/engine/Action.class.php#141 (show)
public function ActionGet($sVar)
{
    return 
$this->$sVar;
}

Возвращает свойство объекта экшена

ActionSet() method
public void ActionSet(string $sVar, null|mixed $mValue=NULL)
$sVar string
$mValue null|mixed
Source Code: /framework/classes/engine/Action.class.php#152 (show)
public function ActionSet($sVar$mValue null)
{
    
$this->$sVar $mValue;
}

Устанавливает свойство объекта экшена

AddEvent() method
protected void AddEvent(string $sEventName, string $sEventFunction)
$sEventName string Название евента
$sEventFunction string Какой метод ему соответствует
Source Code: /framework/classes/engine/Action.class.php#165 (show)
protected function AddEvent($sEventName$sEventFunction)
{
    
$this->AddEventPreg("/^{$sEventName}$/i"$sEventFunction);
}

Добавляет евент в экшен По сути является оберткой для AddEventPreg(), оставлен для простоты и совместимости с прошлыми версиями ядра

See Also

AddEventPreg() method
protected void AddEventPreg()
Source Code: /framework/classes/engine/Action.class.php#174 (show)
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;
}

Добавляет евент в экшен, используя регулярное выражение для евента и параметров

EventErrorDebug() method
protected void EventErrorDebug()
Source Code: /framework/classes/engine/Action.class.php#480 (show)
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 обработчике

EventNotFound() method
protected string EventNotFound()
{return} string
Source Code: /framework/classes/engine/Action.class.php#461 (show)
protected function EventNotFound()
{
    return 
Router::Action('error''404');
}

Вызывается в том случаи если не найден евент который запросили через URL По дефолту происходит перекидывание на страницу ошибки, это можно переопределить в наследнике

See Also

EventShutdown() method
public void EventShutdown()
Source Code: /framework/classes/engine/Action.class.php#470 (show)
public function EventShutdown()
{

}

Выполняется при завершение экшена, после вызова основного евента

ExecEvent() method
public mixed ExecEvent()
{return} mixed
Source Code: /framework/classes/engine/Action.class.php#232 (show)
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)

GetActionClass() method
public string GetActionClass()
{return} string
Source Code: /framework/classes/engine/Action.class.php#439 (show)
public function GetActionClass()
{
    return 
Router::GetActionClass();
}

Получить каталог с шаблонами экшена(совпадает с именем класса)

GetCurrentEventName() method
public null|string GetCurrentEventName()
{return} null|string
Source Code: /framework/classes/engine/Action.class.php#449 (show)
public function GetCurrentEventName()
{
    return 
$this->sCurrentEventName;
}

Возвращает имя евента

GetDefaultEvent() method
public string GetDefaultEvent()
{return} string
Source Code: /framework/classes/engine/Action.class.php#298 (show)
public function GetDefaultEvent()
{
    return 
$this->sDefaultEvent;
}

Получает евент по умолчанию

GetEventMatch() method
protected string|null GetEventMatch(int|null $iItem=NULL)
$iItem int|null Номер совпадения
{return} string|null
Source Code: /framework/classes/engine/Action.class.php#309 (show)
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'];
    }
}

Возвращает элементы совпадения по регулярному выражению для евента

GetParam() method
public mixed GetParam(int $iOffset, $default=NULL)
$iOffset int Номер параметра, начинается с нуля
$default
{return} mixed
Source Code: /framework/classes/engine/Action.class.php#352 (show)
public function GetParam($iOffset$default null)
{
    
$iOffset = (int)$iOffset;
    return isset(
$this->aParams[$iOffset]) ? $this->aParams[$iOffset] : $default;
}

Получает параметр из URL по его номеру, если его нет то null

GetParamEventMatch() method
protected string|null GetParamEventMatch(int $iParamNum, int|null $iItem=NULL)
$iParamNum int Номер параметра, начинается с нуля
$iItem int|null Номер совпадения, начинается с нуля
{return} string|null
Source Code: /framework/classes/engine/Action.class.php#329 (show)
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;
        }
    }
}

Возвращает элементы совпадения по регулярному выражению для параметров евента

GetParams() method
public array GetParams()
{return} array
Source Code: /framework/classes/engine/Action.class.php#363 (show)
public function GetParams()
{
    return 
$this->aParams;
}

Получает список параметров из УРЛ

GetTemplate() method
public string GetTemplate()
{return} string
Source Code: /framework/classes/engine/Action.class.php#425 (show)
public function GetTemplate()
{
    if (
is_null($this->sActionTemplate)) {
        
$this->SetTemplateAction(strtolower($this->sCurrentEvent));
    }
    return 
$this->sActionTemplate;
}

Получить шаблон Если шаблон не определен то возвращаем дефолтный шаблон евента: actions/Action{Action}/{event}.tpl

Init() method
abstract public void Init()
Source Code: /framework/classes/engine/Action.class.php#509 (show)
abstract public function Init();

Абстрактный метод инициализации экшена

RegisterEvent() method
abstract protected void RegisterEvent()
Source Code: /framework/classes/engine/Action.class.php#516 (show)
abstract protected function RegisterEvent();

Абстрактный метод регистрации евентов. В нём необходимо вызывать метод AddEvent($sEventName,$sEventFunction)

RegisterEventExternal() method
protected void RegisterEventExternal(string $sEventName, string|array $sExternalClass)
$sEventName string
$sExternalClass string|array
Source Code: /framework/classes/engine/Action.class.php#221 (show)
protected function RegisterEventExternal($sEventName$sExternalClass)
{
    
$this->aRegisterEventExternal[$sEventName] = $sExternalClass;
}

Регистрируем внешние обработчики для евентов

SetDefaultEvent() method
public void SetDefaultEvent(string $sEvent)
$sEvent string Имя евента
Source Code: /framework/classes/engine/Action.class.php#288 (show)
public function SetDefaultEvent($sEvent)
{
    
$this->sDefaultEvent $sEvent;
}

Устанавливает евент по умолчанию

SetParam() method
public void SetParam(int $iOffset, string $value)
$iOffset int Номер параметра, но по идеи может быть не только числом
$value string
Source Code: /framework/classes/engine/Action.class.php#376 (show)
public function SetParam($iOffset$value)
{
    
Router::SetParam($iOffset$value);
    
$this->aParams Router::GetParams();
}

Установить значение параметра(эмуляция параметра в URL). После установки занова считывает параметры из роутера - для корректной работы

SetTemplate() method
protected void SetTemplate(string $sTemplate)
$sTemplate string Путь до шаблона относительно общего каталога шаблонов
Source Code: /framework/classes/engine/Action.class.php#387 (show)
protected function SetTemplate($sTemplate)
{
    
$this->sActionTemplate $sTemplate;
}

Устанавливает какой шаблон выводить

SetTemplateAction() method
protected void SetTemplateAction(string $sTemplate)
$sTemplate string Путь до шаблона относительно каталога шаблонов экшена
Source Code: /framework/classes/engine/Action.class.php#397 (show)
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;
}

Устанавливает какой шаблон выводить

__construct() method
public void __construct(string $sAction)
$sAction string Название экшена
Source Code: /framework/classes/engine/Action.class.php#100 (show)
public function __construct($sAction)
{
    
parent::__construct();
    
$this->RegisterEvent();
    
$this->sCurrentAction $sAction;
    
$this->aParams Router::GetParams();
}

Конструктор