├── tests ├── simple_var.html ├── simple_object.html ├── modifier.html ├── multiple_files_child.html ├── multiple_files_parent.html ├── escape_var.html ├── README.md ├── simple_block.html ├── clear_var_in_block.html ├── finally_block.html ├── nested_block.html ├── comments.html └── TemplateTest.php ├── .gitignore ├── composer.json ├── CHANGELOG.md ├── .circleci └── config.yml ├── raelgc └── view │ └── Template.php ├── LICENSE └── README.md /tests/simple_var.html: -------------------------------------------------------------------------------- 1 | {FOO} 2 | -------------------------------------------------------------------------------- /tests/simple_object.html: -------------------------------------------------------------------------------- 1 | {FOO->bar} -------------------------------------------------------------------------------- /tests/modifier.html: -------------------------------------------------------------------------------- 1 | {foo|replace:Bar:Baz} -------------------------------------------------------------------------------- /tests/multiple_files_child.html: -------------------------------------------------------------------------------- 1 |

{VAR}

2 | -------------------------------------------------------------------------------- /tests/multiple_files_parent.html: -------------------------------------------------------------------------------- 1 |
{CONTENT}
2 | -------------------------------------------------------------------------------- /tests/escape_var.html: -------------------------------------------------------------------------------- 1 | This is an escaped var: 2 | {{_}FOO} 3 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | Run: 2 | 3 | ./vendor/bin/phpunit tests 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | .buildpath 3 | .settings 4 | nbproject/ 5 | vendor/ 6 | composer.lock 7 | -------------------------------------------------------------------------------- /tests/simple_block.html: -------------------------------------------------------------------------------- 1 | 2 | Text with VAR: {FOO} 3 | 4 | -------------------------------------------------------------------------------- /tests/clear_var_in_block.html: -------------------------------------------------------------------------------- 1 | 2 | Test if {VALUE} is {SELECTED} 3 | 4 | -------------------------------------------------------------------------------- /tests/finally_block.html: -------------------------------------------------------------------------------- 1 | 2 | Text with VAR: {FOO} 3 | 4 | Content in finally block 5 | 6 | -------------------------------------------------------------------------------- /tests/nested_block.html: -------------------------------------------------------------------------------- 1 | 2 | Out top content with {OUT_TOP_VAR} 3 | 4 | Inner content with {INNER_VAR}- 5 | 6 | Out bottom content with {OUT_BOTTOM_VAR} 7 | 8 | 9 | -------------------------------------------------------------------------------- /tests/comments.html: -------------------------------------------------------------------------------- 1 | 4 | 5 | Out top content with {OUT_TOP_VAR} 6 | 7 | Inner content with {INNER_VAR}- 8 | 9 | Out bottom content with {OUT_BOTTOM_VAR} 10 | 11 | 12 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "raelgc/template", 3 | "description": "PHP Template", 4 | "keywords": ["template"], 5 | "homepage": "http://raelcunha.com/template/", 6 | "license": "LGPL-2.1-or-later", 7 | "authors": [{ 8 | "name": "Rael Gugelmin Cunha", 9 | "email": "rael.gc@gmail.com" 10 | }], 11 | "require": { 12 | "php": ">=5.3.0" 13 | }, 14 | "autoload": { 15 | "psr-4": { "raelgc\\": "raelgc" } 16 | }, 17 | "require-dev": { 18 | "phpunit/phpunit": "^5" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 14/01/2021 - Fix #35 - Removendo chamada `each`, que ficou obsoleta no PHP 7.2 2 | 15/05/2020 - Fix #38 - Se a variável é objeto, mostra o json ao invés da palavra "Object" 3 | 14/04/2020 - Todos os métodos `private` foram convertidos para `protected` 4 | 13/04/2020 - Aceitando atributos de objetos em camelCase e snake_case 5 | 15/02/2019 - Melhorando o markdown do arquivo README 6 | 13/02/2019 - Atualizando composer para suportar novo esquema de versionamento 7 | 03/03/2018 - Adicionando o arquivo composer.json 8 | 09/02/2016 - Restaurando parâmetro `$append` do método `block()` 9 | 13/12/2015 - Suporte a HTML Minificado 10 | 25/07/2014 - Adicionando informação sobre escape para variáveis 11 | 27/06/2014 - Versão 2.2: Arrumando ordem de leitura dos atributos de uma classe (obrigado @eduardoeldorado) 12 | 26/02/2014 - Versão 2.0: [suporte a namespace](#instala%C3%A7%C3%A3o-e-uso), [blocos finally](#blocos-finally), [parser automático de blocos pai](#blocos-autom%C3%A1ticos-por-padr%C3%A3o), [modificadores](#vari%C3%A1veis-com-modificadores) 13 | 25/02/2014 - Movendo para o [Github](https://github.com/raelgc/template) 14 | 17/10/2012 - Suporte a arquivos PHP no método addFile() 15 | 06/04/2010 - Adicionado método exists() para checar existência de uma variável 16 | 20/07/2009 - Adicionado suporte a comentários e pequena melhora no desempenho 17 | 07/05/2009 - Substituídas Exceptions genéricas pelas Exceptions da SPL 18 | 05/05/2009 - Valor do parâmetro `$append` do método `block()` alterado para `true` 19 | 04/05/2009 - Renomeados: método `parseBlock()` para `block()`, `getContent()` para `parse()`, `clearVar` para `clear()` 20 | 10/08/2008 - Adicionadas informações sobre html select 21 | 26/02/2008 - Versão inicial do Tutorial 22 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # PHP CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-php/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # Specify the version you desire here 10 | - image: circleci/php:7.1-node-browsers 11 | 12 | # Specify service dependencies here if necessary 13 | # CircleCI maintains a library of pre-built images 14 | # documented at https://circleci.com/docs/2.0/circleci-images/ 15 | # Using the RAM variation mitigates I/O contention 16 | # for database intensive operations. 17 | # - image: circleci/mysql:5.7-ram 18 | # 19 | # - image: redis:2.8.19 20 | 21 | steps: 22 | - checkout 23 | 24 | - run: sudo apt update 25 | # - run: sudo apt install zlib1g-dev libsqlite3-dev composer php-xml 26 | - run: sudo docker-php-ext-install zip 27 | 28 | # Download and cache dependencies 29 | - restore_cache: 30 | keys: 31 | # "composer.lock" can be used if it is committed to the repo 32 | - v1-dependencies-{{ checksum "composer.json" }} 33 | # fallback to using the latest cache if no exact match is found 34 | - v1-dependencies- 35 | 36 | - run: composer install -n --prefer-dist 37 | 38 | - save_cache: 39 | key: v1-dependencies-{{ checksum "composer.json" }} 40 | paths: 41 | - ./vendor 42 | - restore_cache: 43 | keys: 44 | - node-v1-{{ checksum "package.json" }} 45 | - node-v1- 46 | - save_cache: 47 | key: node-v1-{{ checksum "package.json" }} 48 | paths: 49 | - node_modules 50 | 51 | # run tests with phpunit or codecept 52 | #- run: ./vendor/bin/phpunit 53 | - run: ./vendor/bin/phpunit tests/ 54 | -------------------------------------------------------------------------------- /tests/TemplateTest.php: -------------------------------------------------------------------------------- 1 | FOO = 'bar'; 14 | $this->assertEquals('bar', trim($tpl->parse())); 15 | } 16 | 17 | public function testIfVarExists() 18 | { 19 | $tpl = new Template(__DIR__ . '/simple_var.html'); 20 | if ($tpl->exists('FOO')) { 21 | $tpl->FOO = 'bar'; 22 | } 23 | $this->assertEquals('bar', trim($tpl->parse())); 24 | } 25 | 26 | public function testIfVarDoNotExists() 27 | { 28 | $tpl = new Template(__DIR__ . '/simple_var.html'); 29 | // variables are casesensitive 30 | if ($tpl->exists('foo')) { 31 | $tpl->foo = 'bar'; 32 | } 33 | $this->assertEquals('', trim($tpl->parse())); 34 | } 35 | 36 | public function testModifiers() { 37 | $tpl = new Template(__DIR__ . '/modifier.html'); 38 | $tpl->foo = 'Bar'; 39 | $this->assertEquals('Baz', trim($tpl->parse())); 40 | } 41 | 42 | public function testUnparsedBlock() 43 | { 44 | $tpl = new Template(__DIR__ . '/simple_block.html'); 45 | $tpl->FOO = 'bar'; 46 | $this->assertEquals('', trim($tpl->parse())); 47 | } 48 | 49 | public function testSimpleBlock() 50 | { 51 | $tpl = new Template(__DIR__ . '/simple_block.html'); 52 | $tpl->FOO = 'bar'; 53 | $tpl->block("BLOCK_SIMPLE"); 54 | $tpl->FOO = 'baz'; 55 | $tpl->block("BLOCK_SIMPLE"); 56 | $this->assertEquals("Text with VAR: bar\nText with VAR: baz", trim($tpl->parse())); 57 | } 58 | 59 | public function testNestedBlocks() 60 | { 61 | $tpl = new Template(__DIR__ . '/nested_block.html'); 62 | $tpl->OUT_TOP_VAR = 'foo'; 63 | $tpl->OUT_BOTTOM_VAR = 'bar'; 64 | $tpl->INNER_VAR = 'baz'; 65 | $tpl->block("BLOCK_INNER"); 66 | $tpl->INNER_VAR = 'qux'; 67 | $tpl->block("BLOCK_INNER"); 68 | $this->assertEquals("Out top content with foo\nInner content with baz-\nInner content with qux-\nOut bottom content with bar", trim($tpl->parse())); 69 | } 70 | 71 | public function testUnparsedFinallyBlock() 72 | { 73 | $tpl = new Template(__DIR__ . '/finally_block.html'); 74 | $tpl->FOO = 'bar'; 75 | $tpl->block("BLOCK_SIMPLE"); 76 | $this->assertEquals('Text with VAR: bar', trim($tpl->parse())); 77 | } 78 | 79 | 80 | public function testFinallyBlock() 81 | { 82 | $tpl = new Template(__DIR__ . '/finally_block.html'); 83 | $this->assertEquals('Content in finally block', trim($tpl->parse())); 84 | } 85 | 86 | public function testClearVarBlock() 87 | { 88 | $tpl = new Template(__DIR__ . '/clear_var_in_block.html'); 89 | $tpl->VALUE = 'foo'; 90 | $tpl->SELECTED = 'selected'; 91 | $tpl->block('BLOCK_OPTION'); 92 | $tpl->clear('SELECTED'); 93 | $tpl->block('BLOCK_OPTION'); 94 | $this->assertEquals("Test if foo is selected\nTest if foo is", trim($tpl->parse())); 95 | } 96 | 97 | public function testMultipleFiles() 98 | { 99 | $tpl = new Template(__DIR__ . '/multiple_files_parent.html'); 100 | $tpl->addFile('CONTENT', __DIR__ . '/multiple_files_child.html'); 101 | $tpl->VAR = 'foo'; 102 | $this->assertEquals("

foo

\n
", trim($tpl->parse())); 103 | } 104 | 105 | public function testSimpleObject() 106 | { 107 | $tpl = new Template(__DIR__ . '/simple_object.html'); 108 | $foo = new stdClass; 109 | $foo->bar = 'foobar'; 110 | $tpl->FOO = $foo; 111 | $this->assertEquals('foobar', trim($tpl->parse())); 112 | } 113 | 114 | public function testObjectWithGetter() 115 | { 116 | $tpl = new Template(__DIR__ . '/simple_object.html'); 117 | $foo = new class { 118 | private $bar; 119 | public function setBar($bar) { 120 | $this->bar = $bar; 121 | } 122 | public function getBar() { 123 | return $this->bar; 124 | } 125 | }; 126 | $foo->setBar('foobar'); 127 | $tpl->FOO = $foo; 128 | $this->assertEquals('foobar', trim($tpl->parse())); 129 | } 130 | 131 | public function testObjectWithMagicGet() 132 | { 133 | $tpl = new Template(__DIR__ . '/simple_object.html'); 134 | $foo = new class { 135 | private $bar; 136 | public function setBar($bar) { 137 | $this->bar = $bar; 138 | } 139 | public function __get($var) { 140 | return $this->bar; 141 | } 142 | }; 143 | $foo->setBar('foobar'); 144 | $tpl->FOO = $foo; 145 | $this->assertEquals('foobar', trim($tpl->parse())); 146 | } 147 | 148 | public function testObjectWithToString() 149 | { 150 | $tpl = new Template(__DIR__ . '/simple_var.html'); 151 | $foo = new class { 152 | public function setBar($bar) { 153 | $this->bar = $bar; 154 | } 155 | public function __toString() { 156 | return $this->bar; 157 | } 158 | }; 159 | $foo->setBar('foobar'); 160 | $tpl->FOO = $foo; 161 | $this->assertEquals('foobar', trim($tpl->parse())); 162 | } 163 | 164 | public function testArrayParse() 165 | { 166 | $tpl = new Template(__DIR__ . '/simple_var.html'); 167 | $foo = ['bar', 'baz', 'qux']; 168 | $tpl->FOO = $foo; 169 | $this->assertEquals('bar, baz, qux', trim($tpl->parse())); 170 | } 171 | 172 | public function testObjectParse() 173 | { 174 | $tpl = new Template(__DIR__ . '/simple_var.html'); 175 | $foo = new class { 176 | public function setBar($bar) { 177 | $this->bar = $bar; 178 | } 179 | }; 180 | $foo->setBar('foobar'); 181 | $tpl->FOO = $foo; 182 | $this->assertEquals('Object: {"bar":"foobar"}', trim($tpl->parse())); 183 | } 184 | 185 | public function testFailureSimpleObjectCaseMismatch() 186 | { 187 | $this->expectException(RuntimeException::class); 188 | $tpl = new Template(__DIR__ . '/simple_object.html'); 189 | $foo = new stdClass; 190 | $foo->bar = 'foobar'; 191 | // foo is set lowercase but template calls FOO (uppercase) 192 | $tpl->foo = $foo; 193 | $tpl->parse(); 194 | } 195 | 196 | public function testComments() 197 | { 198 | $tpl = new Template(__DIR__ . '/comments.html'); 199 | $tpl->OUT_TOP_VAR = 'foo'; 200 | $tpl->OUT_BOTTOM_VAR = 'bar'; 201 | $tpl->INNER_VAR = 'baz'; 202 | $tpl->block("BLOCK_INNER"); 203 | $tpl->INNER_VAR = 'qux'; 204 | $tpl->block("BLOCK_INNER"); 205 | $this->assertEquals("Out top content with foo\nInner content with baz-\nInner content with qux-\nOut bottom content with bar", trim($tpl->parse())); 206 | } 207 | 208 | public function testEscapeVar() 209 | { 210 | $tpl = new Template(__DIR__ . '/escape_var.html'); 211 | $this->assertEquals("This is an escaped var:\n{FOO}", trim($tpl->parse())); 212 | } 213 | 214 | } 215 | -------------------------------------------------------------------------------- /raelgc/view/Template.php: -------------------------------------------------------------------------------- 1 | accurate = $accurate; 104 | $this->loadfile(".", $filename); 105 | } 106 | 107 | /** 108 | * Put the content of $filename in the template variable identified by $varname 109 | * 110 | * @param string $varname existing template var 111 | * @param string $filename file to be loaded 112 | */ 113 | public function addFile($varname, $filename){ 114 | if(!$this->exists($varname)) throw new \InvalidArgumentException("addFile: var $varname does not exist"); 115 | $this->loadfile($varname, $filename); 116 | } 117 | 118 | /** 119 | * Do not use. Properties setter method 120 | * 121 | * @param string $varname template var name 122 | * @param mixed $value template var value 123 | */ 124 | public function __set($varname, $value){ 125 | if(!$this->exists($varname)) throw new \RuntimeException("var $varname does not exist"); 126 | $stringValue = $value; 127 | if(is_object($value)){ 128 | $this->instances[$varname] = $value; 129 | if(!isset($this->properties[$varname])) $this->properties[$varname] = array(); 130 | if(method_exists($value, "__toString")) $stringValue = $value->__toString(); 131 | else $stringValue = 'Object: '.json_encode($value); 132 | } elseif (is_array($value)) { 133 | $stringValue = implode(', ', $value); 134 | } 135 | $this->setValue($varname, $stringValue); 136 | return $value; 137 | } 138 | 139 | /** 140 | * Do not use. Properties getter method. 141 | * 142 | * @param string $varname template var name 143 | */ 144 | public function __get($varname){ 145 | if(isset($this->values["{".$varname."}"])) return $this->values["{".$varname."}"]; 146 | elseif(isset($this->instances[$varname])) return $this->instances[$varname]; 147 | throw new \RuntimeException("var $varname does not exist"); 148 | } 149 | 150 | /** 151 | * Check if a template var exists. 152 | * 153 | * This method returns true if the template var exists. Otherwise, false. 154 | * 155 | * @param string $varname template var name 156 | */ 157 | public function exists($varname){ 158 | return in_array($varname, $this->vars); 159 | } 160 | 161 | /** 162 | * Loads a file identified by $filename. 163 | * 164 | * The file will be loaded and the file's contents will be assigned as the 165 | * variable's value. 166 | * Additionally, this method call Template::identify() that identifies 167 | * all blocks and variables automatically. 168 | * 169 | * @param string $varname contains the name of a variable to load 170 | * @param string $filename file name to be loaded 171 | * 172 | * @return void 173 | */ 174 | protected function loadfile($varname, $filename) { 175 | if (!file_exists($filename)) throw new \InvalidArgumentException("file $filename does not exist"); 176 | // If it's PHP file, parse it 177 | if($this->isPHP($filename)){ 178 | ob_start(); 179 | require $filename; 180 | $str = ob_get_contents(); 181 | ob_end_clean(); 182 | $this->setValue($varname, $str); 183 | } else { 184 | // Reading file and hiding comments 185 | $str = preg_replace("//smi", "", file_get_contents($filename)); 186 | if (empty($str)) throw new \InvalidArgumentException("file $filename is empty"); 187 | $this->setValue($varname, $str); 188 | $blocks = $this->identify($str, $varname); 189 | $this->createBlocks($blocks); 190 | } 191 | } 192 | 193 | /** 194 | * Check if file is a .php 195 | */ 196 | protected function isPHP($filename){ 197 | foreach(array('.php', '.php5', '.cgi') as $php){ 198 | if(0 == strcasecmp($php, substr($filename, strripos($filename, $php)))) return true; 199 | } 200 | return false; 201 | } 202 | 203 | /** 204 | * Identify all blocks and variables automatically and return them. 205 | * 206 | * All variables and blocks are already identified at the moment when 207 | * user calls Template::setFile(). This method calls Template::identifyVars() 208 | * and Template::identifyBlocks() methods to do the job. 209 | * 210 | * @param string $content file content 211 | * @param string $varname contains the variable name of the file 212 | * 213 | * @return array an array where the key is the block name and the value is an 214 | * array with the children block names. 215 | */ 216 | protected function identify(&$content, $varname){ 217 | $blocks = array(); 218 | $queued_blocks = array(); 219 | $this->identifyVars($content); 220 | $lines = explode("\n", $content); 221 | // Checking for minified HTML 222 | if(1==sizeof($lines)){ 223 | $content = str_replace('-->', "-->\n", $content); 224 | $lines = explode("\n", $content); 225 | } 226 | foreach (explode("\n", $content) as $line) { 227 | if (strpos($line, "/sm"; 244 | preg_match($reg, $line, $m); 245 | if (1==preg_match($reg, $line, $m)){ 246 | if (0==sizeof($queued_blocks)) $parent = $varname; 247 | else $parent = end($queued_blocks); 248 | if (!isset($blocks[$parent])){ 249 | $blocks[$parent] = array(); 250 | } 251 | $blocks[$parent][] = $m[1]; 252 | $queued_blocks[] = $m[1]; 253 | } 254 | $reg = "//sm"; 255 | if (1==preg_match($reg, $line)) array_pop($queued_blocks); 256 | } 257 | 258 | /** 259 | * Identifies all variables defined in the document. 260 | * 261 | * @param string $content file content 262 | */ 263 | protected function identifyVars(&$content){ 264 | $r = preg_match_all("/{(".self::$REG_NAME.")((\-\>(".self::$REG_NAME."))*)?((\|.*?)*)?}/", $content, $m); 265 | if ($r){ 266 | for($i=0; $i<$r; $i++){ 267 | // Object var detected 268 | if($m[3][$i] && (!isset($this->properties[$m[1][$i]]) || !in_array($m[3][$i], $this->properties[$m[1][$i]]))){ 269 | $this->properties[$m[1][$i]][] = $m[3][$i]; 270 | } 271 | // Modifiers detected 272 | if($m[7][$i] && (!isset($this->modifiers[$m[1][$i]]) || !in_array($m[7][$i], $this->modifiers[$m[1][$i].$m[3][$i]]))){ 273 | $this->modifiers[$m[1][$i].$m[3][$i]][] = $m[1][$i].$m[3][$i].$m[7][$i]; 274 | } 275 | // Common variables 276 | if(!in_array($m[1][$i], $this->vars)){ 277 | $this->vars[] = $m[1][$i]; 278 | } 279 | } 280 | } 281 | } 282 | 283 | /** 284 | * Create all identified blocks given by Template::identifyBlocks(). 285 | * 286 | * @param array $blocks contains all identified block names 287 | * @return void 288 | */ 289 | protected function createBlocks(&$blocks) { 290 | $this->parents = array_merge($this->parents, $blocks); 291 | foreach($blocks as $parent => $block){ 292 | foreach($block as $chield){ 293 | if(in_array($chield, $this->blocks)) throw new \UnexpectedValueException("duplicated block: $chield"); 294 | $this->blocks[] = $chield; 295 | $this->setBlock($parent, $chield); 296 | } 297 | } 298 | } 299 | 300 | /** 301 | * A variable $parent may contain a variable block defined by: 302 | * <!-- BEGIN $varname --> content <!-- END $varname -->. 303 | * 304 | * This method removes that block from $parent and replaces it with a variable 305 | * reference named $block. 306 | * Blocks may be nested. 307 | * 308 | * @param string $parent contains the name of the parent variable 309 | * @param string $block contains the name of the block to be replaced 310 | * @return void 311 | */ 312 | protected function setBlock($parent, $block) { 313 | $name = $block.'_value'; 314 | $str = $this->getVar($parent); 315 | if($this->accurate){ 316 | $str = str_replace("\r\n", "\n", $str); 317 | $reg = "/\t*\n*(\s*.*?\n?)\t*\n*((\s*.*?\n?)\t*\n?)?/sm"; 318 | } 319 | else $reg = "/\s*(\s*.*?\s*)\s*((\s*.*?\s*))?\s*/sm"; 320 | if(1!==preg_match($reg, $str, $m)) throw new \UnexpectedValueException("mal-formed block $block"); 321 | $this->setValue($name, ''); 322 | $this->setValue($block, $m[1]); 323 | $this->setValue($parent, preg_replace($reg, "{".$name."}", $str)); 324 | if(isset($m[3])) $this->finally[$block] = $m[3]; 325 | } 326 | 327 | /** 328 | * Internal setValue() method. 329 | * 330 | * The main difference between this and Template::__set() method is this 331 | * method cannot be called by the user, and can be called using variables or 332 | * blocks as parameters. 333 | * 334 | * @param string $varname constains a varname 335 | * @param string $value constains the new value for the variable 336 | * @return void 337 | */ 338 | protected function setValue($varname, $value) { 339 | $this->values['{'.$varname.'}'] = $value; 340 | } 341 | 342 | /** 343 | * Returns the value of the variable identified by $varname. 344 | * 345 | * @param string $varname the name of the variable to get the value of 346 | * @return string the value of the variable passed as argument 347 | */ 348 | protected function getVar($varname) { 349 | return $this->values['{'.$varname.'}']; 350 | } 351 | 352 | /** 353 | * Clear the value of a variable. 354 | * 355 | * Alias for $this->setValue($varname, ""); 356 | * 357 | * @param string $varname var name to be cleaned 358 | * @return void 359 | */ 360 | public function clear($varname) { 361 | $this->setValue($varname, ""); 362 | } 363 | 364 | /** 365 | * Manually assign a child block to a parent block 366 | * 367 | * @param string $parent parent block 368 | * @param string $block child block 369 | */ 370 | public function setParent($parent, $block){ 371 | $this->parents[$parent][] = $block; 372 | } 373 | 374 | /** 375 | * Subst modifiers content 376 | * 377 | * @param string $value text to be modified 378 | * @param $exp 379 | * @return unknown_type 380 | */ 381 | protected function substModifiers($value, $exp){ 382 | $statements = explode('|', $exp); 383 | for($i=1; $ivalues), $this->values, $value); 402 | // Common variables with modifiers 403 | foreach($this->modifiers as $var => $expressions){ 404 | if(false!==strpos($s, "{".$var."|")) foreach($expressions as $exp){ 405 | if(false===strpos($var, "->") && isset($this->values['{'.$var.'}'])){ 406 | $s = str_replace('{'.$exp.'}', $this->substModifiers($this->values['{'.$var.'}'], $exp), $s); 407 | } 408 | } 409 | } 410 | // Object variables replacement 411 | foreach($this->instances as $var => $instance){ 412 | foreach($this->properties[$var] as $properties){ 413 | if(false!==strpos($s, "{".$var.$properties."}") || false!==strpos($s, "{".$var.$properties."|")){ 414 | $pointer = $instance; 415 | $property = explode("->", $properties); 416 | for($i = 1; $i < sizeof($property); $i++){ 417 | if(!is_null($pointer)){ 418 | $obj = strtolower(str_replace('_', '', $property[$i])); 419 | // Get accessor 420 | if(method_exists($pointer, "get$obj")) $pointer = $pointer->{"get$obj"}(); 421 | // Magic __get accessor 422 | elseif(method_exists($pointer, "__get")) $pointer = $pointer->__get($property[$i]); 423 | // Property acessor 424 | elseif(property_exists($pointer, $obj)) $pointer = $pointer->$obj; 425 | elseif(property_exists($pointer, $property[$i])) $pointer = $pointer->{$property[$i]}; 426 | else { 427 | $className = $property[$i-1] ? $property[$i-1] : get_class($instance); 428 | $class = is_null($pointer) ? "NULL" : get_class($pointer); 429 | throw new \BadMethodCallException("no accessor method in class ".$class." for ".$className."->".$property[$i]); 430 | } 431 | } else { 432 | $pointer = $instance->get($obj); 433 | } 434 | } 435 | // Replacing value 436 | $s = str_replace("{".$var.$properties."}", $pointer, $s); 437 | // Object with modifiers 438 | if(isset($this->modifiers[$var.$properties])){ 439 | foreach($this->modifiers[$var.$properties] as $exp){ 440 | $s = str_replace('{'.$exp.'}', $this->substModifiers($pointer, $exp), $s); 441 | } 442 | } 443 | } 444 | } 445 | } 446 | return $s; 447 | } 448 | 449 | /** 450 | * Show a block. 451 | * 452 | * This method must be called when a block must be showed. 453 | * Otherwise, the block will not appear in the resultant 454 | * content. 455 | * 456 | * @param string $block the block name to be parsed 457 | * @param boolean $append true if the content must be appended 458 | */ 459 | public function block($block, $append = true) { 460 | if(!in_array($block, $this->blocks)) throw new \InvalidArgumentException("block $block does not exist"); 461 | // Checking finally blocks inside this block 462 | if(isset($this->parents[$block])) foreach($this->parents[$block] as $child){ 463 | if(isset($this->finally[$child]) && !in_array($child, $this->parsed)){ 464 | $this->setValue($child.'_value', $this->subst($this->finally[$child])); 465 | $this->parsed[] = $block; 466 | } 467 | } 468 | if ($append) { 469 | $this->setValue($block.'_value', $this->getVar($block.'_value') . $this->subst($this->getVar($block))); 470 | } else { 471 | $this->setValue($block.'_value', $this->getVar($block.'_value')); 472 | } 473 | if(!in_array($block, $this->parsed)) $this->parsed[] = $block; 474 | // Cleaning children 475 | if(isset($this->parents[$block])) foreach($this->parents[$block] as $child) $this->clear($child.'_value'); 476 | } 477 | 478 | /** 479 | * Returns the final content 480 | * 481 | * @return string 482 | */ 483 | public function parse() { 484 | // Auto assistance for parse children blocks 485 | foreach(array_reverse($this->parents) as $parent => $children){ 486 | foreach($children as $block){ 487 | if(in_array($parent, $this->blocks) && in_array($block, $this->parsed) && !in_array($parent, $this->parsed)){ 488 | $this->setValue($parent.'_value', $this->subst($this->getVar($parent))); 489 | $this->parsed[] = $parent; 490 | } 491 | } 492 | } 493 | // Parsing finally blocks 494 | foreach($this->finally as $block => $content){ 495 | if(!in_array($block, $this->parsed)){ 496 | $this->setValue($block.'_value', $this->subst($content)); 497 | } 498 | } 499 | // After subst, remove empty vars 500 | return preg_replace("/{(".self::$REG_NAME.")((\-\>(".self::$REG_NAME."))*)?((\|.*?)*)?}/", "", $this->subst($this->getVar("."))); 501 | } 502 | 503 | /** 504 | * Print the final content. 505 | */ 506 | public function show() { 507 | echo $this->parse(); 508 | } 509 | 510 | } 511 | 512 | } 513 | 514 | namespace { 515 | 516 | /** 517 | * Suitable for Template class: similar to str_replace, but using string in first param 518 | * @see str_replace 519 | * @param string $str 520 | * @param string $search 521 | * @param string $replace 522 | * @return mixed 523 | * @author Rael G.C. (rael.gc@gmail.com) 524 | */ 525 | function replace($str, $search, $replace){ 526 | return str_replace($search, $replace, $str); 527 | } 528 | 529 | } 530 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | {signature of Ty Coon}, 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![raelgc](https://circleci.com/gh/raelgc/template.svg?style=svg)](https://app.circleci.com/pipelines/github/raelgc/template) 2 | 3 | Tutorial de Templates em PHP 4 | ======== 5 | 6 | Uma das coisas que as pessoas mais me perguntam sobre PHP, é sobre o uso de Templates. Ou porque leram em algum livro ou fórum, ou seja porque eu comentei em aula. 7 | 8 | Através do uso de templates, deixamos toda a estrutura visual (HTML ou XML, CSS, etc) separado da lógica de programação (código PHP), o que melhora e muito tanto a construção quanto a manutenção de sistemas web. 9 | Existem vários mecanismo de template para PHP, e há um bom tempo no mercado. Mas qual indicar? Sem dúvida alguma, o Smarty é hoje o mais completo deles. Porém, o mais complexo, e de curva mais demorada. Ele é praticamente uma linguagem a parte do PHP. 10 | 11 | Com base nisso, eu resolvi colocar criar um tutorial baseado em um mecanismo de template muito mais simples. Ou seja: este não é um tutorial sobre o Smarty. É sobre Templates, mas baseado uma biblioteca que eu mesmo desenvolvi, e uso em meus projetos (mesmo nos maiores deles), na qual gastei bastante tempo desenvolvendo e melhorando, sempre com o foco principal na facilidade de uso. 12 | 13 | Mas quase todos os conceitos vistos neste tutorial se aplicam a maioria das classes de Template existentes em PHP, portanto, se você entender as idéias explicadas aqui, poderá usar seu mecanismo de Templates favorito. 14 | Para criar esta biblioteca (eu uso templates há muitos anos, quando só existia a PHPLib), eu estudei vários mecanismos de templates (PHPLib, Sigma, etc), portanto não estou "reinventando a roda", apenas "me apoiei no ombro de gigantes" para criar algo muito mais fácil de usar, que atendesse minhas necessidades e da empresa que eu trabalhava na época. De fato, atualmente muita gente usa esta biblioteca. 15 | 16 | Eu inclusive traduzi os comentários dos métodos/funções públicos para facilitar. Você verá que será preciso entender apenas duas idéias básicas: variáveis e blocos. 17 | 18 | Então, vamos lá. 19 | 20 | 21 | ## Changelog 22 | 23 | Por favor, cheque o arquivo de [CHANGELOG](CHANGELOG.md). 24 | 25 | 26 | ## Requisitos Necessários 27 | 28 | É preciso usar qualquer versão do PHP igual ou superior a `5.3`. 29 | 30 | 31 | ## Instalação 32 | 33 | Você pode escolher instalar a biblioteca: 34 | 1. via Composer, 35 | 2. via Git, 36 | 3. ou fazer o download de um arquivo `.zip`. 37 | 38 | ### 1. Via Composer 39 | 40 | Para baixar a biblioteca via Composer, execute o comando: 41 | 42 | ```bash 43 | composer require raelgc/template 44 | ``` 45 | 46 | 1 - Use `require_once` para incluir o autoload e a diretiva `use` para informar o [namespace](http://www.php.net/manual/pt_BR/language.namespaces.rationale.php) da classe Template, da seguinte forma: 47 | 48 | ```php 49 | 55 | ``` 56 | 57 | 58 | ### 2. Via Git 59 | 60 | Para baixar a biblioteca via Git, execute o comando: 61 | 62 | ```bash 63 | git clone https://github.com/raelgc/template.git 64 | ``` 65 | 66 | 1 - Crie uma pasta `lib` no seu projeto. 67 | 68 | 2 - Abra a pasta `template` e copie a pasta `raelgc` (e todo seu conteúdo) para dentro da pasta `lib` do seu projeto. 69 | 70 | 3 - Use `require_once` para incluir a classe Template e a diretiva `use` para informar o [namespace](http://www.php.net/manual/pt_BR/language.namespaces.rationale.php) da classe, da seguinte forma: 71 | 72 | ```php 73 | 79 | ``` 80 | 81 | 82 | ### 3. Via Download 83 | 84 | Para baixar um arquivo `.zip` contendo a biblioteca, clique [aqui](https://github.com/raelgc/template/archive/master.zip). 85 | 86 | 1 - Descompacte o arquivo `.zip`. 87 | 88 | 2 - Crie uma pasta `lib` no seu projeto. 89 | 90 | 3 - Copie a pasta `raelgc` (e todo seu conteúdo) para dentro da pasta `lib` do seu projeto. 91 | 92 | 4 - Use `require_once` para incluir a classe Template e a diretiva `use` para informar o [namespace](http://www.php.net/manual/pt_BR/language.namespaces.rationale.php) da classe, da seguinte forma: 93 | 94 | ```php 95 | 101 | ``` 102 | 103 | 104 | ## Exemplo e explicação: Olá Mundo 105 | 106 | O funcionamento básico do mecanismo de templates é baseado na seguinte idéia: você tem um arquivo PHP (que usará a biblioteca), e este arquivo não conterá código HTML algum. O código HTML ficará separado, em um arquivo que conterá somente códigos HTML. Este arquivo HTML será lido pelo arquivo PHP. Aliás, tudo será processado no arquivo PHP. 107 | 108 | Dito isso, vamos ao primeiro exemplo, o já manjado Olá mundo. Vamos criar 2 arquivos: o PHP responsável por toda a lógica, e o arquivo HTML com nosso layout. 109 | 110 | Então, crie um arquivo HTML, chamado hello.html com o conteúdo abaixo: 111 | 112 | ```html 113 | 114 | 115 | 116 | Olá Mundo, com templates PHP! 117 | 118 | 119 | 120 | ``` 121 | 122 | 123 | Agora, crie o arquivo PHP, hello.php: 124 | 125 | ```php 126 | show(); 134 | 135 | ?> 136 | ``` 137 | 138 | Agora basta executar em seu navegador, o script hello.php, e verificar que ele irá exibir o conteúdo lido de hello.html. 139 | 140 | Se algo deu errado, consulte a seção sobre as Mensagens de Erro. 141 | 142 | 143 | ## Variáveis 144 | 145 | Vamos agora a um conceito importante: variáveis de template. Como você pode imaginar, vamos querer alterar várias partes do arquivo HTML. Como fazer isso? Simples: no lado do HTML, você cria as chamadas variáveis de template. Veja o exemplo abaixo: 146 | 147 | ```html 148 | 149 | 150 | 151 | Olá {FULANO}, com templates PHP! 152 | 153 | 154 | 155 | ``` 156 | 157 | 158 | Repare na variável `FULANO`, entre chaves. Ela vai ter seu valor atribuído no código PHP. 159 | 160 | Variáveis só podem contêr em seu nome: letras, números e underscore (`_`). O uso de maiúsculas é apenas uma convenção, pra facilitar a identificação quando olhamos o código HTML. Mas, obrigatoriamente tem que estar entre chaves, sem nenhum espaço em branco. 161 | 162 | Então, como ficaria o código PHP que atribui valor a ela? Vamos a ele: 163 | 164 | ```php 165 | FULANO = "Rael"; 172 | $tpl->show(); 173 | 174 | ?> 175 | ``` 176 | 177 | Execute então novamente o script, e você verá que o código final gerado no navegador será: 178 | 179 | ```html 180 | 181 | 182 | 183 | Olá Rael, com templates PHP! 184 | 185 | 186 | 187 | ``` 188 | 189 | Variáveis de template que não tiverem um valor atribuído, serão limpas do código final gerado. 190 | 191 | Outra coisa sobre variáveis: você pode repetir as variáveis de template (ou seja, usar a mesma variável em vários lugares). Mas, óbvio, todas mostrarão o mesmo valor. 192 | 193 | Para ler o valor de uma variável, acesse do mesmo modo: 194 | 195 | ```php 196 | FULANO = "Rael"; 205 | 206 | // Imprimindo o valor da variável 207 | die("Valor de FULANO: ".$tpl->FULANO); 208 | 209 | $tpl->show(); 210 | 211 | ?> 212 | ``` 213 | 214 | Repare que usando as variáveis de template, você pode continuar editando o arquivo HTML em seu editor favorito: as variáveis de template serão reconhecidas como um texto qualquer, e o arquivo HTML não ficará poluído de código PHP. O contrário também é verdade: seu arquivo PHP ficará limpo de código HTML. 215 | 216 | 217 | ## Checando se Variáveis Existem 218 | 219 | Caso você queira atribuir valor pra uma variável de template, mas não tem certeza se a variável existe, você pode usar o método exists() para fazer essa checagem. 220 | 221 | Como é de se esperar, ele retorna `true` caso a variável exista. Caso não, retorna false: 222 | 223 | ```php 224 | exists("FULANO")) $tpl->FULANO = "Rael"; 233 | 234 | $tpl->show(); 235 | 236 | ?> 237 | ``` 238 | 239 | ## Variáveis com Modificadores 240 | 241 | É possível, dentro do arquivo HTML, chamarmos algumas funções do PHP, desde que elas atendam as duas condições: 242 | 243 | - A função tem que sempre retornar um valor; 244 | - A função deve ter sempre como primeiro parâmetro uma string; 245 | 246 | Vamos supor o seguinte arquivo PHP, que atribui as variáveis de template `NOME` e `VALOR`: 247 | 248 | ```php 249 | NOME = 'Fulano Ciclano da Silva'; 257 | 258 | $tpl->VALOR = 100; 259 | 260 | $tpl->show(); 261 | 262 | ?> 263 | ``` 264 | 265 | E o seguinte HTML, já fazendo uso dos modificadores: 266 | 267 | ```html 268 | 269 | 270 | 271 | Exemplo - Modificadores 272 | 273 | 274 | 275 | 276 | 277 |
Nome: {NOME|replace:Fulano:Rael}
278 |
Valor: R$ {VALOR|str_pad:5:0:0},00
279 | 280 | 281 | 282 | ``` 283 | 284 | Explicando: a linha `{NOME|replace:Fulano:Rael}` equivale a chamar no PHP `replace('Fulano Ciclano da Silva', 'Fulano', 'Rael')`. 285 | 286 | E essa função `replace`? É uma função declarada dentro da classe Template, que basicamente faz a mesma coisa que a função do PHP [`str_replace`](http://php.net/manual/pt_BR/function.str-replace.php) (substitui um texto por outro). A diferença é que ela recebe uma string como primeiro parâmetro. Lembre que essa é uma das condições para uma função poder ser usada dentro do HTML. 287 | 288 | Já no segundo exemplo, usamos a função interna do PHP, [`str_pad`](http://php.net/manual/pt_BR/function.str-pad.php) (já que ela já recebe como primeiro parâmetro uma string, não precisamos criar uma nova função). Neste caso, estamos usando ela para adicionar zeros à esquerda do valor, para que o valor sempre tenha 5 dígitos (e quando não tiver, que esses dígitos sejam completados com zero). Veja a [documentação desta função](http://php.net/manual/pt_BR/function.str-pad.php) para maiores esclarecimentos. 289 | 290 | ## Blocos 291 | 292 | Esse é o segundo e último conceito que você precisa saber sobre essa biblioteca de templates: os blocos. 293 | 294 | Imagine que você gostaria de listar o total de produtos cadastrados em um banco de dados. Se não houver nenhum produto, você irá exibir uma aviso de que nenhum produto foi encontrado. 295 | 296 | Vamos utilizar então, dois blocos: um que mostra a quantidade total; e outro que avisa que não existem produtos cadastrados, caso realmente o banco esteja vazio. O código HTML para isso é: 297 | 298 | ```html 299 | 300 | 301 | 302 |

Quantidade de produtos cadastrados no sistema:

303 | 304 | 305 |
Existem {QUANTIDADE} produtos cadastrados.
306 | 307 | 308 | 309 |
Não existe nenhum produto cadastrado.
310 | 311 | 312 | 313 | 314 | ``` 315 | 316 | Repare que o início e final do bloco são identificados por um comentário HTML, com a palavra `BEGIN` (para identificar início) ou `END` (para identificar fim) e o nome do bloco em seguida. 317 | 318 | As palavras BEGIN e END sempre devem ser maiúsculas. O nome do bloco deve conter somente letras, números ou underscore. 319 | 320 | E então, no lado PHP, vamos checar se os produtos existem. Caso sim, mostraremos o bloco `BLOCK_QUANTIDADE`. Caso não, vamos exibir o bloco `BLOCK_VAZIO`. 321 | 322 | ```php 323 | 0){ 335 | $tpl->QUANTIDADE = $quantidade; 336 | $tpl->block("BLOCK_QUANTIDADE"); 337 | } 338 | 339 | // Caso não exista nenhum produto, exibimos a mensagem de vazio 340 | else { 341 | $tpl->block("BLOCK_VAZIO"); 342 | } 343 | 344 | $tpl->show(); 345 | 346 | ?> 347 | ``` 348 | 349 | Como você pode reparar, blocos podem contêr variáveis de template. E blocos só são exibidos se no código PHP pedirmos isso, através do método `block()`. Caso contrário, o bloco não é exibido no conteúdo final gerado. 350 | 351 | Outro detalhe importante: ao contrário das variáveis de template, cada bloco deve ser único, ou seja, não podemos usar o mesmo nome para vários blocos. 352 | 353 | Repare que mesmo com o uso de blocos, podemos continuar editando o arquivo HTML em qualquer editor HTML: os comentários que indicam início e fim de bloco não irão interferir em nada. 354 | 355 | Agora vamos a outro exemplo usando blocos: imagine que você precisa mostrar os dados dos produtos que existem no seu cadastro. Vamos então, usando blocos, montar o HTML para isso: 356 | 357 | ```html 358 | 359 | 360 | 361 |

