Open Power Libs 2.0

Copyright © Invenzzia Group 2008-2009
Available under the terms of license: GNU Free Documentation License 1.2
Generated: 22.11.2009

Table of Contents

Table of Contents
1. Preface
2. Installation
Next »

1. Preface

Open Power Libs is a project that aims to create a set of advanced and well-designed PHP5/PHP6 libraries. It is not a standalone framework, because it does not contain some of the tools necessary to build the website from scratch. However, you may think about it as an additional library collection for your favorite framework. The reason why we decided to write such a script, is easy. There are lots of good frameworks, but not all of their components are good enough. Let's take a look at the example - template engines. Most of them ends at putting PHP structures into Yet Another Syntax, and no doubt the programmers consider them evil and the framework designers choose pure PHP as a template language. But PHP is rather a programming language and some common tasks require much of coding or using various advanced features to keep the code simple enough. As we do not create a complete framework, we could spend much more time on designing a better template engine, that allows to solve problems in the way PHP was not and never will be able to do.

Package contents

The status of the package contents:

  1. Open Power Libs core (OPL) - provides base classes and interfaces. Stable.
  2. Open Power Template (OPT) - a template engine. Stable.
  3. Open Power Classes (OPC) - a group of smaller supporting classes. Under development.
  4. Open Power Forms (OPF) - form processing. Planning.

Of course, the libraries do not work alone. OPF cannot work without OPT, because all the forms and controls are drawn using the template engine features. On the other hand, most of OPC classes are standalone projects, but as they provide implementations for various OPT and OPF interfaces, they can also cooperate.

Framework integration

OPL is not integrated by default with any particular framework. The basic integration is very simple - just load the core plus the libraries you need and start using them. However, this usually does not allow to use all of the framework features. The best results are achieved when OPL is plugged into the native framework subsystems. The library was designed to make this task as simple as possible, by analyzing the APIs of the most popular solutions.

The official framework ports are on the way, too. The first that is going to appear, is OPL Zend Framework Port.

Documentation contents

Each of the libraries has its own documentation. This documentation provides only the description of the core subsystems and conventions used in the project.

Table of Contents
2. Installation
1. Preface
« Previous
2.1. Standard installation
Next »

2. Installation

This chapter describes the installation issues. OPL is available in two versions:

  1. Standard (a group of separate PHP files)
  2. PHAR archives. PHAR comes from PHP Archive and it is the new PHP solution similar to Java JAR files.

System requirements

If using the standard version, OPL requires at least PHP 5.2. The recommended version is PHP 5.2.6, as the earlier ones contain an ugly bug that can affect some of the libraries.

OPL makes use of some classes available from PHP 5.3. On PHP 5.2, it activates its own replacements with the necessary functionality which are a bit slower.

The recommended version is PHP 5.3. OPL is also checked against PHP 6.

Required PHP modules:

  1. PCRE (bundled as of PHP 5.3)
  2. PHAR (bundled as of PHP 5.3), if using PHAR version.
  3. SPL
2. Installation
2.1. Standard installation
2. Installation
« Previous
2.2. PHAR installation
Next »

2.1. Standard installation

Create a single directory for the OPL libraries code called "installation directory". Each OPL package contains an /lib folder whose must be copied to the installation directory.

In order to use OPL libraries in your project, you need to load the core file and register an autoloader:

require('../../lib/Opl/Base.php');
Opl_Loader::setDirectory('../../lib/');
Opl_Loader::register();
 
// use the libraries now

OPL uses exceptions to report problems and errors. It is recommended to capture them. The basic exception class used by the libraries is Opl_Exception, but each of the libraries provides also its own class. OPL contains also the default exception handler:

require('../../lib/Opl/Base.php');
Opl_Loader::setDirectory('../../lib/');
Opl_Loader::register();
 
try
{
    // your code
}
catch(Opl_Exception $exception)
{
    Opl_Error_Handler($exception);
}
2. Installation
2.2. PHAR installation
2.1. Standard installation
« Previous
3. Design and concepts
Next »

2.2. PHAR installation

PHAR archives solve some problems with the directory structure and the initialization. Be sure that you have the appropriate archives and simply include them:

require('./opl.phar');
require('./opt.phar');
require('./opf.phar');
 
// use the libraries now

All the initialization is done automatically.

When loading a PHAR archive like above, PHP does not parse and execute all the scripts in the archive. It executes only the part called stub which initializes the library. The rest of the content is executed on demand.

The ordinary directory structure is necessary, if you are going to use third party components and add-ons. OPL libraries allow you to load them with the plugin system or include and register manually. In the second case, you might need to specify the exact paths to the class files manually, because the autoloader will try to find them in the archives:

require('./opl.phar');
require('./opt.phar');
require('./opf.phar');
 
Opl_Loader::mapAbsolute('Opx_Extra_Addon', './addons/Opx/Extra/Addon.php');

You can also pack the addons into another PHAR archive and configure the stub properly.

Table of Contents
3. Design and concepts
2.2. PHAR installation
« Previous
3.1. Autoloading
Next »

3. Design and concepts

This chapter provides the information about the library design.

3. Design and concepts
3.1. Autoloading
3. Design and concepts
« Previous
3.2. Coding standards
Next »

3.1. Autoloading

The OPL core provides its own general-purpose autoloader designed to handle the libraries that use the Foo_Bar_Joe class naming format. The autoloader provides an abstraction layer for the automatic class loading using various rules. Thus, you do not have to remember, how a certain library is organized and where the required classes are really located. The filesystem mapping rules are:

Foo -> Foo.php
Foo_Bar -> Foo/Bar.php
Foo_Bar_Joe -> Foo/Bar/Joe.php

The autoloading process

The autoloader is not limited to OPL libraries. Using it, you can also handle third party pieces of code, if they follow similar naming conventions, for example Zend Framework or Doctrine. The autoloader groups the classes into libraries, using the first part of the name. The class Foo_Bar is assumed to be a part of Foo library.

The autoloader features:

Currently, the autoloader does not support PHP 5.3 namespaces, however, they will be introduced very soon.

The common configuration

Let's create a common autoloader configuration:

// The autoloader itself must be loaded manually
require('./libs/Opl/Base.php');
 
