Česky
version 3.0.0

  PClib - PHP component library

Quickstart

Core of the library consists from these classes:
ClassDescription
Tplbasic class which implements HTML-template.
FormCreating of the form, load and save form to the database, validation, sending by mail etc.
GridDatabase grid with sorting and pagging, filtering support, summarization rows, formatting of the fields etc.
AuthAuthorization and user account management with roles and hiearchical rights.
DbDatabase layer.
TranslatorMultilanguage support (translator service).
AppProvide access to application services e.g. configuration, logger, running application actions etc.

0.0 Class pclib\Tpl Showing template
$t 
= new PCTpl('tpl/mytemplate.tpl');
$t->values['A'] = 'Insert text from php to the template.';
$t->values['B'] = 123456.789;
$t->values['C'] = date("Y-m-d H:i:s");
$t->out();
 
At first we create object $t from template file "mytemplate.tpl". Next, we put few values into template and finally show template with function $t->out(). Values inserted into template can be transformed/formatted according instructions in section elements of template file (This section is loaded into array $t->elements in class constructor).

Hint: It is common that we need place a template into another one. (Most websites has fixed header and footer (a layout), and only content in the middle is changing) Function $t->html() returns content of the template (i.e. resulting html). So for placing $t into covering template just do: $website->values['CONTENT'] = $t->html(). Or use method $app->setLayout().

0.1 Class pclib\Grid Showing datagrid
$products 
= new PCGrid('tpl/mygrid.tpl');
$products->setQuery('select * from PRODUCTS');
$products->out();
 
These three lines will show content of database table PRODUCTS as datagrid similar to this example.
In case that you are interested how grid template looks like, click on "source" in the link above - it contains complete source code including template file. With simple changes of html and css you can get for example this look.
To enable sorting, add keyword "sort" at column definition in template file. Changing format of the pager is easy too. Another posibilites includes date formatting, string clipping, using lookup tables and so on.

0.2 Class pclib\Form Showing Form
$productForm 
= new PCForm('tpl/productform.tpl');
$productForm->values $db->select('PRODUCTS''ID=100');
$productForm->out();
 