Produtos cadastrados no sistema:

362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 |
NomeQuantidade
{NOME}{QUANTIDADE}
375 | 376 | 377 | 378 | ``` 379 | 380 | Repare que temos apenas uma linha de tabela HTML para os dados dos produtos, dentro de um bloco. Vamos então atribuir valor a estas variáveis, e ir duplicando o conteúdo do bloco conforme listamos os produtos: 381 | 382 | ```php 383 | "Sabão em Pó", "quantidade" => 15), 393 | array("nome" => "Escova de Dente", "quantidade" => 53), 394 | array("nome" => "Creme Dental", "quantidade" => 37) 395 | ); 396 | 397 | // Listando os produtos 398 | foreach($produtos as $p){ 399 | $tpl->NOME = $p["nome"]; 400 | $tpl->QUANTIDADE = $p["quantidade"]; 401 | $tpl->block("BLOCK_PRODUTO"); 402 | } 403 | 404 | $tpl->show(); 405 | 406 | ?> 407 | ``` 408 | 409 | O comportamento padrão do método `block()` é manter o conteúdo anterior do bloco, somado (ou melhor, concatenado) ao novo conteúdo que acabamos de atribuir. 410 | 411 | No exemplo acima, os dados dos produtos vieram do array `$produtos`. Caso estes dados estivessem armazenados em um banco de dados, então bastaríamos fazer como no exemplo abaixo: 412 | 413 | ```php 414 | NOME = $linha["nome"]; 429 | $tpl->QUANTIDADE = $linha["quantidade"]; 430 | $tpl->block("BLOCK_PRODUTO"); 431 | } 432 | 433 | $tpl->show(); 434 | 435 | ?> 436 | ``` 437 | 438 | 439 | ## Blocos aninhados 440 | 441 | Vamos agora então juntar os 2 exemplos de uso de blocos que vimos: queremos mostrar os dados dos produtos em um bloco, mas caso não existam produtos cadastrados, exibiremos uma mensagem com um aviso. Vamos fazer isso agora usando blocos aninhados, ou seja, blocos dentro de outros blocos: 442 | 443 | ```html 444 | 445 | 446 | 447 |