Opl_Loader::register();
Opl_Loader::setDirectory('./libs/');
Opl_Loader::setDefaultHandler(array('Opl_Loader', 'oplHandler'));
 
// Now we can load the classes

The code snippet above configures the common autoloading settings for all the libraries:

In this example, the setDefaultHandler() does not have to be used, as this handler is active by default.

Library-specific settings

The last example has one disadvantage: the libraries that do not belong to OPL project probably won't want to follow the rules specified by the OPL handler. In this case we can configure everything manually:

// The autoloader itself must be loaded manually
require('./libs/Opl/Base.php');
 
Opl_Loader::register();
Opl_Loader::setDirectory('./libs/');
Opl_Loader::setDefaultHandler(null);
 
Opl_Loader::addLibrary('Opl', array('handler' => array('Opl_Loader', 'oplHandler')));
Opl_Loader::addLibrary('Opt', array('handler' => array('Opl_Loader', 'oplHandler')));
Opl_Loader::addLibrary('ExtraLibrary', array('handler' => 'someExtraHandler')));
 
// Now we can load the classes

Both OPL and OPT use the OPL handler and we have configured it for them, but the extra library uses different special rules and must use different handler.

Besides the handler, we may also define the library paths:

// The autoloader itself must be loaded manually
require('./libs/Opl/Base.php');
 
Opl_Loader::register();
Opl_Loader::addLibrary('ExtraLib1', array('directory' => './vendor/ExtraLib1/'));
Opl_Loader::addLibrary('ExtraLib2', array('basePath' => './vendor/'));

The difference between directory and basePath is clear, if we take a look at the directory structure:

/vendor
/vendor/ExtraLib1
/vendor/ExtraLib1/File.php
/vendor/ExtraLib2
/vendor/ExtraLib2/File.php
/vendor/ExtraLib1.php
/vendor/ExtraLib2.php

Handling unregistered libraries

By default, OPL autoloader tries to handle every possible class, but sometimes this is not the correct behavior. Let's take a look at the Doctrine ORM autoloader which also loads the model classes with the name ModelName, so we want OPL autoloader to skip them. The solution is provided below:

require('./libs/Opl/Base.php');
 
Opl_Loader::register();
Opl_Loader::setHandleUnknownLibraries(false);
Opl_Loader::addLibrary('Opl', array('basePath' => './libs/'));
Opl_Loader::addLibrary('Doctrine', array('basePath' => './libs/', 'handler' => null));
 
spl_autoload_register(array('Doctrine', 'autoload'));
 
$myModel = new MyModel;

When handling unknown libraries is disabled, the autoloader skips all the classes that do not belong to the libraries registered with addLibrary(). In the example above, we have registered Opl and Doctrine only. All the classes whose names do not begin with those two identifiers are skipped and left for the next autoloader in the queue.

PHAR-s

The autoloader can easily work with PHAR archives:

require('./libs/opl.phar');
require('./libs/opt.phar');

Yes, it is so simple, because PHAR-s are self-configurable and their stubs may automatically set the necessary options and handlers.

Conclusion

As we can see, the OPL autoloader is a quite powerful tool that is able to help you managing the increasing number of classes and files.

See also:

3. Design and concepts
3.2. Coding standards
3.1. Autoloading
« Previous
3.3. Configuration options
Next »

3.2. Coding standards

This document describes the coding standards used by OPL. All the PHP files in the project fall under these rules.

Directory structure

The installation directory (in this document: /src) is divided into several directories, one for each library. The library directory names must be a three-letter codes with the first character capitalized created from the first letters of the library name words. For example, Open Power Template code is OPT (directory name: Opt). In the rest of the document, the library directory in the file path will be marked as Opx.

The library directories contain the PHP files and other subdirectories. The names must begin with a capital letter.

File structure

The PHP file must begin with the <?php string and a license/copyright header that can be found in HEADER file. You must not end the file with ?>.

The file is divided into several parts marked by comment. The code template is:

<?php
/*
 *  OPEN POWER LIBS <http://www.invenzzia.org>
 *  ==========================================
 *
 * This file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE. It is also available through
 * WWW at this URL: <http://www.invenzzia.org/license/new-bsd>
 *
 * Copyright (c) Invenzzia Group <http://www.invenzzia.org>
 * and other contributors. See website for details.
 *
 * $Id$
 */
 
/*
 * Optional file description
 */
 
/*
 * Function definitions
 */
 
// code here
 
/*
 * Interface definitions
 */
 
// code here
 
/*
 * Class definitions
 */
 
// code here

Feel free to remove the parts you do not use.

By default, the file must contain exactly one class or interface, but it can contain more than one functions at the same time. The functions must be for internal use only, otherwise you must be sure that they will be available, when the user calls them, as the autoloader does not capture ordinary functions.

The exceptions are:

  1. Core files (/src/Opx/Class.php). They may contain any number of classes and interfaces. They should be necessary to make the library work, so that OPL does not waste time to include them from separate files.
  2. Exception files (/src/Opx/Exception.php) They may contain any number of classes whose names end with word Exception.

Naming rules

Naming rules for classes, interfaces, functions and class fields.

  1. Class names look as follows: Opx_Something_More. The name must begin with a three-letter library code. The name parts are separated with underline and begin with a big letter. They are automatically mapped to a file in the filesystem. For example, Opx_Something_More will be loaded from /src/Opx/Something/More.php.
  2. Interfaces follow the same rules as classes, but the last part of their name should be Interface, for example: Opl_Translation_Interface.
  3. Exception classes follow the same rules, as the rest of the classes, except that the last part of their name must be Exception, for example: Opl_Debug_Exception. Moreover, they must be stored in /src/Opx/Exception.php file.
  4. For class function and field names, we use camelCase.
  5. Protected, private and public internal use methods or fields must have names that begin with an underline, for example: _foo().
  6. For class constants, we use BIG_LETTER_NOTATION.
  7. For variable names, we use $camelCase.
  8. For standard function names, we use the same rules, as for classes, except that the name does not refer to the filesystem. Example: Opl_Error_Handler in /src/Opl/Exception.php file.

