English
version 2.9.5

  PClib - PHP component library

PClib handbook

Poznámka: Pouze v angličtině!

Table of content: •TOC

Ex.1: Basic template

Template is strip of HTML code (or another textual data) with so called template tags. These template tags can be replaced with some data, coming from php-code. Template is usually stored in some file (we use files with .tpl extension, but it is up to you). If you want modify layout of your application, you just modify HTML file without necessarity change php code.
With this approach you will avoid creating bugs in application functionality, make cleaner code, layout changes are easy and can be managed separately by HTML-designer, meanwhile programmer is doing only application logic.
Template engine brings you framework for reading, filling and printing templates.

Our first template will be very simple. Consider this HTML code:
1.1 Template file productdetail.tpl

<HTML>
<HEAD>
<TITLE>{PAGE_TITLE}</TITLE>
<LINK rel="stylesheet" href="website.css"></LINK>
</HEAD>
<BODY>
<H1>{NAME}</H1>
Product name: {NAME}<BR>
Category: {CATEGORY}<BR>
Description: {DESC}<BR>
Price: <B>{PRICE}</B> USD<BR>
Expiration date: {EXPDAT}<BR>
<A HREF="index.php?modul=cart&action=add&id={ID}">Add to shopping cart</A>
</BODY>
</HTML>
Variables in curly braces are template tags and will be filled from php. For tag name you can use the same characters like for any PHP-variable. In the tutorial, we use uppercase tag names in most cases.
We store this html code as file tpl/productdetail.tpl and create PHP script which:
1. Load template file
2. Assign values for template tags
3. Print template on the screen. 1.2 Product detail page
require 'pclib/pclib.php';                       //Include pclib framework

$page = new PCTpl('tpl/productdetail.tpl');        //STEP 1. Load template

$page->values['ID']     = 1;                     //STEP 2. Assign template tags
$page->values['PAGE_TITLE'] = 'Chocolate box';
$page->values['NAME']       = 'Chocolate box';
$page->values['CATEGORY']   = 'Confections';
$page->values['PRICE']  = 1200;
$page->values['EXPDAT'] = date('Y-m-d'time() + 30 DAY);
$page->values['DESC']   = 'Some description <I>here</I><br>...';

$page->out();                                    //STEP 3. Print template on the screen.
 


Working of this program is very straighforward: After loading template it goes through HTML code (it is done in method $tpl->out()) and when it found template tag, it looks into asociative array $tpl->values for item with same name. If it is found, it will replace template tag.
We fill $tpl->values array into step 2. You can work with it like with any other associative array.

Most common scenario is loading values from database table. Maybe you wouldn't print HTML-result on the screen immediatelly. In this case you use method $tpl->html() instead of $tpl->out(), which return HTML-result into variable, without printing on the screen.
1.3 Product detail page, loading from database
require 'pclib/pclib.php';                       //Include pclib framework

$db = new PCDb('pdo_mysql://root@localhost/test');     //Connect to database

$product_id = (int)$_GET['product_id'];          //Get product_id
$page = new PCTpl('tpl/productdetail.tpl');        //STEP 1. Load productdetail template

$product $db->select("select * from PRODUCTS where ID='$product_id'");  //STEP 2. Load product data from db-table

if (!$product) die("Product $product_id not found!"); //STEP 3. Here we can do some bussines logic
$product['NAME'] = strtoupper($product['NAME']);

$page->values $product;                       //STEP 4. Assign product data into template
$page->values['PAGE_TITLE'] = $product['NAME']; //Assign some additional template tag

$html $page->html();                             //Instead of calling $page->out() we can get HTML string
print $html;                                       //Print page
 

Note that we are using pclib db class here, but you can use PDO or even mysql_query() as you prefer.

In following example we use layout - the master template, which contains "frame" of our site, which is used for all pages of the site.
In layout can be logo, menu, footer etc.
Next we put content of our $page into layout. 1.4 More templates
require 'pclib/pclib.php'//Include pclib framework

$website = new PCTpl('tpl/website.tpl'); //layout is stored into website.tpl template

$page =  new PCTpl ($filename); //setup page template
$page->values $page_vars;

$website->values['CONTENT'] = $page->html(); //Put page into {CONTENT} variable
 


Ex.2: Template elements - definiton of element's attributes

We rarely print data on the screen as it was loaded from database. We want do some "transformations" before we print it. One of the most often transformation is formating. We may want use php-function number_format() for formating of price, or function strftime() for formating date etc. Look at following pseudocode:

data 
LOAD_FROM_DATABASE
TRANSFORM
(datatransformation)
PRINT(
data)
 
The data is array of values loaded from database, transformation is array which specify how data should be transformed (i.e. formated) and TRANSFORM is code which realise required transformation. In PClib, transformation can be specified using simple "language". Formating of fields PRICE and EXPDATE, mentioned above can be specified like this:
string PRICE format 
"0.,"
string EXPDATE date "d. m. Y"
 