Produtos cadastrados no sistema:

448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 |
NomeQuantidade
{NOME} {QUANTIDADE}
462 | 463 | 464 | 465 |
Nenhum registro encontrado.
466 | 467 | 468 | 469 | 470 | ``` 471 | 472 | E então, caso existam produtos, nós exibimos o bloco `PRODUTOS`. Caso contrário, exibimos o bloco `VAZIO`: 473 | 474 | ```php 475 | "Sabão em Pó", "quantidade" => 15), 485 | array("nome" => "Escova de Dente", "quantidade" => 53), 486 | array("nome" => "Creme Dental", "quantidade" => 37) 487 | ); 488 | 489 | // Listando os produtos 490 | foreach($produtos as $p){ 491 | $tpl->NOME = $p["nome"]; 492 | $tpl->QUANTIDADE = $p["quantidade"]; 493 | $tpl->block("BLOCK_DADOS"); 494 | } 495 | 496 | // Se existem produtos, então mostramos o bloco com os dados de todos 497 | if(isset($produtos) && is_array($produtos) && sizeof($produtos) > 0){ 498 | $tpl->block("BLOCK_PRODUTOS"); 499 | } 500 | // Senão, mostramos o bloco com o aviso de nenhum cadastrado 501 | else { 502 | $tpl->block("BLOCK_VAZIO"); 503 | } 504 | 505 | $tpl->show(); 506 | 507 | ?> 508 | ``` 509 | 510 | ## Blocos Automáticos por Padrão 511 | 512 | Um detalhe muito importante desta nova versão da biblioteca (versão 2.0 em diante) em relação a sua antecessora: agora, se um bloco aninhado é exibido, todos os blocos pais serão automaticamente exibidos. 513 | 514 | Ou seja, pegando o exemplo anterior, podemos simplificar o código PHP anterior para ficar assim: 515 | 516 | ```php 517 | "Sabão em Pó", "quantidade" => 15), 527 | array("nome" => "Escova de Dente", "quantidade" => 53), 528 | array("nome" => "Creme Dental", "quantidade" => 37) 529 | ); 530 | 531 | // Listando os produtos 532 | foreach($produtos as $p){ 533 | $tpl->NOME = $p["nome"]; 534 | $tpl->QUANTIDADE = $p["quantidade"]; 535 | $tpl->block("BLOCK_DADOS"); 536 | } 537 | 538 | // Se não existem produtos, mostramos o bloco com o aviso de nenhum cadastrado 539 | if(!isset($produtos) || !is_array($produtos) || !sizeof($produtos)){ 540 | $tpl->block("BLOCK_PRODUTOS"); 541 | } 542 | 543 | $tpl->show(); 544 | 545 | ?> 546 | ``` 547 | 548 | Ou seja, se existem produtos, e por consequência o `BLOCK_DADOS` foi exibido, o `BLOCK_PRODUTOS` automaticamente será. 549 | 550 | Mais continue lendo, vamos conseguir fazer mais coisas automaticamente, e com menos código, usando os blocos `FINALLY`. 551 | 552 | 553 | ## Blocos FINALLY 554 | 555 | No exemplo anterior, usamos o `BLOCK_PRODUTOS` para exibir os produtos, e caso não existam produtos, usamos o `BLOCK_VAZIO` para exibir uma mensagem amigável de que não existem produtos cadastrados. 556 | 557 | Podemos fazer isso de forma mais automática: usandos os blocos `FINALLY`. 558 | 559 | Veja como ficaria o arquivo HTML neste caso: 560 | 561 | ```html 562 | 563 | 564 | 565 |