The names should be clever enough to illustrate what the particular function/class does. Moreover, you should keep the same naming patterns in your project - if your class contains several methods that do almost the same, all of their names should be similar. For example, in Open Power Template, the compiler contains a group of methods that allow to obtain various things. They are named like this: isProcessor(), isNamespace(), isFunction() etc.

Basic code formatting

The indentation must be done with tabulation. Spaces must not be used to format or indent the source code.

Classes, functions, etc.

All the classes, functions and interfaces may be one tab away from the left margin:

// Good
class Opx_Foo
{
 
}
 
    // Also good
    class Opx_Foo
    {
 
    }

Each curly bracket increases the indentation by one.

Opening curly brackets must be in a separate line:

// Good
class Opx_Foo
{
 
}
 
// Veeery bad, die, go to hell!
class Opx_Bar{
 
}

Class and interface closing curly brackets must be accompanied with the class/interface name written in the single line comment that looks like this: // end classname;

class Opx_Foo
{
 
} // end Opx_Foo;

The methods must follow it as well, but here we add also the round brackets to indicate what it is:

class Opx_Foo
{
    public function foo()
    {
 
    } // end foo();
 
} // end Opx_Foo;

All of the class items must have the visibility modifier: public, protected or private. You must not use var keyword or write methods without a public modifier.

Control structures

Basic information

While statement:

while($expression)
{
    someContent();
}

For statement:

for($i = 0; $i < 10; $i++)
{
    someContent();
}

do... while statement:

do
{
    someContent();
}
while($expression);

foreach statement:

foreach($array as $value)
{
    someCode();
}
 
foreach($array as $index => $value)
{
    someCode();
}

if-else statement:

if($expression)
{
    someContent();
}
elseif($expression)
{
    someContent();
}
else
{
    someContent();
}

switch statement:

switch($expression)
{
    case 'value1':
    case 'value2':
        someContent();
        break;
    case 'value3':
        someContent();
        break;
    default:
        someContent();
}

Try... catch statement:

try
{
    someContent();
}
catch(Exception $exception)
{
    exceptionHandler($exception);
}

Additional information

For statements should be used to iterate through an array with numeric indexes:

$cnt = sizeof($array);
for($i = 0; $i < $cnt; $i++)
{
    someContent($array[$i]);
}

To iterate through associative arrays, we use foreach.

In switch, we are allowed to create constructs with advanced flow control (i.e. conditional breaks), if it makes the code shorter and simpler to understand.

If we have to move the iterator until the condition is not true, we can use the following construct:

for(start_condition; end_condition; iterate){}

Expressions

Basic information

The operators should be separated from values with one space. It can be avoided, if the expression is very long:

// short expression
$a + $b
// very long expression
$a+$b+$c+$d+$e+$f+$g+$h+$i+$j+$k+$l+$m+$n+$o+$p+$r+$s+$t+$u+$v+$w+$x+$y+$z

For strings, single quotes must be used unless we have newline/carriage return/tab characters to show. We connect the strings with the values with dots:

'Single quoted text';
'Single quoted text '.$data.' with some data';
"Double quoted text, because it uses \r\n";

The object access operators are written without surrounding spaces:

$obj->method();
class::method();

The use of brackets:

$a * ($b + $c)
$a[$b][$c]

The conditional operator should be written in brackets:

$a = ($b == true ? 'Foo' : 'Bar');

Data type information

OPL makes use of the NULL type. The methods must return null instead of the requested content, if such content has not been found:

if(!isset($foo[$resource]))
{
    return NULL;
}
return $foo[$resource];

To check, whether the NULL value has been returned, we the === null expression:

if($foo === null)
{
    someContent();
}

Other issues

Data structures

If we are going to use a data structure, we must use SPL implementations:

  1. SplDoublyLinkedList
  2. SplQueue
  3. SplStack
  4. SplHeap
  5. SplPriorityQueue
  6. SplFixedArray

However, we must pay attention to PHP 5.2. If the requested functionality is not implemented in /Opl/Php52.php, we should implement it.

Comments

The code must be commented. For short notes, we use single-line comments:

// Now we must do foo.

We do not comment obvious things and issues.

For longer explanations, we use multiline comments:

/* This is a multiline
 * comment that explains
 * something
 */

In the development code, we should mark the unfinished places with TODO comments:

// TODO: Implement XXX!

Documentation

The methods and the most important class fields should be equipped with phpdoc That briefly describes the particular item and provides some information on the arguments and return values.

/**
 * This method does something.
 * 
 * @param string $foo The required argument
 * @param int $bar=5 optional The optional argument
 * @return int
 */
public function something($foo, $bar = 5)
{
    // ...
} // end something();

Please note that phpdoc is not used to generate the API reference, but rather provides the basic help for programmers and IDE.

3. Design and concepts
3.3. Configuration options
3.2. Coding standards
« Previous
4. API reference
Next »

3.3. Configuration options

The OPL core can be configured by setting the Opl_Registry states. These options apply to all OPL libraries:

Opl_Registry::setState('some_option', 'value');

Below, you can find a list of possible options:

opl_debug_console
Turns on/off the debug console globally
opl_extended_errors
Shows the extended error information in the exception handler. You should disable this option in your production environment.
opl_custom_console
Hides the default debug console generated by OPL, allowing to install a custom one. The original console still collects the data, and the programmer may load them from the console memory.
Table of Contents
4. API reference
3.3. Configuration options
« Previous
4.1. Opl_Class class
Next »

4. API reference

This chapter provides the core API reference. Note that OPL allows to rewrite the core in order to integrate the libraries with your framework and therefore the API divides in two parts:

  1. OPL public API - for library users
  2. OPL library API - for library programmers

If you are going to rewrite the OPL core, only the second part needs to be implemented. There are available the code templates on the OPL website with the autoloader and optional PHAR generators.

4. API reference
4.1. Opl_Class class
4. API reference
« Previous
4.1.1. _pluginLoader()
Next »

4.1. Opl_Class class

ConstructAbstract class
Extended byOpc_Class, Opf_Class, Opt_Class

Generic core class for the libraries. It provides the basic configuration and plugin management functionality.

Configuration support

