Chifa
Новичок
Объектная обертка к php_templates
php_templates - очень удобен с точки зрения скорости и принципа работы, но при его использовании тащит за собой все недостатки процедурного программирования.
Я написал к нему объектную обертку - возможно кому-нибудь пригодится. В идеале конечно же, если su1d реализует этот класс в одной из следующих версий своей библиотеки... ну а пока...
Помимо базовой функциональности библиотеки класс реализует централизованный отлов ошибок - наследование + свой метод error() позволяет обрабатывать ВСЕ ошибки библиотеки в одном месте
php_templates - очень удобен с точки зрения скорости и принципа работы, но при его использовании тащит за собой все недостатки процедурного программирования.
Я написал к нему объектную обертку - возможно кому-нибудь пригодится. В идеале конечно же, если su1d реализует этот класс в одной из следующих версий своей библиотеки... ну а пока...
Помимо базовой функциональности библиотеки класс реализует централизованный отлов ошибок - наследование + свой метод error() позволяет обрабатывать ВСЕ ошибки библиотеки в одном месте
PHP:
class PhpTemplate {
/**
* Handle of template created by tmpl_open() or tmpl_load()
*
* @var resource
*/
protected $template;
/**
* Can be overwritten to handle errors...
*
* @param string $method method name failure happens in
* @param string $message text description of error
* @return mixed result of error handler if is set; FALSE otherwize
*/
protected function error( $method, $message ) {
return FALSE;
}
/**
* Loads a template from file
*
* @param string $filename path to template (as in fopen())
* @param array $config when passed, engine reads the following configuration parameters from config array:
* <ul>
* <li>left - a string with left part of template tag</li>
* <li>right - right part of template tag</li>
* <li>ctx_ol - left part of template context opening tag ("context open left")</li>
* <li>ctx_or - right part of template context opening tag ("context open right")</li>
* <li>ctx_cl - left part of template context closing tag ("context close left")</li>
* <li>ctx_cr - right part of template context closing tag ("context close right")</li>
* </ul>
* @return boolean TRUE on success; value evaluated by error handler on failure
*/
public function open( $filename, $config = null ) {
if (is_null($config)) {
$res = tmpl_open($filename);
} else {
$res = tmpl_open($filename, $config);
}
$this->template = $res;
return (FALSE !== $res) ? TRUE : $this->error(__METHOD__, "cannot open template from file");
}
/**
* Loads a template from a string. Acts exactly like tmpl_open(), but instead of a filename with template,
* loads a template from template parameter.
*
* @param string $template variable with template content in
* @param array $config when passed, engine reads the following configuration parameters from config array:
* <ul>
* <li>left - a string with left part of template tag</li>
* <li>right - right part of template tag</li>
* <li>ctx_ol - left part of template context opening tag ("context open left")</li>
* <li>ctx_or - right part of template context opening tag ("context open right")</li>
* <li>ctx_cl - left part of template context closing tag ("context close left")</li>
* <li>ctx_cr - right part of template context closing tag ("context close right")</li>
* </ul>
* @return boolean TRUE on success; value evaluated by error handler on failure
*/
public function load( $template, $config = null ) {
if (is_null($config)) {
$res = tmpl_load($template);
} else {
$res = tmpl_load($template, $config);
}
$this->template = $res;
return (FALSE !== $res) ? TRUE : $this->error(__METHOD__, "cannot load template from variable");
}
/**
* Closes opened template handle.
*
* @return boolean TRUE on success; value evaluated by error handler on failure
*/
public function close(){
$res = tmpl_close($this->template);
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot close template");
}
/**
* Returns the value of a tag or a context in the last iteration.
*
* @param string $path path to tag or context
* @return mixed
* <ul>
* <li>When path points to a tag, the function returns tag's value in the last iteration of its context.</li>
* <li>When a context is addressed by path, the returned value is an array containing all values of tags
* and context within the the given context.</li>
* <li>Returns value evaluated by error handler on failure.</li>
* </ul>
*/
public function get( $path ) {
$res = tmpl_get($this->template, $path);
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot receive tag or context from last iteration");
}
/**
* Assigns a value to a template tag.
*
* @param string $path global or local path of a tag or context to receive values. This parameter
* should point to a template context when the value is an array.
* When called with two parameters, the path is assumed to be the current path
* in the template (see tmpl_context()).
* @param mixed $value Associative arrays provide values for tags named by array keys. Indexed arrays with
* subarrays in values create new iterations of the context pointed to by path.
* Template handle can be passed as a value too. In this case template is parsed
* and its resulting output is assigned to the tag.
* @return boolean TRUE on success; value evaluated by error handler on failure
*/
public function set( $path, $value = null ) {
if (is_null($value)) {
$value = $path;
if ($value instanceof PhpTemplate) $value = $value->template;
$res = tmpl_set($this->template, $value);
} else {
if ($value instanceof PhpTemplate) $value = $value->template;
$res = tmpl_set($this->template, $path, $value);
}
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot set tag value(s)");
}
/**
* Assigns a value to a tag with the same name in every context. When called every tag
* named by $tag parameter is assigned the value in every context of template.
*
* @param string $tag tag name
* @param string $value tag value
* @return boolean TRUE on success; value evaluated by error handler on failure
*/
public function set_global( $tag, $value ) {
$res = tmpl_set_global($this->template, $tag, $value);
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot set global tag value(s)");
}
/**
* Unassignes a value from a tag or empties a context. Deletes the value assigned to the tag pointed by path
* in the current iteration or deletes iterations of a context.
*
* @param string $path path to context or tag to unassign
* @return boolean TRUE on success; value evaluated by error handler on failure
*/
public function uset( $path ) {
$res = tmpl_unset($this->template, $path);
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot unset value of '$path'");
}
/**
* Changes the current context in a template and/or returns path to the current context.
* Template contexts are like directories in a file system, and tmpl_context() function is like
* a chdir command that you use in a command line shell.
* Every template context has its path from the root context which is a template itself.
* When passing a path parameter to any template function you may do that in both global
* (like '/context1/context2/tag') and local ('context2/tag' or '../context/tag') forms.
* You may not have two contexts with the same global path!
* Note, that a call to tmpl_context() on a context which is empty (without any template
* tags assigned in it) and not iterated, creates a new iteration of the given context!
*
* @param string $path path to template context from the root context; root context is a template itself.
* @return string global path to currently active template context;
* value evaluated by error handler on failure
*/
public function context( $path = null ) {
if (is_null($path)) {
$res = tmpl_context($this->template);
} else {
$res = tmpl_context($this->template, $path);
}
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot modify and/or receive current context");
}
/**
* This function iterates a context pointed to by path. By default empty contexts (which have no any tags
* assigned in them) are not parsed by tmpl_parse() function. If you want an empty context to appear
* on the page, it needs to be iterated. Every subsequent iteration of an empty context gives no result.
*
* @param string $path path to template context from the root context; root context is a template itself.
* @return boolean TRUE on success; value evaluated by error handler on failure
*/
public function iterate ( $path ) {
$res = tmpl_iterate($this->template, $path);
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot iterate template context for path = $path");
}
/**
* Parses a template. When you finished assigning values to template tags and contexts, you call tmpl_parse()
* to parse the loaded template and take the resulting content. The second optional parameter path points
* to a context to be parsed. In this case only the addressed context is parsed. You may call tmpl_parse()
* on a template as many times as you need.
*
* @param string $path optional parameter points to a context to be parsed. In this case only the addressed
* context is parsed.
* @return string parsed template content or value evaluated by error handler on failure
*/
public function parse( $path = null ) {
if (is_null($path)) {
$res = tmpl_parse($this->template);
} else {
$res = tmpl_parse($this->template, $path);
}
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "cannot parse template");
}
/**
* Retrieves template's structure.
* This function is useful when program doesn't know what template tags are present in template,
* and the code may depend on what tags are used in the template.
*
* @param string $path global or local path pointing to a context which structure is to be retrieved.
* The current path is used when this parameter is omitted.
* @param integer $mask filters the function's output by elements type. It could be set to one of three values:
* <ul>
* <li>TMPL_TAG - only retrieve paths to template tags. This is the default value.</li>
* <li>TMPL_CONTEXT - only retrieve paths to template contexts.</li>
* <li>TMPL_TAG | TMPL_CONTEXT - get both tags and contexts paths.</li>
* </ul>
* @param integer $mode changes the structure of resulting array and could take one of the following values:
* <ul>
* <li>TMPL_LONG - retrieve full path to every template element. Context paths
* are terminated with a slash (/) character and tag paths are not. This is
* the default value.</li>
* <li>TMPL_SHORT - only get a tag or a context name without full path to the root</li>
* </ul>
* @return array Returns array with template tags and contexts hierarchy or
* value evaluated by error handler on failure
*/
public function structure( $path = null, $mask = null, $mode = null ) {
if (is_null($path)) {
$res = tmpl_structure($this->template);
} else
if (is_null($mask)) {
$res = tmpl_structure($this->template, $path);
} else
if (is_null($mode)) {
$res = tmpl_structure($this->template, $path, $mask);
} else {
$res = tmpl_structure($this->template, $path, $mask, $mode);
}
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "template does not contain any structure");
}
/**
* Checks type of template element
*
* @param string $path global or local path pointing to a context which structure is to be retrieved.
* @return integer TMPL_TAG when path is pointing to a tag, and TMPL_CONTEXT when a context
* is pointed to by path.
* value evaluated by error handler when given path doesn't exist in the template.
*/
public function type_of( $path ) {
$res = tmpl_type_of($this->template, $path);
return (FALSE !== $res) ? $res : $this->error(__METHOD__, "path '$path' does not exists in template");
}
}