As you can see, it is as simple as datagrid. Result will look roughly like in here. On the second line we fill associative array values, which contains all data filled in the fields of the form. If we omit this step, form will be shown empty. We are using function of class db here, which returns row from table PRODUCTS as associative array.
Class Form integrates all fuctions for working with forms, including form validation, storing in database or showing error messages if form was not filled properly. 0.3 Class Form Storing form
if ($productForm->submitted) {
  
$ok $productForm->validate();
  if (
$ok$productForm->insert('PRODUCTS');
  else 
$productForm->out();
}
 
The above code says: When form was submitted, do validation (validation rules for the form fields are specified in template). If we pass, insert filled values into table PRODUCTS. If not, show form again with error messages.

Note: Data filled by the user are stored in array $productForm->values. If form is not valid, function validate() fill array $productForm->invalid with error messages. These messages can be shown in template.

0.4 Class pclib\Db Read/write row from database table.
$db 
= new PCDb("pdo_mysql://user:password@mysql.host.cz/databasename");

$product $db->select('PRODUCTS''ID=100');
$product['buyPrice'] *= 1.2;
$db->update('PRODUCTS'$product'ID=100');

print 
paramstr("Product {productName} has new price {buyPrice}."$product);
 
PClib Db uses plain associative arrays as container storing content of database table row/rows.
These arrays can be loaded into form very easy, read back from form filled by user, loaded into grid etc. Class Db supports working with these arrays among other things. In our example we read row of the table into array $product, raise product price by 20 percent and store it back into database.

Note: Function paramstr() put values from associative array $product into text string. Keys are in curly brackets - just like in template.

Hint: It can be useful, for debugging purposes, check how resulting SQL sent to the database server looks like. To do this, enable debugbar: $app->debugMode = true;. There is also variable $db->lastQuery containing last executed query sql code.

0.5 Multilanguage texts.
$translator 
= new pclib\Translator();
$translator->language 'en';
print 
$translator->translate('Hello!');
 
Translator uses database table (or file) of text for translation. First, you need create table of source code text (stored as 'source' language) and then you can create translation for example using padmin tool.
Usually, we initialize translator indirectly by setting application language (and we can use shortcut $app->text instead of $translator->translate):
$app
->language 'en';
print 
$app->text('Hello!'); 
 
If we use 'source' language, translator will be filling table of source texts automatically meanwhile using of application. Translator is aware of template labels, error messages and pclib messages and add them into translation table. Other texts in templates you can mark for translation using 'translate' tag: <M>Some text</M>

Hint: Store price or dateformat into translation texts: $dateFormat = $app->text('%m/%d/%Y');
If you need switch whole file, you can store path into translation texts:
print file_get_contents($app->text('views/en/aboutus.html'));
You can use placeholders: $app->text('Welcome %s on our site', $name);

0.6 Class pclib\Auth Authorization and authentication.
$auth 
= new PCAuth();
$ok $auth->login('username''password');
if (!
$ok) { var_dump($auth->errors); die(); }

$user $auth->getUser();
print 
paramstr("User {FULLNAME} has been logged in."$user->toArray());

if (
$auth->hasRight('demo/products/delete')) print "User has permission delete products.";
$auth->logout();
 
A few words to above code: Function login() check user name and password and authorize user. If name or password is wrong, we write errors and quit. If user has been authorised, we read his account information into variable $user and write his name. At least we test if he has permission "demo/product/delete" and perform logout. For configuration of user accounts and permissions you can use authentization console aterm in padmin. It's even possible prepare batch file with roles and permissions for your project. Here is example: Auth policy

Note: Class auth uses database, so you must establish db conection before using it. Also setting of configuration variable 'pclib.auth.secret' is required. Look at the demo source.

Hint: You can assign permission with wildcard "*" to the user or role. Say "demo/products/*" grant all permissions beginning with "demo/products/": "demo/products/delete", "demo/products/edit" ...etc.
By assigning just "*" i.e. $authc->uGrant('username', '*'); (class AuthC) or username +right * in console, gives all rights to the user.

0.7 Class pclib\Logger - writting events into log.
$logger 
= new PCLogger();
$logger->log('NOTICE''user-login');
 
If we would put this two lines into previous example, event would be stored into database log.

Hint: You can use application log for logging: $app->log('NOTICE', 'user-login'); It will works when you setup application logger first: $app->logger = new Logger(); If you need disable logging, just comment this line - method app->log() do nothing then.
You can search, check or delete collected logs into application padmin.

0.8 Using class pclib\App. Creating object of class App is required since version 1.8.8. Class App contains service container $app->services, which is used by other pclib classes and you will need register any global service like this:
$app 
= new PCApp('application-name');
$app->db = new PCDb('pdo_mysql://...');
 
Now you can continue writing your code as in previous versions. Or you can delegate routing and dispatching of requests to the class App. In this case, file index.php can looks like this:
$app 
= new PCApp('application-name');
//Various initializations...
$app->run();
$app->out();
 
Method $app->run() will take request from browser, translate it to the App_Controller method call and try find controller's object in controllers/ directory. If class is found, instantiate it and call requested method with proper parameters. Method $app->out() will print result returned from your controller's method. In your controller, you can access object $app easy way using $this->app:
//file /controllers/CartController.php
class CartController extends PCController
{
  
//executed on url '?r=cart/show&id=123' or '/cart/show?id=123'
  
function showAction($id) {
    
$cart = new PCForm('/tpl/cart/form.tpl');
    
$cart->values $this->app->db->select('shop_cart'pri($id));
    return 
$cart->html();
  }
}
 
The $app object contains more entities owned by application in general, for example:
$app->config - pclib configuration - You can add your own application config file like this: $app->addConfig($filename);
$app->layout - app's layout, set this template with $app->setLayout('website.tpl');
$app->enviroment - test, production or develop enviroment
$app->debugMode - true/false - enable debugging mode

From the designer's point of view, class App realizes facade pattern: You have simplified access to many specialized classes from one entry point. For example by enabling $app->debugMode you are using class DebugBar, by setting $app->language you initialize service $app->translator of class Translator, methods such as $app->log() for logging (class Logger) or $app->text() for translation (class Translator) are noop if these services are not enabled.