The general library configuration should be done as public fields with short and intuitive names and default values set. However, Opl_Class supports also additional fields with __get() and __set() methods.

If you try to read the undefined directive, Opl_OptionNotExists_Exception is thrown.

There is also a generic interface for loading and returning the configuration:

  1. Opl_Class::loadConfig()
  2. Opl_Class::getConfig()

Plugin support

If the library is going to use plugins, it must implement Opl_Class::_pluginLoader() protected method. Opl_Class defines three configuration directives for plugins:

pluginDir
string A single directory with plugins.
array A list of directories with plugins.
pluginDataDir
string A directory for storing the plugin loader information. It must be writable by the script.
pluginAutoload
boolean If set to true, the plugins are automatically detected and loaded once they are put in one of the pluginDir directories. If set fo false, you must manually remove the plugin loader information from pluginDataDir.
4.1. Opl_Class class
4.1.1. _pluginLoader()
4.1. Opl_Class class
« Previous
4.1.2. _securePath()
Next »

4.1.1. _pluginLoader()

ConstructMethod
Visibilityprotected
Referencevoid Opl_Class::_pluginLoader( string $directory, string $file )
Argument list
$directory - string
The directory, where the plugin is stored.
$file - string
The file, where the plugin is stored.
Versionssince 2.0.0-dev7

The method is used, when the temporary plugin file is being rebuilt. It takes the directory and the filename and it must generate a PHP code that loads it. This is a sample implementation:

protected function _pluginLoader($dir, $file)
{
    return 'require(\''.$dir.$file.'\'); ';
} // end _pluginLoader();

See also:

4.1. Opl_Class class
4.1.2. _securePath()
4.1.1. _pluginLoader()
« Previous
4.1.3. getConfig()
Next »

4.1.2. _securePath()

Statusinternal
ConstructMethod
Visibilitypublic
Referencevoid Opl_Class::_securePath( string &$path )
Argument list
$path - &string
The path to secure.
Versionssince 2.0.0-dev8

A help method to sanitize the file paths by adding the slash to the end, if the user has not provided it:

$path = 'this/is/some/path';
$this->_securePath($path);
echo $path; // shows "this/is/secure/path/"

As of OPL 2.0.2 the method visibility is changed from protected to public in order to simplify the further migration to OPL 2.1. This is an internal method, so the change should not affect existing scripts.

4.1. Opl_Class class
4.1.3. getConfig()
4.1.2. _securePath()
« Previous
4.1.4. loadConfig()
Next »

4.1.3. getConfig()

ConstructMethod
Visibilitypublic
Referencearray Opl_Class::getConfig()
Returned valueThe current library configuration.
Versionssince 2.0.0-dev8

Returns the entire library configuration as an array.

4.1. Opl_Class class
4.1.4. loadConfig()
4.1.3. getConfig()
« Previous
4.1.5. loadPlugins()
Next »

4.1.4. loadConfig()

ConstructMethod
Visibilitypublic
Referencebool Opl_Class::loadConfig( mixed $config )
Argument list
$config - mixed
The array with the configuration or the path to the INI file.
Returned valueTrue on success.
Versionssince 2.0.0-dev7

Loads the library configuration from an array or INI file. Returns false if the file could not be loaded or $config is not array.

4.1. Opl_Class class
4.1.5. loadPlugins()
4.1.4. loadConfig()
« Previous
4.2. Opl_Debug
Next »

4.1.5. loadPlugins()

ConstructMethod
Visibilitypublic
Referencevoid Opl_Class::loadPlugins()
Thrown exceptionsOpl_NotWriteable_Exception, Opl_FileNotExists_Exception, Opl_InvalidType_Exception
Versionssince 2.0.0-dev7

Loads the plugins stored in all of the pluginDir directories. The directories are scanned only once, to create a temporary PHP file which loads the rest. The file is saved in pluginDataDir. If pluginAutoload is true, the plugin directories are scanned for modifications. If there are any new plugins, the temporary file is rebuilt.

In order to create a support for plugins in your library, you have to implement the Opl_Class::_pluginLoader() method.

See also:

4. API reference
4.2. Opl_Debug
4.1.5. loadPlugins()
« Previous
4.2.1. backtrace()
Next »

4.2. Opl_Debug

ConstructClass

The class provides some debugging utilities helpful during the development process. Note that the final code should not contain any references to this class.

4.2. Opl_Debug
4.2.1. backtrace()
4.2. Opl_Debug
« Previous
4.2.2. dump()
Next »

4.2.1. backtrace()

Statusstatic public
Referencevoid Opl_Debug::backtrace()

Prints the debug backtrace.

4.2. Opl_Debug
4.2.2. dump()
4.2.1. backtrace()
« Previous
4.2.3. printFlags()
Next »

4.2.2. dump()

Statusstatic public
Referencevoid Opl_Loader::dump( Mixed $value, String $desc = '' )

Dumps the specified $value to the script output. It allows to add an optional description that helps to find the dump in the output.

4.2. Opl_Debug
4.2.3. printFlags()
4.2.2. dump()
« Previous
4.2.4. write()
Next »

4.2.3. printFlags()

Statusstatic public
Referencevoid Opl_Debug::printFlags( Integer $value, Boolean $console = false )

This is a helper method to work with bitwise flags. It displays the numbers of bits that are set to 1 in the integer $value. The optional argument $console allows to prepare an output for the system console instead of packing it into HTML.

4.2. Opl_Debug
4.2.4. write()
4.2.3. printFlags()
« Previous
4.2.5. writeErr()
Next »

4.2.4. write()

Statusstatic public
Referencevoid Opl_Loader::write( String $value, Boolean $console = false )

Prints the specified value in the output. If the $console is set to false, the method packs the value into HTML tags that cause it to be displayed in the new line. For $console = true, it simply adds the newline characters to the value.

4.2. Opl_Debug
4.2.5. writeErr()
4.2.4. write()
« Previous
4.3. Opl_Debug_Console
Next »

4.2.5. writeErr()

Statusstatic public
Referencevoid Opl_Loader::writeErr( String $value )

Prints the specified value in the standard error output. It automatically adds the newline characters to the value.

4. API reference
4.3. Opl_Debug_Console
4.2.5. writeErr()
« Previous
4.3.1. addList()
Next »