The first line tell PClib to show PRICE field with separated thousands (like "1,200" ), second format EXPDATE to day.month.year format: 30. 12. 2007. Template engine parse this DDL code and create transformation array. PClib implements most useful TRANSFORM algorithmes. Not clear? See whole example. 2.1 Template file productdetail.tpl with formatting
<?elements
string PRICE format "0.,"
string EXPDATE date "d. m. Y"
string DESC size "40"
bind CATEGORY list "1,Meat,2,Vegetables,3,Fruits,4,Confections"
?>
<HTML>
<HEAD>
<TITLE>{PAGE_TITLE}</TITLE>
<LINK rel="stylesheet" href="website.css"></LINK>
</HEAD>
<BODY>
<H1>{NAME}</H1>
Product name: {NAME}<BR>
Category: {CATEGORY}<BR>
Description: {DESC}<BR>
Price: <B>{PRICE}</B> USD<BR>
Expiration date: {EXPDAT}<BR>
<A HREF="index.php?modul=cart&action=add&id={ID}">Add to shopping cart</A>
</BODY>
</HTML>
As you can see, it is the same HTML template like in 1.1 extended with elements definition at beginning. You can print this template with script 1.3 - no changes are necessary.
(We have two more fields here: DESC will show only first 40 characters of the string and CATEGORY works like lookup field - in database is stored just ID of the CATEGORY and in template is ID transformed to CATEGORY name)
Here is explanation of what is behind the scene.
2.2 Printing template with elements. Accessing elements array.
$page 
= new PCTpl('tpl/productdetail.tpl'); //Parse DDL block and load spec into $page->elements array
$page->elements['DESC']['size'] = 50;     //Now you can access elements array
$page->values $product;                 //Next we assign values
$page->out();              //Here data are formatted and placed into template
 


At first line $page->elements array is filled. You can modify this array before printing of template and change transformations/formatting rules from PHP. In our example, we are changing attribute size of field DESC from value 40 to 50. Try command var_dump($page->elements) here, to see structure of elements array.
In method $page->out() last two lines of our pseudocode TRANSFORM(data, transformation) and PRINT(data) are done. In more detail:

Value coming from $page->values is transformed using parameters in $page->elements array by proper handler which is invoked. (handler is a method of tpl class). If there is no handler or no parameters, value from values is just printed on the screen.
Syntax of data definition "language" is very simple. Every field is specified at one line and format of the line is:
type_of_field identifier attribute1 attribute2 attribute3 ...
Attribute can have parameter. If so, parameter must be enclosed by quotes, like this: attribute "parameter". If you need quotes into parameter, use double quotes: attr "onclick=""alert(this.value)""". If you write into template field types or attributes which are not supported by any handler, they will be ignored. In later examples you will see how create your own handler.

These details are not so important. The point is, that you can specify formating in template file and/or specify/modify it in php code. Of course, you can format field by your own code too. Now we use DDL mostly for formating specification. In example of the form class, you will see how create form elements like input or select using DDL.
Note that DDL doesn't do any action. There is no "if" or "while". We want avoid moving bussiness logic into template. Interpretation of DDL is job of our php class.

There is also possibility create template without HTML part, like this: 2.3 Template file productdetail.tpl. Default layout.
<?elements
string PRICE format "0.,"
string EXPDATE date "d. m. Y"
string DESC size "40"
bind CATEGORY list "1,Meat,2,Vegetables,3,Fruits,4,Confections"
?>
In this case template will be printed using default layout. You can use this for debugging or during development of aplication, if you don't want lose time with creating layout. Template with default layout is printed by method out_default(). If you have application with very unified look, you can override this method for creating your own default layout and use HTML template only in few necessary cases.

Ex.3: Template blocks

Sometimes, you need do operations (like hidding, moving, repeating) with whole large block of text, which is part of your template (including html and template tags). Basically, we don't want move this html at php code. You can use nested templates for this, but it is not very comfortable. Fortunately, PClib offers you template blocks. You can mark beginning and end of block in template, name them, and work with them from php.
3.1 Simple block demonstration. File productlist.tpl
<h1>{PAGE_TITLE}</h1>
{BLOCK items}
Product <b>{PRODUCT}</b> cost of {PRICE} USD.<BR>
<!-- BLOCK END -->
<BR>
{BLOCK ELSE}
There are no items.
{/BLOCK}
Go <a href="javascript:history.back();">back</a>
Now we have two blocks named items and noitems. Beginning and end of the blocks are specified using special html comments. You can have any number of blocks in template, they can be even nested with a few limitations. In following php code we will demonstrate how you can hide or show these blocks, and repeat block content for printing more products. 3.2 Printing of template with blocks.
$array_of_products 
= array(
  
'Tea''Bread''Butter''Eggs''Bacon''Honey'
 
);

$array_of_costs = array(3.50246103.30);
$no_of_products count($array_of_products);

$page = new PCTpl ('tpl/productlist.tpl');                        //STEP 2. Assign template variables
$page->values['PAGE_TITLE'] = "List of $no_of_products products.";
$page->values['PRODUCT'] = $array_of_products;
$page->values['PRICE'] = $array_of_costs;

$page->elements['items']['repeat'] = $no_of_products;           //STEP 3. Set BLOCKs

$page->out();                                           //...and print template.
 


By setting $page->elements['items']['noprint'] to 1 or 0 you can hide/show block items. You can hide/show not only block but also any template tag using same method.

Note: For convenience, pclib offers method tpl::enable(). So if you need show/hide "items" block or any element, you can use $page->enable('items'); or $page->disable('items'); to disable.

Because we want print line Product <b>{PRODUCT}</b> cost of {PRICE} USD.<BR> for each product from $array_of_products we set attribute $page->elements['items']['repeat'] to number of loops.

We have two tags into block items: {PRODUCT} and {PRICE}. Looking at php-source, you can see that we assign two arrays to this tags. What happens? Yes, it iterate through arrays and show one value from these arrays in each BLOCK loop. Using this technique, you can create html data-grids.
In next example, you will see how PClib grid object fills template from database for you.

Using grid NEXT»