Produtos cadastrados no sistema:

566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 |
NomeQuantidade
{NOME} {QUANTIDADE}
580 | 581 | 582 |
Nenhum registro encontrado.
583 | 584 | 585 | 586 | 587 | 588 | ``` 589 | 590 | E o arquivo PHP? Bem, ele vai ficar mais simples ainda: 591 | 592 | ```php 593 | "Sabão em Pó", "quantidade" => 15), 603 | array("nome" => "Escova de Dente", "quantidade" => 53), 604 | array("nome" => "Creme Dental", "quantidade" => 37) 605 | ); 606 | 607 | // Listando os produtos 608 | foreach($produtos as $p){ 609 | $tpl->NOME = $p["nome"]; 610 | $tpl->QUANTIDADE = $p["quantidade"]; 611 | $tpl->block("BLOCK_DADOS"); 612 | } 613 | 614 | $tpl->show(); 615 | 616 | ?> 617 | ``` 618 | 619 | Primeiro detalhe importante: o bloco `FINALLY` nunca precisa ser invocado no arquivo PHP. Caso ele exista no HTML, ele sempre será chamado se o bloco relacionado não for exibido. 620 | 621 | Ou seja, se não houverem produtos, o bloco `FINALLY` exibirá automaticamente o aviso de que não exitem registros encontrados. Prático, né? 622 | 623 | E segundo detalhe: no arquivo PHP, o bloco `BLOCK_PRODUTOS` nem foi chamado. Mas como o bloco mais interno, `BLOCK_DADOS`, foi chamado, o bloco pai automaticamente será mostrado. 624 | 625 | 626 | ## Blocos com HTML Select 627 | 628 | Uma das dúvidas mais comuns é: como usar a classe Template com o elemento `select` do HTML? Ou melhor: como fazer um elemento `option` ficar selecionado, usando Template? 629 | 630 | Vamos então montar nossa página HTML com o elemento `select` e os devidos `options`, representando cidades de uma lista: 631 | 632 | ```html 633 | 634 | 635 | 636 | 643 | 644 | 645 | 646 | ``` 647 | 648 | Agora vamos ao respectivo arquivo PHP: 649 | 650 | ```php 651 | "Cidade 0", 1 => "Cidade 1", 2 => "Cidade 2"); 660 | 661 | // Valor selecionado 662 | $atual = 1; 663 | 664 | foreach($cidades as $value => $text){ 665 | 666 | $tpl->VALUE = $value; 667 | $tpl->TEXT = $text; 668 | 669 | // Vendo se a opção atual deve ter o atributo "selected" 670 | if($atual == $value) $tpl->SELECTED = "selected"; 671 | 672 | // Caso esta não seja a opção atual, limpamos o valor da variável SELECTED 673 | else $tpl->clear("SELECTED"); 674 | 675 | $tpl->block("BLOCK_OPTION"); 676 | 677 | } 678 | 679 | $tpl->show(); 680 | 681 | ?> 682 | ``` 683 | 684 | Como resultado, o navegador exibirá o seguinte código: 685 | 686 | ```html 687 | 688 | 689 | 690 | 697 | 698 | 699 | 700 | ``` 701 | 702 | Reparou que no arquivo PHP chamamos o método `clear`? Se não chamarmos este método (que limpa o valor de uma variável), todas as opções (`option`) ficariam com a propriedade `selected` (obviamente, efeito não desejado): 703 | 704 | ```html 705 | 706 | 707 | 708 | 715 | 716 | 717 | 718 | ``` 719 | 720 | 721 | ## Usando vários arquivos HTML 722 | 723 | Um uso bastante comum de templates é usarmos um arquivo HTML que contenha a estrutura básica do nosso site: cabeçalho, rodapé, menus, etc. E outro arquivo com o conteúdo da página que desejamos mostrar, ou seja, o "miolo". Dessa forma, não precisamos repetir em todos os arquivos HTML os elementos comuns (cabeçalho, rodapé, etc), e as páginas HTML que terão o conteúdo (o "miolo") ficarão mais limpas, menores e mais fáceis de serem mantidas. 724 | 725 | Como fazer isso com templates? Em primeiro lugar, vamos criar nosso arquivo "base" HTML, o arquivo base.html: 726 | 727 | ```html 728 | 729 | 730 | Título da Página 731 | 732 | 733 | 734 |
{FULANO}, seja bem vindo!
735 | 736 |
{CONTEUDO}
737 | 738 |
Deseja maiores informações? Clique aqui para saber
739 | 740 | 741 | 742 | ``` 743 | 744 | Agora, vamos criar o arquivo que contém o "miolo" de nossa página HTML, o arquivo miolo.html: 745 | 746 | ```html 747 |

