Action

Package engine
Inheritance abstract class Action » LsObject
Subclasses ActionAdmin, ActionAjax, ActionBlog, ActionBlogs, ActionComments, ActionError, ActionIndex, ActionLink, ActionLogin, ActionMy, ActionPeople, ActionPersonalBlog, ActionPhotoset, ActionPlugin, ActionProfile, ActionQuestion, ActionRegistration, ActionRss, ActionSearch, ActionSettings, ActionStream, ActionSubscribe, ActionTag, ActionTalk, ActionTopic, ActionUserfeed
Since 1.0
Source Code /engine/classes/Action.class.php
Абстрактный класс экшена.

От этого класса наследуются все экшены в движке. Предоставляет базовые метода для работы с параметрами и шаблоном при запросе страницы в браузере.

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
aParams array Список параметров из URL Action
aParamsEventMatch array Список совпадений по регулярному выражению для евента Action
aRegisterEvent array Список зарегистрированных евентов Action
oEngine Engine|null Объект ядра 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
EventShutdown() Выполняется при завершение экшена, после вызова основного евента Action
ExecEvent() Запускает евент на выполнение Action
GetActionClass() Получить каталог с шаблонами экшена(совпадает с именем класса) Action
GetCurrentEventName() Возвращает имя евента Action
GetDefaultEvent() Получает евент по умолчанию Action
GetParam() Получает параметр из URL по его номеру, если его нет то null Action
GetParams() Получает список параметров из УРЛ Action
GetTemplate() Получить шаблон Action
Init() Абстрактный метод инициализации экшена Action
SetDefaultEvent() Устанавливает евент по умолчанию Action
SetParam() Установить значение параметра(эмуляция параметра в URL). Action
__call() Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля Action
__construct() Конструктор Action

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
AddEvent() Добавляет евент в экшен Action
AddEventPreg() Добавляет евент в экшен, используя регулярное вырожение для евента и параметров Action
EventNotFound() Вызывается в том случаи если не найден евент который запросили через URL Action
GetEventMatch() Возвращает элементы совпадения по регулярному выражению для евента Action
GetParamEventMatch() Возвращает элементы совпадения по регулярному выражению для параметров евента Action
RegisterEvent() Абстрактный метод регистрации евентов. 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;

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

oEngine property
protected Engine|null $oEngine;

Объект ядра

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

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

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

See Also

AddEventPreg() method
protected void AddEventPreg()
Source Code: /engine/classes/Action.class.php#117 (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];
    if (isset(
$aNames[1])) {
        
$aEvent['name']=$aNames[1];
    } else {
        
$aEvent['name']=$aEvent['method'];
    }
    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;
}

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

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

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

See Also

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

}

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

ExecEvent() method
public mixed ExecEvent()
{return} mixed
Source Code: /engine/classes/Action.class.php#151 (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'];
            
$this->Hook_Run("action_event_".strtolower($this->sCurrentAction)."_before",array('event'=>$this->sCurrentEvent,'params'=>$this->GetParams()));
            
$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: /engine/classes/Action.class.php#322 (show)
public function GetActionClass() {
    return 
Router::GetActionClass();
}

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

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

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

GetDefaultEvent() method
public string GetDefaultEvent()
{return} string
Source Code: /engine/classes/Action.class.php#192 (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: /engine/classes/Action.class.php#202 (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: /engine/classes/Action.class.php#242 (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: /engine/classes/Action.class.php#220 (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: /engine/classes/Action.class.php#252 (show)
public function GetParams() {
    return 
$this->aParams;
}

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

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

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

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

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

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

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

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

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

SetParam() method
public void SetParam(int $iOffset, string $value)
$iOffset int Номер параметра, но по идеи может быть не только числом
$value string
Source Code: /engine/classes/Action.class.php#264 (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: /engine/classes/Action.class.php#274 (show)
protected function SetTemplate($sTemplate) {
    
$this->sActionTemplate=$sTemplate;
}

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

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

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

__call() method
public mixed __call(string $sName, array $aArgs)
$sName string Имя метода
$aArgs array Аргументы
{return} mixed
Source Code: /engine/classes/Action.class.php#362 (show)
public function __call($sName,$aArgs) {
    return 
$this->oEngine->_CallModule($sName,$aArgs);
}

Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля

__construct() method
public void __construct(Engine $oEngine, string $sAction)
$oEngine Engine Объект ядра
$sAction string Название экшена
Source Code: /engine/classes/Action.class.php#94 (show)
public function __construct(Engine $oEngine$sAction) {
    
$this->RegisterEvent();
    
$this->oEngine=$oEngine;
    
$this->sCurrentAction=$sAction;
    
$this->aParams=Router::GetParams();
}

Конструктор