4.3. Opl_Debug_Console

ConstructClass

This class provides the debug console services for the OPL libraries. It generates the debug console and provides an interface to add new data to the console.

4.3. Opl_Debug_Console
4.3.1. addList()
4.3. Opl_Debug_Console
« Previous
4.3.2. addListOption()
Next »

4.3.1. addList()

Statusstatic public
Referencevoid Opl_Debug_Console::addList( String $id, String $title)

Creates a new list of "key => value" pairs in the debug console with the specified $title. $id should be an unique key that allows to refer to this list.

4.3. Opl_Debug_Console
4.3.2. addListOption()
4.3.1. addList()
« Previous
4.3.3. addListOptions()
Next »

4.3.2. addListOption()

Statusstatic public
Referencevoid Opl_Debug_Console::addListOption( String $id, String $title, Mixed $value)

Adds a new "key => value" pair to the list $id.

4.3. Opl_Debug_Console
4.3.3. addListOptions()
4.3.2. addListOption()
« Previous
4.3.4. addTable()
Next »

4.3.3. addListOptions()

Statusstatic public
Referencevoid Opl_Debug_Console::addListOptions( String $id, Array $options )

Adds the "key => value" pairs from the associative array $options to the list $id.

4.3. Opl_Debug_Console
4.3.4. addTable()
4.3.3. addListOptions()
« Previous
4.3.5. addTableInformation()
Next »

4.3.4. addTable()

Statusstatic public
Referencevoid Opl_Debug_Console::addTable( String $id, String $title, Array $columns )

Creates a new table in the debug console entitled $title. The $id should be an unique key that allows to refer to this table later. $columns must contain a list of table column titles. You may prepend them with the width, for example 50%:Column name. An example:

Opl_Debug_Console::addTable('table', 'My debugging table', array(
    '30:#',
    '*:Column 1',
    '25%:Column 2'
));
4.3. Opl_Debug_Console
4.3.5. addTableInformation()
4.3.4. addTable()
« Previous
4.3.6. addTableItem()
Next »

4.3.5. addTableInformation()

Statusstatic public
Referencevoid Opl_Debug_Console::addTableInformation( String $id, String $information )

Adds some extra information that will be displayed under the specified table title.

4.3. Opl_Debug_Console
4.3.6. addTableItem()
4.3.5. addTableInformation()
« Previous
4.3.7. display()
Next »

4.3.6. addTableItem()

Statusstatic public
Referencevoid Opl_Debug_Console::addTableItem( String $id, Array $columnValues)

Adds a new item to the table $id. The $columnValues array must contain a list of values to be shown in the table columns:

Opl_Debug_Console::addTable('table', 'My debugging table', array(
    '30:#',
    '*:Column 1',
    '25%:Column 2'
));
Opl_Debug_Console::addTableItem('table', array(
    5, 'Text 1', 'Text 2'
));
4.3. Opl_Debug_Console
4.3.7. display()
4.3.6. addTableItem()
« Previous
4.3.8. getLists()
Next »

4.3.7. display()

Statusstatic public
Referencevoid Opl_Debug_Console::display()

If the global configuration option opl_custom_console is not set, displays the debug console in the output.

4.3. Opl_Debug_Console
4.3.8. getLists()
4.3.7. display()
« Previous
4.3.9. getTables()
Next »

4.3.8. getLists()

Statusstatic public
Referencearray Opl_Debug_Console::getLists( )
Returned valueThe array of lists registered in OPT
Versionssince 2.0.3

Returns the lists currently maintained by the debug console. The returned value is an assotiative array of pairs unique list ID => options. Each list options consist of a pair of elements:

See also:

4.3. Opl_Debug_Console
4.3.9. getTables()
4.3.8. getLists()
« Previous
4.4. Opl_ErrorHandler class
Next »

4.3.9. getTables()

Statusstatic public
Referencearray Opl_Debug_Console::getTables( )
Returned valueThe array of tables registered in OPT
Versionssince 2.0.3

Returns the tables currently maintained by the debug console. The returned value is an assotiative array of pairs unique table ID => options. Each list options consist of four elements:

See also:

4. API reference
4.4. Opl_ErrorHandler class
4.3.9. getTables()
« Previous
4.4.1. _resolveContextInfo()
Next »

4.4. Opl_ErrorHandler class

ConstructClass
Extended byOpt_ErrorHandler

The class provides a generic interface for exception handling. This includes:

  1. Displaying the message
  2. Providing some debug information, if necessary
  3. Providing context information for specified exception types.

By overwriting the class, you can create a support for exceptions in other libraries, or changing the default error layout.

4.4. Opl_ErrorHandler class
4.4.1. _resolveContextInfo()
4.4. Opl_ErrorHandler class
« Previous
4.4.2. display()
Next »

4.4.1. _resolveContextInfo()

Statusprotected
Referencevoid Opl_ErrorHandler::_resolveContextInfo( Opl_Exception $exception )
Versionssince 2.0.0-dev8

Displays the informers associated with the specified exception $exception.

Informer is a special method in the error handler that is able to display some extra information about the exception, for example the library configuration or the backtrace.

The list of informers is stored in the protected field $_context. The method may be used in display() to display the context information in the specified place.

Context help

A sample list of informers may look like this:

protected $_context = array(
    'Exception_Name_1' => array(
        'Informer1' => array('Informer arguments'),
        'Informer2' => array('Informer arguments'), 
    ),
    'Exception_Name_2' => array(
        'Informer1' => array('Informer arguments'),
        'Informer2' => array('Informer arguments'), 
    ),
    // For other exceptions
    '__UNKNOWN__' => array(
        'Informer1' => array('Informer arguments'),
        'Informer2' => array('Informer arguments'), 
    ),
);

The informers are simple methods that take the exception object as the first argument, but optionally, they can take much more. The method name must begin with _print, so that Informer1 points to _printInformer1 method. The HTML code must be displayed with echo.

Available informers

OPL provides the following filters:

  1. ErrorInfo - displays the text provided in the argument.
  2. StackInfo - used to display stack assigned to the exception, with marking the last element as invalid. In the argument we can specify the stack title.
  3. BasicConfiguration - used to print the basic library configuration. This method must be extended in the particular library error handlers in order to work.
  4. Backtrace - prints the backtrace.