Produtos cadastrados no sistema:

748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 |
NomeQuantidade
{NOME} {QUANTIDADE}
762 | 763 | 764 |
Nenhum registro encontrado.
765 | 766 | 767 | 768 | ``` 769 | 770 | 771 | No arquivo PHP então, usamos o método addFile(), onde informamos duas coisas: em qual variável do template o conteúdo do novo arquivo será jogado, e qual o caminho desse arquivo. Depois disso, basta usar as variáveis e blocos normalmente, independente de qual arquivo HTML eles estejam: 772 | 773 | ```php 774 | addFile("CONTEUDO", "miolo.html"); 783 | 784 | $tpl->FULANO = "Rael"; 785 | 786 | // Produtos cadastrados 787 | $produtos = array( 788 | array("nome" => "Sabão em Pó", "quantidade" => 15), 789 | array("nome" => "Escova de Dente", "quantidade" => 53), 790 | array("nome" => "Creme Dental", "quantidade" => 37) 791 | ); 792 | 793 | // Listando os produtos 794 | foreach($produtos as $p){ 795 | $tpl->NOME = $p["nome"]; 796 | $tpl->QUANTIDADE = $p["quantidade"]; 797 | $tpl->block("BLOCK_DADOS"); 798 | } 799 | 800 | $tpl->show(); 801 | 802 | ?> 803 | ``` 804 | 805 | 806 | ## Guardando o conteúdo do template 807 | 808 | Até agora exibimos o conteúdo gerado pelo template na tela, através do método `show()`. Mas, e quisermos fazer outro uso para esse conteúdo, como salvá-lo em arquivo ou outra coisa do tipo? Basta usarmos o método `parse()`, que gera o conteúdo final e o retorna: 809 | 810 | ```php 811 | addFile("CONTEUDO", "miolo.html"); 818 | 819 | // Variáveis, blocos, etc 820 | $tpl->FULANO = "Rael"; 821 | 822 | // Pega o conteúdo final do template 823 | $conteudo = $tpl->parse(); 824 | // Salva em um arquivo 825 | file_put_contents("arquivo.txt", $conteudo); 826 | 827 | ?> 828 | ``` 829 | 830 | 831 | ## Usando Objetos 832 | 833 | A classe Template suporta a atribuição de objetos para as variáveis de template desde a versão `1.5` (verifique no código fonte da classe sua versão). 834 | 835 | Isso ajuda bastante caso estejamos usando alguma biblioteca ORM, como [Doctrine2](http://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html), o [ORM do Kohana](http://kohanaframework.org/3.3/guide/orm/using) ou o [Eloquent do Laravel](http://laravel.com/docs/eloquent). 836 | 837 | Isso faz com que o código nos arquivos PHP fique bastante reduzido (claro, desde que você use objetos), e devido a isso, há uma melhora (quase imperceptível) em desempenho. 838 | 839 | Para que os exemplos fiquem mais claros, vamos trabalhar com uma suposta página que exibe detalhes de um produto. Os produtos possuem como atributos: `id` e `name`. 840 | 841 | A classe Template funcionará tanto com classes que usam encapsulamento (`get` e `set` do atributo), quanto para classes que chamam os atributos diretamente (geralmente através dos métodos mágicos do PHP). 842 | 843 | Primeiro, vamos a um exemplo de classe Produtos retirado diretamente dos [exemplos da Doctrine2](http://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html#starting-with-the-product): 844 | 845 | ```php 846 | id; 863 | } 864 | 865 | public function getName() 866 | { 867 | return $this->name; 868 | } 869 | 870 | public function setName($name) 871 | { 872 | $this->name = $name; 873 | } 874 | } 875 | 876 | ?> 877 | ``` 878 | 879 | Vamos então modificar o arquivo PHP para carregar um produto, e usar o suporte a objetos de Template: 880 | 881 | ```php 882 | find('Product', 1); 894 | 895 | # Atribuindo a variável template 896 | $tpl->P = $produto; 897 | 898 | $tpl->show(); 899 | 900 | ?> 901 | ``` 902 | 903 | O arquivo HTML também deve ser modificado pra exibir as propriedades de Produto: 904 | 905 | ```html 906 | 907 | Id: {P->ID}
908 | Nome: {P->NAME}
909 | ``` 910 | 911 | A instrução `P->NAME` chamará o método `$p->getName()`, caso ele exista. Se não existir esse método na classe, um erro será disparado. 912 | 913 | Isso vale para qualquer atributo que tentarmos chamar no HTML: será traduzido para `$meuObjeto->getAtributo()`. 914 | Se o nome do método PHP for composto, como por exemplo `$p->getExpirationDate()`, basta usar underscore `_` no HTML como separador dos nomes: no caso do exemplo, ficaria `P->EXPIRATION_DATE`. 915 | 916 | Se a biblioteca ORM não fizer uso de `get` e `set`, como no Kohana ou Laravel, também funciona: a classe Template vai ver se a classe Produto tem o atributo `$meuObjeto->atributo`, e ainda, se a classe tiver o método mágico `__get`, a classe Template também tentará chamá-lo. 917 | 918 | ## Comentários 919 | 920 | A exemplo das linguagens de programação, a classe Template suporta comentários no HTML. Comentários são úteis para várias coisas, entre elas, identificar o autor do HTML, versão, incluir licenças, etc. 921 | 922 | Diferentemente dos comentários HTML, que são exibidos no código fonte da página, os comentários da classe Template são extraídos do HTML final. Na verdade os comentários de Template são extraídos antes mesmo de qualquer processamento, e tudo que estiver entre os comentários será ignorado. 923 | 924 | Os comentários ficam entre as tags ``. Repare que usamos 3 tracinhos, ao invés de 2 (que identificam comentários HTML). A razão é simples: permitir diferenciarmos entre um e outro, e permitir que os editores continuem reconhecendo o conteúdo entre `` como comentários. 925 | 926 | Veja o exemplo abaixo: 927 | 928 | ```html 929 | 935 | 936 |

Produtos cadastrados no sistema:

937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 |
NomeQuantidade
{NOME}{QUANTIDADE}
951 | 952 | 953 |
Nenhum registro encontrado.
954 | 955 | 956 | ``` 957 | 958 | ## Criando XML, CSV e outros 959 | 960 | O uso mais comum de templates é com arquivos HTML. Mas como essa biblioteca é direcionada ao uso de qualquer tipo de arquivo de texto, podemos usá-la com vários outros formatos de arquivo, como XMLs e arquivos CSVs. 961 | 962 | Como fazer isso? Mais simples impossível: não muda nada, basta apenas ao invés de indicar um arquivo HTML para o Template, indicar qualquer outro arquivo de texto. E usar variáveis e blocos nele conforme já vimos, exibindo o conteúdo na tela, ou salvando em arquivos. 963 | 964 | 965 | ## Criando arquivos do Office 966 | 967 | Se você precisa elaborar um relatório que deve ser exibido em formato do Word (`.doc`) ou do Excel (`.xls`), também podemos usar a classe Template para isso. 968 | 969 | Em primeiro lugar, crie normalmente no Office seu relatório. Após terminar, escolha a opção "Salvar como", e selecione o formato HTML. Feito isso, abra este arquivo HTML em seu editor PHP (não se assuste, é bastante poluído e cheio de tags estranhas) e use-o conforme visto até agora: crie variáveis, declare blocos, nada de diferente. 970 | Se você for salvar o conteúdo em um arquivo, coloque neste arquivo a extensão `.doc` (ou `.xls` no caso de uma planilha). O Office abrirá normalmente este arquivo, convertendo-o automaticamente de HTML para o formato desejado na primeira vez em que for aberto. 971 | 972 | Se você for exibir o conteúdo no navegador ao invés de salvá-lo num arquivo, você precisa modificar o header para avisar o navegador que se trata de um documento do Office, forçando o navegador a interpretá-lo como tal (o Firefox irá fazer o download do arquivo, o IE irá abrir o Microsoft Office como um plugin e exibir o arquivo dentro do navegador mesmo). 973 | 974 | Faça isso com a instrução `header()` do PHP: 975 | 976 | ```php 977 | FULANO = "Rael"; 993 | 994 | $tpl->show(); 995 | 996 | ?> 997 | ``` 998 | 999 | 1000 | ## Gerenciando erros 1001 | 1002 | Quando um erro acontece, você deve ter reparado que a mensagem de erro gerada pela classe Template é um pouco diferente do usual em PHP: ao invés de ser apenas um `die()` com a mensagem de erro, é gerada uma exceção (`Exception`). 1003 | 1004 | Por que isso? 1005 | 1006 | Com as exceptions, temos duas vantagens: a primeira é ver todo o stack do erro, ou seja, ver desde o lugar em que foi originado o erro, passando por todos os arquivos em que ele apareceu. Isso facilita muito o trabalho de debug e correção. Para ver o código de erro e a stack corretamente, peça para o navegador exibir o código-fonte da página, pois somente neste modo as quebras de linhas são visualizadas corretamente. 1007 | 1008 | A segunda vantagem é poder gerenciar o erro, se desejarmos, e fazermos com que a execução de nosso script não seja interrompida, através do uso de `try/catch`: 1009 | 1010 | ```php 1011 | FOO = "bar"; 1021 | // Capturando erro e evitando que o script seja interrompido 1022 | } catch (Exception $e){ 1023 | echo "FOO não existe!"; 1024 | } 1025 | 1026 | $tpl->show(); 1027 | 1028 | ?> 1029 | ``` 1030 | 1031 | 1032 | ## Variáveis Dinâmicas 1033 | 1034 | Imagine um caso onde você tem várias variáveis de template em seu arquivo HTML, e tem um valor que precisa atribuir a uma delas. Mas o problema é: a variável que precisa receber o valor é definida apenas durante a execução do script. Ou seja, é uma variável dinâmica, ou como alguns chamam, uma "variável variável". Nosso arquivo HTML então seria: 1035 | 1036 | ```html 1037 | 1038 | 1039 | 1040 | Olá {NOME_FULANO}! 1041 | 1042 | 1043 | 1044 | ``` 1045 | 1046 | Repare que no arquivo HTML não há nada de diferente. No arquivo PHP então, basta usar chaves: 1047 | 1048 | ```php 1049 | {"NOME_".strtoupper($varname)} = "Rael"; 1061 | 1062 | $tpl->show(); 1063 | 1064 | ?> 1065 | ``` 1066 | 1067 | 1068 | ## Escapando Variáveis 1069 | 1070 | Vamos supor que por algum motivo você precise manter uma variável de template no resultado final de seu HTML. Como por exemplo: você está escrevendo um sistema que gera os templates automaticamente pra você. 1071 | 1072 | Para isso, vamos supor que você tenha o HTML abaixo: 1073 | 1074 | ```html 1075 | 1076 | 1077 | 1078 | {CONTEUDO} 1079 | 1080 | 1081 | 1082 | ``` 1083 | 1084 | E você precisa que `{CONTEUDO}` não seja substituído (ou removido), mas que permaneça no HTML final. 1085 | 1086 | Para isso, faça o *escape* incluindo `{_}` dentro da variável: 1087 | 1088 | ```html 1089 | 1090 | 1091 | 1092 | {{_}CONTEUDO} 1093 | 1094 | 1095 | 1096 | ``` 1097 | 1098 | E pronto: no HTML final `{CONTEUDO}` ainda estará presente. 1099 | 1100 | ## Mensagens de Erro 1101 | 1102 | Abaixo estão os significados para as mensagens de erro exibidas pela classe Template: 1103 | 1104 | * `Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}'`: provavelmente você está usando PHP 4 (veja os requisitos necessários para usar esta biblioteca). 1105 | 1106 | * `addFile: var não existe`: você está usando o método addFile() para adicionar um arquivo HTML (ou equivalente), mas a variável de template na qual você quer jogar o conteúdo, não existe. 1107 | 1108 | * `var não existe`: você está tentando atribuir valor a uma variável que não existe. Certifique-se de que o nome da variável de template está correto, e que você está utilizando como nome desta variável somente letras, números e underscore, entre chaves. 1109 | 1110 | * `arquivo não existe`: você está informando o caminho para um arquivo HTML (ou equivalente) que não existe, ou cuja permissão de leitura é negada. 1111 | 1112 | * `arquivo está vazio`: o arquivo HTML (ou equivalente) que você está passando como parâmetro está vazio. Se está vazio, ou você está informando um arquivo errado, ou esqueceu de colocar conteúdo nele. 1113 | 1114 | * `bloco duplicado: `: o nome que você está tentando atribuir ao bloco já foi dado para outro bloco. Lembre-se que o nome do blocos deve ser único. Se você estiver usando mais de um arquivo HTML (ou equivalente), o bloco com o mesmo nome que o seu pode estar em um dos outros arquivo. 1115 | 1116 | * `bloco está mal formado`: o bloco que você declarou está com defeitos. Talvez você tenha usado a tag `BEGIN BLOCK` com um nome, e tenha terminado (a tag `END BLOCK`) com outro. Ou então, esqueceu da tag `END BLOCK`. Ou tenha colocado a tag `FINALLY BLOCK` em local errado. 1117 | 1118 | * `bloco não existe`: você está informando ao método `block()` o nome de um bloco que não existe. Certifique-se de que o nome do bloco está correto, e que você está utilizando como nome deste bloco somente letras, números e underscore. 1119 | 1120 | * `não existe método na classe para acessar ->`: não existe método para acessar a propriedade que você está chamando. Se você chamar no HTML por `OBJETO->NOME`, a classe deste objeto precisa ter um método chamado getNome() ou isNome(). Veja maiores detalhes na seção "Usando Objetos". 1121 | 1122 | 1123 | ## Precisão e Desempenho 1124 | 1125 | Uma dúvida comum ao uso de templates é: o quanto isso afeta o desempenho? A resposta é: menos do que você imagina. Deixe-me explicar o motivo. 1126 | 1127 | Esta biblioteca é muito mais rápida que as bibliotecas de template antigas, como a finada PHPLib, e outras similares. O motivo é que o uso de expressões regulares dentro dela é evitado, não sendo usado para fazer todo o funcionamento, como as bibliotecas antigas faziam. 1128 | 1129 | Ainda assim, esta biblioteca não possui um mecanismo de cache, como por exemplo, o template Smarty possui. Por duas razões. A primeira é a simplicidade de uso: não é preciso criar nem configurar diretórios, nem permissões Unix, etc. A segunda é que o desempenho é bom o suficiente para manter esta simplicidade. De qualquer forma, sinta-se à vontade para criar um mecanismo de cache. 1130 | 1131 | Eu uso esta biblioteca durante anos, e fui aperfeiçoando seu desempenho. Ela já foi usada em sites de grande tráfego, e nunca foi o gargalo. Se você usa esta biblioteca e fizer uma medição de desempenho de seu sistema, verá que em 98% dos casos, o gargalo é o banco de dados, e não o uso do processador. Sempre são consultas mal construídas, ou consultas feitas dentro de laços, este tipo de coisa. 1132 | 1133 | Um efeito colateral do bom desempenho desta biblioteca: se você pedir para seu navegador exibir o código fonte de uma página gerada pela classe Template, irá ver que o código final não remove algumas tabulações (tab ou \t) que existiam no começo de cada bloco do template, dando a aparência de que o código final está um pouco mais bagunçado do que deveria. A razão disto é que se essas tabulações fossem removidas por padrão, esta remoção traria uma queda na performance da classe Template. 1134 | 1135 | Como uma tabulação no código fonte não traz efeito algum para o conteúdo HTML final, o comportamento padrão da classe Template é ignorar estas tabulações de início de bloco, deixando elas no código final. O único caso em que isso pode ser um problema é quando você precisa de uma reprodução fiel dos seus arquivos HTML, como no uso das tags `
` e ``. Já prevendo isso, existe um segundo parâmetro (opcional) usado na declaração do objeto Template: o parâmetro $accurate. Se você usar ele com o valor true, então seu código final HTML será uma reprodução fiel dos arquivos HTML usados no Template (com a devida penalidade em performance):
1136 | 
1137 | ```php
1138 | show();
1149 | 
1150 | ?>
1151 | ```
1152 | 
1153 | ## Conclusão
1154 | 
1155 | O uso de mecanismos de Template é um grande avanço no desenvolvimento de aplicações web, pois nos permite manter a estrutura visual de nosso aplicativo separado da programação PHP.
1156 | 
1157 | Eu tentei incluir neste tutorial todos os tópicos que cobrem o uso de templates. Se você tiver problemas, procure primeiro em todos os tópicos aqui. Lembre-se que este trabalho é voluntário, e que eu gastei muito tempo escrevendo este tutorial, além do tempo gasto nesta biblioteca. Portanto, antes de me enviar um email com algum problema, tente resolvê-lo sozinho: grande parte do aprendizado está nisso. Se você não conseguir, vá em frente, e fale comigo.
1158 | 
1159 | Em caso de defeitos, sugestões ou melhorias, crie um [issue no GitHub](https://github.com/raelgc/template/issues/).
1160 | 
1161 | 
1162 | 
1163 | ## Licença
1164 | 
1165 | A licença desta biblioteca é regida pela licença LGPL. Ou seja, você pode utilizá-la, como biblioteca, mesmo em projetos comerciais.
1166 | 
1167 | Lembre-se apenas de ser uma pessoa legal e enviar de volta eventuais modificações, correções ou melhorias.
1168 | 


--------------------------------------------------------------------------------