The libraries may also provide their own informers.

4.4. Opl_ErrorHandler class
4.4.2. display()
4.4.1. _resolveContextInfo()
« Previous
4.5. Opl_Loader class
Next »

4.4.2. display()

Statuspublic
Referencevoid Opl_ErrorHandler::display( Opl_Exception $exception )
Versionssince 2.0.0-dev8

Displays the specified exception and runs informers, if necessary.

try
{
 
 
}
catch(Opl_Exception $exception)
{
    $handler = new Opl_ErrorHandler;
    $handler->display($exception);
}
4. API reference
4.5. Opl_Loader class
4.4.2. display()
« Previous
4.5.1. addLibrary()
Next »

4.5. Opl_Loader class

ConstructClass

This class provides the necessary autoload utilities for the OPL core. The autoloader supports the following features:

  1. Automatic loading based on the class/interface name.
  2. Core files with more than one class and interface that are always used by the library and therefore must be always available.
  3. Manual mapping. You can provide the path to the file with the class manually.
4.5. Opl_Loader class
4.5.1. addLibrary()
4.5. Opl_Loader class
« Previous
4.5.2. autoload()
Next »

4.5.1. addLibrary()

ConstructStatic method
Visibilitypublic
Referencevoid addLibrary(string $library, array $config);
Argument list
$library - string
The library name and prefix of its classes.
$config - array
The library configuration.
Versionssince 2.0-RC1

Adds the specific settings for the library $library. The rules will be applied to all the classes beginning with the prefix $library. The allowed settings are:

By default, the autoloader uses the OPL handler. If you are going to use the autoloader with non-OPL libraries, you should disable it for them.

Opl_Loader::addLibrary('Foo', array('directory' => './foo', 'handler' => 'myHandlerFunction'));
Opl_Loader::load('Foo_Class');

The example above will load the Foo_Class source code from the ./foo/ directory and use the myHandlerFunction to deal with some specific autoloading needs.

Library handlers

The standard autoloader converts the class name to the file name by replacing the underscores with the directory separator and adding the .php file extension. However, some libraries may have some specific needs. For example, in OPL the autoloader must perform the following extra actions:

Such needs are supported with external handlers. If your library needs one, with this method you can add it. The handler must be an ordinary function or class method:

boolean autoloadingHandler(string $library, string $className)

The method must return true, if the autoloader should still load the file using the standard rules and false, if the handler has already found and loaded the requested class.

See also:

4.5. Opl_Loader class
4.5.2. autoload()
4.5.1. addLibrary()
« Previous
4.5.3. getDirectory()
Next »

4.5.2. autoload()

ConstructStatic method
Visibilitypublic
Referencebool Opl_Loader::autoload( string $className )
Argument list
$className - string
The class to load.
Returned valueFalse, if the class cannot be found with this autoloader.
Versionssince 2.0.0-dev7

The class autoloading method. It has to be registered as an autoloader in order to use OPL properly:

Opl_Loader::register();

See also:

4.5. Opl_Loader class
4.5.3. getDirectory()
4.5.2. autoload()
« Previous
4.5.4. getLibraryPath()
Next »

4.5.3. getDirectory()

ConstructStatic method
Visibilitypublic
Referencestring Opl_Loader::getDirectory()
Returned valueThe current library directory.
Versionssince 2.0.0-dev7

Returns the current location of OPL class files.

4.5. Opl_Loader class
4.5.4. getLibraryPath()
4.5.3. getDirectory()
« Previous
4.5.5. load()
Next »

4.5.4. getLibraryPath()

ConstructStatic method
Visibilitypublic
Referencestring Opl_Loader::getLibraryPath( string $library )
Argument list
$library - string
The library name
Returned valueThe path to the library files
Versionssince 2.0-RC1

Returns the path to the specified library files.

4.5. Opl_Loader class
4.5.5. load()
4.5.4. getLibraryPath()
« Previous
4.5.6. loadPaths()
Next »

4.5.5. load()

ConstructStatic method
Visibilitypublic
Referencebool Opl_Loader::load( $className )
Argument list
$className - string
The class to load.
Returned valueFalse, if the class cannot be found with this autoloader.
Versionssince 2.0.0-dev7

An alias to Opl_Loader::autoload().

See also:

4.5. Opl_Loader class
4.5.6. loadPaths()
4.5.5. load()
« Previous
4.5.7. map()
Next »

4.5.6. loadPaths()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::loadPaths( String|Array $paths )
Argument list
$paths - mixed
The path to the INI file or array with library definitions.
Versionssince 2.0.0-beta2

Loads the path configuration from the array $paths or from the INI file, if $paths is a string with a valid filesystem path. A sample INI file:

; The main path
directory = "./"
 
; Per-library paths
[libraries]
Opl = "/yourpath/Opl/lib/"
Opt = "/yourpath/Opt/lib/"

This method has been added only for development purposes. You should not use it in the production environment.

See also:

4.5. Opl_Loader class
4.5.7. map()
4.5.6. loadPaths()
« Previous
4.5.8. mapAbsolute()
Next »

4.5.7. map()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::map( string $className, string $file )
Argument list
$className - string
The class name to map.
$file - string
The file with the class.
Versionssince 2.0.0-dev7

Allows to specify the path to the class $className manually within its library directory.

Opl_Loader::setDirectory('../libs/');
Opl_Loader::map('Opx_Some_Class', 'Sth/Else/Somefile.php');
 
// Loads this class from `../libs/Opx/Sth/Else/Somefile.php`
$obj = new Opx_Some_Class;

To specify an absolute path, use Opl_Loader::mapAbsolute().

See also:

4.5. Opl_Loader class
4.5.8. mapAbsolute()
4.5.7. map()
« Previous
4.5.9. mapLibrary()
Next »

4.5.8. mapAbsolute()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::map( string $className, string $file )
Argument list
$className - string
The class name to map.
$file - string
The file with the class.
Versionssince 2.0-beta2

Allows to specify the path to the class $className manually, ignoring the library directory settings.

A comparison example:

Opl_Loader::setDirectory('../libs/');
 
Opl_Loader::map('Opx_Class1', 'Some/File.php');
Opl_Loader::mapAbsolute('Opx_Class2', '../libs2/file.php');
 
// Loaded from `../libs/Opx/Some/File.php`
$item = new Opx_Class1;
 
// Loaded from `../libs2/file.php`
$item = new Opx_Class2;

See also:

4.5. Opl_Loader class
4.5.9. mapLibrary()
4.5.8. mapAbsolute()
« Previous
4.5.10. oplHandler()
Next »

4.5.9. mapLibrary()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::mapLibrary( string $libraryName, string $directory )
Argument list
$libraryName - string
The library name
$directory - string
The directory with the library files.
Versionssince 2.0-beta2

The method is an alias to addLibrary() method, limited to specifying the alternative library directory.

See also:

4.5. Opl_Loader class
4.5.10. oplHandler()
4.5.9. mapLibrary()
« Previous
4.5.11. pharHandler()
Next »

4.5.10. oplHandler()

ConstructStatic method
Visibilitypublic
Referenceboolean oplHandler(string $library, string $className);
Argument list
$library - string
The library name to handle.
$className - string
The class name to load.
Versionssince 2.0-RC1

The OPL autoloading handler which is enabled by default in the autoloader.

See also:

4.5. Opl_Loader class
4.5.11. pharHandler()
4.5.10. oplHandler()
« Previous
4.5.12. register()
Next »

4.5.11. pharHandler()

ConstructStatic method
Visibilitypublic
Referenceboolean pharHandler(string $library, string $className);
Argument list
$library - string
The library name to handle.
$className - string
The class name to load.
Versionssince 2.0-RC1

The OPL autoloading handler used by the PHAR-s.

See also:

4.5. Opl_Loader class
4.5.12. register()
4.5.11. pharHandler()
« Previous
4.5.13. removeLibrary()
Next »

4.5.12. register()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::register()
Versionssince 2.0-beta2

Registers the autoloader in the PHP stack.

4.5. Opl_Loader class
4.5.13. removeLibrary()
4.5.12. register()
« Previous
4.5.14. setCheckFileExists()
Next »

4.5.13. removeLibrary()

ConstructStatic method
Visibilitypublic
Referencevoid removeLibrary(string $library);
Argument list
$library - string
The library to remove.
Versionssince 2.0-RC1

Removes the library-specific settings from the autoloader.

See also:

4.5. Opl_Loader class
4.5.14. setCheckFileExists()
4.5.13. removeLibrary()
« Previous
4.5.15. setDefaultHandler()
Next »

4.5.14. setCheckFileExists()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::setCheckFileExists( boolean $status )
Argument list
$status - boolean
Versionssince 2.0-RC1

Specifies, whether the autoloader should check the file existence in the filesystem (true) or not (false).

Due to the performance reasons, we recommend to keep this setting disabled, especially in the production environment.

4.5. Opl_Loader class
4.5.15. setDefaultHandler()
4.5.14. setCheckFileExists()
« Previous
4.5.16. setDirectory()
Next »

4.5.15. setDefaultHandler()

ConstructStatic method
Visibilitypublic
Referencevoid setDefaultHandler(callback $handler);
Argument list
$handler - callback
The callback to the new default library handler.
Versionssince 2.0-RC1

Sets the default autoloading handler that will be used for all the libraries that do not have their own specific settings. The $handler argument must be a valid PHP callback to the following function or method:

boolean autoloadingHandler(string $library, string $className)

The function must return true, if the standard autoloading process should be still performed or false, if the handler has already found and loaded the requested class.

To disable the default handler feature, you must set the $handler argument to null.

The autoloader is initialized with the OPL handler by default. If you wish to use the autoloader with non-OPL libraries, you should use this method to disable it.

See also:

4.5. Opl_Loader class
4.5.16. setDirectory()
4.5.15. setDefaultHandler()
« Previous
4.5.17. setHandleUnknownLibraries()
Next »

4.5.16. setDirectory()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::setDirectory( string $directory )
Argument list
$directory - string
The new directory with the libraries.
Versionssince 2.0.0-dev7

Sets the directory, where the autoloader should look for class files.

See also:

4.5. Opl_Loader class
4.5.17. setHandleUnknownLibraries()
4.5.16. setDirectory()
« Previous
4.6. Opl_Registry class
Next »

4.5.17. setHandleUnknownLibraries()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Loader::setHandleUnknownLibraries( boolean $status )
Argument list
$status - boolean
The new status.
Versionssince 2.0-RC1

With this method, you can control, whether OPL autoloader should handle the libraries that have not been registered with addLibrary() or not. By default, such handling is enabled, however in the following example it conflicts with another autoloader and we must turn it off:

Opl_Loader::addLibrary('Opl', array('directory' => './path/to/Opl/'));
Opl_Loader::addLibrary('ExtraLibrary', array('directory' => './path/to/ExtraLibrary/'));
Opl_Loader::setHandleUnknownLibraries(false);
 
$class = new SomeExtraLibraryStuff; // do not handle it with OPL
4. API reference
4.6. Opl_Registry class
4.5.17. setHandleUnknownLibraries()
« Previous
4.6.1. exists()
Next »

4.6. Opl_Registry class

ConstructClass

Generic storage class that helps to manage global objects, settings and other data.

4.6. Opl_Registry class
4.6.1. exists()
4.6. Opl_Registry class
« Previous
4.6.2. get()
Next »

4.6.1. exists()

ConstructStatic method
Visibilitypublic
Referencebool Opl_Registry::exists( string $name )
Argument list
$name - string
The object name.
Returned valueTrue, if the specified object exists.
Versionssince 2.0.0-dev7

Returns true, if the specified object $name is registered.

See also:

4.6. Opl_Registry class
4.6.2. get()
4.6.1. exists()
« Previous
4.6.3. getState()
Next »

4.6.2. get()

ConstructStatic method
Visibilitypublic
Referenceobject Opl_Registry::get( string $name )
Argument list
$name - string
The object name.
Returned valueThe registered object.
Thrown exceptionsOpl_Debug_ItemNotExists_Exception
Versionssince 2.0.0-dev7

Returns previously registered object:

Opl_Registry::register('foo', new Opl_Foo_Object);
 
$obj = Opl_Registry::get('foo');

If the object does not exists, Opl_Debug_ItemNotExists_Exception is thrown.

See also:

4.6. Opl_Registry class
4.6.3. getState()
4.6.2. get()
« Previous
4.6.4. register()
Next »

4.6.3. getState()

ConstructStatic method
Visibilitypublic
Referencemixed Opl_Registry::getState( string $name )
Argument list
$name - string
The state name
Returned valueThe state value
Versionssince 2.0.0-dev7

Returns the specified value stored as $name. If the state does not exist, the method returns null.

See also:

4.6. Opl_Registry class
4.6.4. register()
4.6.3. getState()
« Previous
4.6.5. setState()
Next »

4.6.4. register()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Registry::register( string $name, object $object )
Argument list
$name - string
The name that will be given to the object in the registry.
$object - object
The object to store.
Versionssince 2.0.0-dev7

Registers the specified object as $name.

Opl_Registry::register('foo', new Opl_Foo_Object);
 
$obj = Opl_Registry::get('foo');

See also:

4.6. Opl_Registry class
4.6.5. setState()
4.6.4. register()
« Previous
4.7. Opl_Translation_Interface
Next »

4.6.5. setState()

ConstructStatic method
Visibilitypublic
Referencevoid Opl_Registry::setState( string $name, mixed $value )
Argument list
$name - string
The new state name
$value - mixed
The state value
Versionssince 2.0.0-dev7

Stores the specified scalar $value (string, integer, boolean etc.) under the $name. This is used also as a global OPL configuration utility:

Opl_Registry::setState('foo', 'value');
echo Opl_Registry::getState('foo');

See also:

4. API reference
4.7. Opl_Translation_Interface
4.6.5. setState()
« Previous
4.7.1. _()
Next »

4.7. Opl_Translation_Interface

ConstructInterface

This is an interface for the translation services in OPL. It allows to read the interface texts using simple and short keys. The programmer should implement language-specific features on his own.

4.7. Opl_Translation_Interface
4.7.1. _()
4.7. Opl_Translation_Interface
« Previous
4.7.2. assign()
Next »

4.7.1. _()

ConstructAbstract method
Visibilitypublic
Referencestring Opl_Translation_Interface::_( $group, $id )
Argument list
$group - string
The language group name
$id - string
The message ID
Versionssince 2.0.0-dev7

Returns the text assigned to the specified $id in group $group.

4.7. Opl_Translation_Interface
4.7.2. assign()
4.7.1. _()
« Previous
5. Appendix
Next »

4.7.2. assign()

ConstructAbstract method
Visibilitypublic
Referencemixed Opl_Translation_Interface::assign( $group, $id, ... )
Argument list
$group - string
The language group name
$id - string
The message ID
... - mixed
The values to assign to the message.
Versionssince 2.0.0-dev7

Assigns the values provided as the extra arguments to the specified text $id in group $group. The method should also return the generated string.

Table of Contents
5. Appendix
4.7.2. assign()
« Previous
A. Future release information
Next »

5. Appendix

This chapter contains some extra information about the project.

5. Appendix
A. Future release information
5. Appendix
« Previous
B. Support
Next »

Appendix A. Future release information

In this chapter, you can find some information about the future releases of OPL and the roadmap.

Version compatibility

The PHP language evolves and introduces many important features with every new major release. We want to produce a reliable software that is compatible both forwards and backwards. Below, you can find an information about the OPL version compatibility with PHP releases.

OPL 2.0
Requires PHP 5.2.0+
Must work on PHP 5.2, 5.3 and 6.0 in the future
Support: at least to the end of 2010
OPL 2.1
Requires PHP 5.3.0+
Must work on PHP 5.3 and 6.0
Support: at least 2 years from the release date
OPL 2.2 and the other
Same requirements as 2.1
OPL 3.0
Requires PHP 6.0+
Must work on PHP 6.0 and future releases

Planned improvements

Improved debug console

In OPL 2.1 we would like to provide a new, more convenient and portable debugging console system, more similar to those ones that can be found in various frameworks. The backward compatibility will be retained. The rendering part will be separated from the data collector, so that it will be much easier to write custom rendering codes.

Command Line Interface

The libraries from 2.1 branch are planned to have a command line interface. OPL core will introduce a small framework for writing modular console management applications.

Namespace supports

PHP 5.3 introduced the concept of namespaces. Currently, the autoloader cannot handle correctly the code that uses them. Such a support is planned for OPL 2.1.

5. Appendix
B. Support
A. Future release information
« Previous
C. Reporting bugs
Next »

Appendix B. Support

If you have a problem with the OPL library and do not know how to solve it, take a look at our discussion board, forums.invenzzia.org - we will try to help you find the solution and talk about many other things.

Support rules

5. Appendix
C. Reporting bugs
B. Support
« Previous
D. License and authors
Next »

Appendix C. Reporting bugs

If you found a bug, please visit our bugtracker: bugs.invenzzia.org and report it. You will help developing the library.

How to use the bugtracker?

  1. We use the same bugtracker for various projects. Be sure that you add the report to the correct project.
  2. If it is possible, the report should contain a standalone test case that is ready to run. This will speed up reproducing the bug on our computers and creating the patch. If we cannot reproduce the bug, probably it will not be fixed.
  3. Include the information on OPL and PHP versions, as well as other projects that could interfere with the library.
  4. Please describe the expected behavior and the actual result.
  5. We include the full error message, if it is provided.
  6. The report must be written in English.
  7. Remember: if we need extra information, we will ask for them.
5. Appendix
D. License and authors
C. Reporting bugs
« Previous

Appendix D. License and authors

Open Power Libraries 2 was designed and created by the Invenzzia programming group which is also the holder of the copyrights. The people that worked on this:

Copyright © Invenzzia Group 2008-2009 - www.invenzzia.org

License

Open Power Libraries 2.0 is available under the terms of new BSD license. It is included in the library archives.

This documentation is available under the terms of GNU Free Documentation License 1.2. Its content is included in the library archives and the source files are available to download on the Invenzzia website.