-
Notifications
You must be signed in to change notification settings - Fork 0
Dev.Kernel APIs
config
service
engine
registry
log
model
db
debug
path
url
value|Pi\Application\Config Pi::config(string $name = null, string $domain = '')
This static method is provided by system, it is used to load configuration data of Pi. The object this method could operate are the files in the var/config
directory and data similar to application's config
table where category
is general
and module
is system
.
Parameters
name
Specifying the name of configuration element and configuration data will be returned according to this parameter.
domain
Configuration domain.
Return values
This API will return the configuration data of Pi by passed name parameter, if the name parameter is not set, this API will return a Pi\Application\Config
handler. It can help you to operate with configuration data.
The default values of name parameter you can use are come from two resources:
-
Fields in
config
array ofvar/config/engine.php
folder; -
The value of
title
field in application'sconfig
table where category is general.$config = Pi::config('environment'); $config = Pi::config('sitename'); $config = Pi::config('theme');
The value of $config
will be:
'debug'
'Web Applications'
'default'
Pi/Application/Config
Methods in this class can help you to fetch configuration data from the file specified. Methods in Config
class are:
mixed value get(string $name, string $domain = '');
Config object set(string $name, mixed $value, string $domain = '');
Config object setConfigs(array $configs, string $domain = '');
Config object unsetDomain(string $domain = '');
Config object loadDomain(string $domain = '');
array load(string $configFile);
-
loadDomain()
This method is used to load configuration data of a domain from table
config
, it do not return the data directly, but callsetConfigs()
to store data, you can callget()
method to fetch the data.$config = Pi::config()->loadDomain(); $configs = $config->get('sitename'); $configs = Pi::config()->loadDomain('meta')->get('author', 'meta');
The
$configs
value of second line may be the following data as default:'Pi'
The
loadDomain()
method achieves loading data for later uses, so we can fetch the data indirectly:$config = Pi::config()->loadDomain('meta'); ... $configs = $config->get('author', 'meta');
-
load()
This method is used to load configuration data in
var/config
directory by file name:$configs = Pi::config()->load('host.php'); $configs = Pi::config()->load('service.database.php');
Pi\Application\Service\ServiceAbstract|Pi\Application\Service Pi::service(string $name = null, array $options = array())
Parameters
name
Name of service classes to load. This value should be the file name without suffix in the Pi/Application/Service
directory.
options
Value for constructing an object.
Return values
If the name
parameter is not set, a Pi\Application\Service
handler will be returned. Or else, it will return a handler relates to the parameter name
. For example, if the first parameter set to database
, and class Pi\Application\Service\Database
is exists, the handler of this class will be returned.
The following two examples will have the same results:
$assetService = Pi::service()->load('asset');
$assetService = Pi::service('asset');
The output is a handler:
'Pi/Application/Service/Asset'
Pi/Application/Service/Asset
This class is used to operate the asset
directory of Pi. Part of methods in this class are list as follows:
string getBasePath();
string getBaseUrl();
string getPath(string $component);
string getUrl(string $component);
string getAssetPath(string $component, string $file);
string getAssetUrl(string $component, string $file, bool $versioning = true);
string getModuleAsset(string $file, string $module = null, bool $versioning = true);
string getThemeAsset(string $file, string $theme = null, bool $versioning = true);
string getSourcePath(string $component, string $file = '');
string versionStamp(string $path, string $url);
string string getCustomAsset(string $file, string $module = null, bool $versioning = true);
bool publishFile(string $sourceFile, string $targetFile, bool = $override = true);
bool publishAsset(string $component, string $file, bool $override = true);
bool publish(string $component, string $target = '', bool $override = true);
bool publishCustom(string $theme);
bool removeCustom(string $theme);
bool remove(string $component);
string getStaticPath(string $file);
string getStaticUrl(string $file, bool $versioning = true);
-
getBasePath() and getBaseUrl()
These two methods will return the path and url of
asset
folder respectively.echo Pi::service('asset')->getBasePath(); echo Pi::service('asset')->getBaseUrl();
The output will list as follows if Pi is installed in
D:/wamp/www
directory:'D:/wamp/www/Pi/www/asset' 'http://localhost/Pi/www/asset'
-
getPath() and getUrl()
These two methods are used to get the path and url of the component in
www/asset
directory.echo Pi::service('asset')->getPath('theme/default'); echo Pi::service('asset')->getUrl('module/system');
The output is:
'D:/wamp/www/Pi/www/asset/theme-default' 'http://localhost/Pi/www/asset/module-system'
-
getAssetPath() and getAssetUrl()
These two methods will return complete asset path and url of files. Their first parameter decide which path or url to choose, for example, a
module
string will returnurl/to/usr/
when usegetAssetUrl
.The
getAssetUrl()
method take a third parameter, which decide whether to append version information for url.echo Pi::service('asset')->getAssetPath('theme/default', 'image/logo.png'); echo Pi::service('asset')->getAssetUrl('theme/default', 'image/logo.png'); echo Pi::service('asset')->getAssetUrl('theme/default', 'image/logo.png', false);
Output:
'D:/wamp/www/Pi/www/asset/theme-default/image/logo.png' 'http://localhost/Pi/www/asset/theme-default/image/logo.png?1353312883' 'http://localhost/Pi/www/asset/theme-default/image/logo.png'
-
getSourcePath()
This method is used to return the full path of asset files, it takes two parameters, the first one decides which path to use to generate the final path, for example, a string
module
tells thatroot/path/usr/module
path will be use. The second parameter is the file name.echo Pi::service('asset')->getSourcePath('module/demo', 'image/logo.png');
Output:
'D:/wamp/www/Pi/usr/module/demo\asset\image/logo.png'
-
versionStamp()
This method is used to append version information behind given url, user must first check the enable checkbox in application's configuration to enable appending version.
The parameter
$path
is the full path of the file, the file's modify time of which will be detected as the file version. The parameter$url
is the file's url.$path = Pi::service('asset')->getAssetPath('theme/default', 'image/logo.png'); $url = Pi::service('asset')->getAssetUrl('theme/default', 'image/logo.png', false); echo Pi::service('asset')->versionStamp($path, $url);
Output:
'http://localhost/Pi/www/asset/theme-default/image/logo.png?1353312883'
-
getModuleAsset()
This method is used to get asset file in a module, the
$file
parameter is the file directory start from asset folder, themodule
parameter is the module name, and the$versioning
parameter decides whether to append version information.echo Pi::service('asset')->getModuleAsset('image/logo.png', 'demo', false);
Output:
'http://localhost/Pi/www/asset/module-demo/image/logo.png'
-
getThemeAsset()
This method is used to get asset file in a theme, the usage of this method is as same as that of
getModuleAsset()
. Its second parameter is the theme name.echo Pi::service('asset')->getThemeAsset('css/style.css', 'default', true);
Output:
'http://localhost/Pi/www/asset/theme-default/css/style.css?1353312883'
-
getCustomAsset()
This method is used to get the full path of custom asset. the usage of this method is as same as that of
getModuleAsset()
.echo Pi::service('asset')->getCustomAsset('script/test.css', 'demo', true);
Output:
'http://localhost/Pi/www/asset/custom-default/demo/script/test.css?1353404046'
-
publishFile()
This method is only to execute publish operation by given soure file path and target file path.
NOTE: the given file name must be absoute file path.
$sourePath = 'D:/wamp/www/trunk/usr/theme/demo/asset'; $targetPath = 'D:/wamp/www/trunk/www/asset/theme-channel'; Pi::service('asset')->publishFile($sourcePath, $targetPath);
-
publish()
This method is used to publish component assets folder. It will transfer the given folder name into absolute path first and then copy the folder into
www/asset
folder.Its first and second parameters are the source folder and target folder, respectively. And both of the parameter names must be consist of
type
andfolder name
. The third parameter tells whether to override existent folder.Pi::service('asset')->publish('module/demo'); Pi::service('asset')->publish('module/demo', 'module/demo');
This two line codes will publish the
asset
folder ofdemo
module into thewww/asset
folder and set the published folder name asmodule-demo
. -
publishAsset()
This method has the same function as
publish()
, the difference is thatpublishAsset()
function only applicable for direct copy but not for symbolic link. -
publishCustom()
Pi allows user to define custom module theme in theme package, the
publishCustom
method is used publish asset file to thewww/asset
folder as namecustom-{theme name}
.Pi::service('asset')->publishCustom('demo');
Then a package named
custom-demo
will be created. -
getStaticPath() and getStaticUrl()
These two methods are used to get the full static path and url of the given file, respectively. The
getStaticUrl()
method allows users to attach version information after url by setting the second parameter.echo Pi::service('asset')->getStaticPath('css/style.css'); echo Pi::service('asset')->getStaticUrl('js/eefocus/login.js', false); echo Pi::service('asset')->getStaticUrl('js/eefocus/login.js');
Output:
'D:/wamp/www/trunk/www/static\css/style.css' 'http://localhost/trunk/www/static/js/eefocus/login.js' 'http://localhost/trunk/www/static/js/eefocus/login.js?1354250463'
-
remove()
Remove component assets folder, the parameter passed should be consist of
type
andcomponent name
.Pi::service('asset')->remove('module/demo'); Pi::service('asset')->remove('theme/default');
-
removeCustom()
Remove custom assets in a theme, the parameter passed is theme name.
Pi::service('asset')->removeCustom('demo');
Pi/Application/Authentication
This class is used for user identity authentication. Its methods are list as:
Zend\Authentication\Result authenticate();
$this object setAdapter(Adapter $adapter);
getAdapter();
$this object setStorage(Storage $storage);
getStorage();
Boolean hasIdentity();
mixed|null getIdentity();
clearIdentity();
wakeup(string $identity = null);
-
authenticate() and wakeup()
The
authenticate()
method is used to authenticate user identity by passed identity and credential. Thewakeup()
method is used to wake up a user by passed identity.$identity = $post['identity']; $credential = $post['credential']; $result = Pi::service('authentication')->authenticate($identity, $credential); if (!$result->isValid()) { ... } Pi::service('authentication')->wakeup($identity);
-
hasIdentity() and getIdentity()
These two methods can be used to check and fetch the identity, for example:
if (Pi::service('authentication')->hasIdentity()) { ... $identity = Pi::service('authentication')->getIdentity(); }
-
setStorage() and getStorage()
Pi/Application/Audit
This class is used to output log message to a file.
void shutdown();
void attach(string $name, array|string|null $options);
bool write(string $name, array $messages);
void log(string $name, array|string $args);
-
log()
Usually we can just use this method to log message. For example:
Pi::service('audit')->log('test', array('val1', 'val2', 'val3'));
And we will get a file with these contents:
2013-06-07T11:02:22+08:00,val1,val2,val2
As we can see, each record contains two part: timestamp and messages. Timestamp format is acquiescently set to
date('c')
, and the messages are the seriation of all the values of the array we pass to as the second parameter. This log file actually is a CSV file, which means the fields are separated by a literal comma.Besides, The log file is under
Pi::path('log')
directory, the file name is 'test' which we pass to as the first parameter, and the file suffix is 'log' which is set by the class acquiescently. -
attach()
If we need to apply some custom configurations to the log, we may use this method.
Pi::service('audit')->attach('test', array( 'format' => "%time% name is %s, age is %s\n", 'file' => '/home/logs/hello.csv', 'timeformat' => 'M j H:i:s' )); Pi::service('audit')->log('test', array( 'name' => 'jiang', 'age' => 22, ));
Then the log displays like this:
Jun 7 12:06:51 name is jiang, age is 22
We can only set three attributes to a log file: message format, file position and name, and time format. Put '%time%' in where we want display the current time.
-
write()
This method is used to log several messages at once. The usage and output is just like
log()
method. But pay attention to the second parameter. It should be a two-dimensional array, each sub array should contain two part: timestamp and a array of messages. For example:Pi::service('audit')->write('testWrite', array( array( time(), array('val1'), ), array( time(), array('val2'), ) ));
We will get two records:
2013-06-07T15:14:24+08:00,val1 2013-06-07T15:14:24+08:00,val2
-
shutdown()
Pi/Application/Cache
Sometimes users may frequently access a same table to get needed data, these operation will takes a lot of time and make the request slow down, one of the most usual method is to write the data into cache, users can fetch the data without accessing database. This class helps user to operate cache easily.
AbstractAdapter storage();
AbstractAdapter loadStorage(array|string $config = array());
Cache setNamespace(string $namespace = '', AbstractAdapter $storage = null);
string getNamespace(string $namespace = '');
Cache clearByNamespace(string $namespace = '', AbstractAdapter $storage = null);
Cache setItem(string $key, mixed $value, string|array $options = array(), AbstractAdapter $storage = null);
mixed getItem(string $key, string|array $options = null, AbstractAdapter $storage = null);
Cache removeItem(string $key, string|array $options = null, AbstractAdapter $storage = null);
-
storage()
Get cache storage, instantiate a new one if it not exist yet.
$storage = Pi::service('cache')->storage();
-
loadStorage()
This method is used to load cache storage according to given parameters. The passed parameter can be string, which indicates the cache type, such as
apc
,filesystem
ormemcached
, or array include cache configuration. Users can refer tovar/config/cache.apc.php
to learn to the array structure of configuration.This method will load the cache adapter handler and plugin handler set in the configuration array.
// load apc adapter if cache.apc.php file is exists Pi::service('cache')->loadStorage('apc'); // load apc adapter by given cofiguration array $config = array( 'adapter' => array( 'name' => 'apc', 'options' => array( 'namespace' => 'apc', ), 'plugins' => array( 'exception_handler' => array('throw_exceptions' => false), ), ); Pi::service('cache')->loadStorage($config);
The code above will return
Zend\Cache\Storage\Adapter\Apc
handler that contain aZend\Cache\Storage\Plugin\ExceptionHandler
plugin handler. -
setNamespace()
Set namespace to current cache storage adapter. The second parameter
$storage
indicate the namespace of which cache handler to set.// Set namespace of current storage Pi::service('cache')->setNamespace('apc'); // Set namespace of 'filesystem' storage $storage = Pi::service('cache')->loadStorage('filesystem'); Pi::service('cache')->('filesystem', $storage);
-
getNamespace()
Get canonized namespace by prepending Pi identifier. If the given parameter is null, return the Pi identifier only.
echo Pi::service('cache')->getNamespace(); echo Pi::service('cache')->getNamespace('test');
If the value of identifier is set to
xob3ca
in thevar/config/engine.php
, the output are:'xob3ca' 'xob3ca_test'
-
clearByNamespace()
Clear cache by namespace, the second parameter will decide which storage to clear, if it is not set, the current storage will be clear.
Pi::service('cache')->clearByNamespace('apc');
-
setItem()
This method is used to set items into storage by namespace. The third parameter is used to decide the namespace and the time length to store the item. Its fouth parameter decide the storage to use.
Pi::service('cache')->setItem('test', 'hello world', 'apc'); Pi::service('cache')->setItem('test', array('hello world'), array('namespace' => 'apc', 'ttl' => 3600)); $storage = Pi::service('cache')->loadStorage('apc'); Pi::service('cache')->setItem('test', 'hello world', 'apc', $storage);
-
getItem()
Get items from storage by passed namespace.
$result = Pi::service('cache')->getItem('test', 'apc'); $storage = Pi::service('cache')->loadStorage('apc'); $result = Pi::service('cache')->getItem('test', array('namespace' => 'apc'), $storage);
-
removeItem()
Remove items from storage by namespace.
Pi::service('cache')->getItem('test', 'apc'); $storage = Pi::service('cache')->loadStorage('apc'); Pi::service('cache')->getItem('test', array('namespace' => 'apc'), $storage);
Pi/Application/Service/Captcha
This class mainly used to operate captcha. The methods are list as follows:
AdapterInterface load(string $type = null, array $options = array());
-
load()
This method is used to load a captcha adapter, it takes two parameters, the first one is the type of captcha, it decides which handler to get. The second parameter is optional, and is used as parameter for constructing an object.
Pi::service('captcha')->load('image')->generate();
Pi/Application/Service/Database
This class is used to operate database, it mainly load a database handler to operate with database.
Pi\Application\Db db($options = array());
Pi\Application\Db loadDb($option = array());
-
db()
This method mainly return a
Pi\Application\Db
handler for user to operate tables.echo Pi::service('database')->db()->prefix('login', 'system');
If the prefix of Pi database is
xe
, this code will return:'xe_system_login'
Pi/Application/Service/I18n
The default language of Pi is english, but some users of non-english countries may have difficult to use this application or show their product to their local users. The I18n
class provides developers some method to translate language.
Methods provider by this class are:
Translator getTranslator();
I18n setTranslator(Translator $translator);
I18n setLocale(string $locale);
string getLocale();
I18n load(array|string $domain, string|null $locale = null);
I18n loadModule(string $domain, string $module = null, string $locale = null);
I18n loadTheme(string $domain, string $theme = null, $locale = null);
string getPath(array|string $domain = '', string $locale = null);
Translator translator(string $domain = '', string|null $locale = null);
string translate(string $message, $domain = null, string $locale = null);
-
setTranslator()
Set translator with current locale.
Pi::service('i18n')->setTranslator(new \Pi\I18n\Translator\Translator);
-
getTranslator()
Get translator, and instantiate one if it is not avaliable.
$translator = Pi::service('i18n')->getTranslator(); $translator = Pi::service('i18n')->translator;
-
setLocale() and getLocale()
Operating locale of application, the locale is a string of language name, such as
en
,zh-CN
. ThesetLocale
method will also configure the translator locale.Pi::service('i18n')->setLocale('en'); $locale = Pi::service('i18n')->getLocale(); $locale = Pi::service('i18n')->locale;
Output:
'en'
- getPath()
This method is used to get resource folder path by passed parameters, its parameter should contain data of component, file name or locale.
User can use array to pass component and file data as well as string. In the array, its first value indicates component and its second value indicates file name. In the string, component and file name are connected by character
':'
, theusr
component will be used if only file name data is set (mean not use : in string).echo Pi::service('i18n')->getPath(array('module/demo')); echo Pi::service('i18n')->getPath(array('module/demo', 'block'), 'zh-CN'); echo Pi::service('i18n')->getPath(array('usr', 'mail/template'), 'en'); echo Pi::service('i18n')->getPath('date'); echo Pi::service('i18n')->getPath('module/demo:block');
Output following data if system locale is
'en'
:'D:/wamp/www/trunk/usr/module/demo/locale/en' 'D:/wamp/www/trunk/usr/module/demo/locale/zh-CN/block' 'D:/wamp/www/trunk/usr/locale/en/mail/template' 'D:/wamp/www/trunk/usr/locale/zh-CN/date' 'D:/wamp/www/trunk/usr/module/demo/locale/zh-CN/block'
- load()
Load translation resource and existent data will be flushed. By using this method, translation data will be load for later using.
Its first parameter can be array or string which contain component and file data of the translation file. And the second parameter indicates the locale name.
For example, if the passed parameter is an array, such as
array($v1, $v2)
, then the parameter$v1
indicate the component, and the parameter$v2
is the translation file name, likeblock.csv
if$v2 = block
. (Refer togetPath()
method)The third parameter of
load()
method indicates translation file of which folder will be loaded, for example, value'en'
tells that files inlocale/en
folder will be loaded.Pi::service('i18n')->load(array('theme/defalut', 'main'), 'en'); Pi::service('i18n')->load(array('lib/Pi/Captcha/Image')); Pi::service('i18n')->load('usr:date', 'en');
The following translation files will be load if the system locale is
en
:'D:/wamp/www/trunk/usr/theme/defalut/locale/en/main.csv' 'D:/wamp/www/trunk/lib/Pi/Captcha/Image/locale/zh-CN/main.csv' 'D:/wamp/www/trunk/usr/locale/en/date.csv'
- loadModule()
Load a module locale.
Pi::service('i18n')->loadModule('block'); Pi::service('i18n')->loadModule('block', 'demo', 'en');
- loadTheme()
Load a theme resource.
Pi::service('i18n')->loadTheme('main', 'default', 'en');
- translator()
Clone a translator with specified domain and locale.
$translator = Pi::service('i18n')->translator('module/demo', 'en'); $translator = Pi::service('i18n')->translator('theme/default', 'zh-CN');
-
translate()
Translating a pass message.
// use default domain and locale Pi::translate('This is a demo'); // use module/demo domain and chinese Pi::translate('This is a demo', 'module/demo', 'zh-CN'); // use syntactic sugar to translate echo __('This is a demo'); echo __('This is a demo', 'module/demo', 'zh-CN'); _e('This is a demo');
Pi/Application/Service/Module
This class is used to operate module, such as getting module name and meta, etc.
Module object setModule(string $module);
string current();
string getMetaFile();
array createMeta();
Boolean init(boolean $force = false);
array|Boolean meta(string $module = null);
Boolean isActive(string $module);
array config(string $key = null, string $module = null);
array loadMeta(string $module, string $type = null);
string path(string $module);
string directory($module = null);
array content(array $variables, array $conditions);
-
current()
This method is used to get current active module, it will return the module name.
$module = Pi::service('module')->current(); echo $module;
If current module is
demo
, the output will be:'demo'
-
getMetaFile()
This method will return a meta file name which contains the active module meta data. Generally, the meta file is
module.meta.php
. -
createMeta()
This method will write meta data fetching from DB into the meta file.
-
init()
This method is used to initialize the service, it will load all meta data from meta file.
-
meta()
This method is used to get module meta data.
if (Pi::service('module')->init(true)) { $meta = Pi::service('module')->meta('system'); }
The
$meta
variable is an array:array( 'directory' => 'system', 'active' => '1', )
-
isActive()
This method will check whether a module is active.
-
config()
This method will fetch configuration data from application's
config
table according to its parameters.The
$module
parameter of this method indicates the module name, the system configuration data will be returned if this parameter is not set.echo Pi::service('module')->config('sitename'); echo Pi::service('module')->config('author', 'user');
The first line will output:
'Web Application'
-
loadMeta()
This method will load
meta
data in themodule.php
of a module according to its parameter. If thetype
parameter is not set, all data will be returned.Pi::service('module')->loadMeta('user'); Pi::service('module')->loadMeta('user', 'meta');
-
path()
This method is used to get path of a module.
Pi/Application/Service/Registry
This class mainly provides users a handler point to Pi/Application/Registry
directory.
For example:
Pi::service('registry')->config;
This code will return a Pi\Application\Registry\Config
handler, then you can use the handler to call its methods.
You can also use a method directly, the following two line has similar results:
Pi::service('registry')->config->read('system', 'general');
Pi::service('registry')->config('read', 'system', 'general');
**Pi/Application/Service/Session`
This class contains a magic method __get()
, it will return a Zend\Session\Container
handler, then you can use this handler to operate sessions.
For example:
$session = Pi::service('session')->session;
Now you can set sessions:
$session->offsetSet('email', $email);
Pi::service('session')->email = $email;
Checking whether key exists:
$session->offsetExists('email');
Getting value by key:
$email = $session->offsetGet('email');
$email = Pi::service('session')->email;
Getting container name:
echo $session->getName();
The output of this code will be:
'session'
It also allows you to get a session manager for more operations, a getManager()
method can be used to achieve it:
$sessionManager = Pi::sevice('session')->session->getManager();
It may return a Zend\Session\SessionManager
handler:
$sessionManager->setSessionCookieLifetime(30);
Pi/Application/Service/Taxonomy
This service class is mainly for user to manage global taxonomy, a table prepended with system prefix will be created to store data.
Methods for user to use are list as follows:
bool add(array $taxonData, string $domainName = null);
Model|false get(string $domainName = 'taxon');
bool truncate(string $domainName = null);
bool delete(string $domainName = null);
bool update(array $taxonData, string $domainName = null);
array|false getTree(string $domainName = null, array $cols = array());
array|false getList(string $domainName = null, array $cols = array());
int addDomain(array $domainData, array|false $taxonData = array());
int updateDomain(array $domainData, array|false $taxonData = false);
array|false getDomain(int|string $entity);
bool deleteDomain(int|string $entity, $deleteTaxa = true);
-
add()
Add taxonomy data to special domain according to passed parameter if the table for taxonomy is not exists.
The data to insert into table are assign to an array, which also should the relationship of each data, and the
$domainName
parameter decides the table name to create.$data = array(); $result = Pi::service('taxonomy')->add($data, 'demo');
-
get()
Get taxonomy database model by the given taxonomy domain. This method will return a nested set model which we will introduce at the
Pi::model
section, and users could use the model object to operate the taxonomy table.$demoModel = Pi::service('taxonomy')->get('demo'); $taxonModel = Pi::service('taxonomy')->get();
-
truncate()
Empty taxon data model by given taxonomy domain.
$result = Pi::service('taxonomy')->truncate('demo');
-
delete()
Delete taxon data table by given taxonomy domain. This method will not drop the relating domain data in
taxonomy_domain
table.$result = Pi::service('taxonomy')->delete('demo');
-
update()
Update taxonomy data for a domain.
$data = array(); $result = Pi::service('taxonomy')->update($data, 'demo');
-
getTree()
Get nested taxonomy data by passed domain parameter. The second parameter of this method shows the fields to fetch.
$rows = Pi::service('taxonomy')->getTree('demo', array('id', 'name'));
The
$rows
variable has a structure like this:Array ( [3] => Array ( [id] => 3 [name] => root [left] => 1 [right] => 8 [child] => Array ( [4] => Array ( ... ) ... ) ) )
NOTE: the
id
field is required if the second parameter is set. -
getList()
Get adjacency list of taxon data according to passed domain data. Its second parameter shows fields to fetch.
$rows = Pi::service('taxonomy')->getList('demo', array('id', 'name'));
-
addDomain()
Add a taxonomy domain and its taxonomy data if provided.
Its first parameter is an array, which contains domain data and will be inserted into
taxonomy_domain
table. The second parameter decide whether to create a table and add data.$domain = array( 'name' => 'demo', 'title' => 'Demo taxonomy', 'description' => 'Creating a global taxonomy for demo module', 'module' => 'demo', ); // Only add a domain data $result = Pi::service('taxonomy')->addDomain($domain, false); // Add a domain, and add a empty table for storing taxonomy data $result = Pi::service('taxonomy')->addDomain($domain); $result = Pi::service('taxonomy')->addDomain($domain, array()); // Add a domain as well as a table, and insert taxonomy data into table $data = array(); $result = Pi::service('taxonomy')->addDomain($domain, array());
-
updateDomain()
Update a taxonomy domain, and update its taxonomy data if provided.
// Only update domain $result = Pi::service('taxonomy')->updateDomain($domain, false); // Update domain and its taxonomy data $data = array(...); $result = Pi::service('taxonomy')->updateDomain($domain, $data);
-
getDomain()
Get a taxonomy domain by using id or unique name.
$result = Pi::service('taxonomy')->getDomain(1); $result = Pi::service('taxonomy')->getDomain('demo');
-
deleteDomain()
Delete a taxonomy domain, and delete its taxonomy table if the second parameter set to true, or not set.
// delete domain as well as taxonomy table $result = Pi::service('taxonomy')->deleteDomain(1); // only delete domain $result = Pi::service('taxonomy')->deleteDomain('demo', false);
Pi/Application/Service/Theme
This class is used to operate with theme.
Theme setTheme(string $theme);
string current();
array loadConfig(string $theme);
string path(string $theme);
-
current()
This method will return the current theme name.
-
loadConfig()
This method is used to load theme configuration data from the
config.php
of theme package.Pi::service('theme')->loadConfig('default');
Pi\Application\Engine\AbstractEngine engine(string $type, array $config = array())
This method mainly used to initilize the Pi application.
Parameters
type
Application type, this parameter decides which handler to return.
config
Configuration data used for constructing object.
Return values
This method will return a handler according to its type
parameter, for example, a root
type will return a Pi\Application\Engine\Root
handler. If the type
is set to ''
, it will return Pi\Application\Engine\Standard
as default.
If you want to get a handler of root class in Pi\application\engine
directory, you can use:
$root = Pi::engine('root');
If you want to load and boot the application, using the following code:
Pi::engine()->run();
Pi/Application/Engine/Admin
This class inherits from standard
class, and it achieve tasks of loading configs, default listeners, module manager, bootstrap, application and running application.
mixed loadResource(string $resource, array $options = array());
-
loadResource()
This method is used to load resources according to its parameter. It will get a handler of the class in
Pi\Application\Resource
directory by setting the$resource
parameter. Then theboot()
method of the class will be called.Pi::engine('admin')->loadResource('acl');
mixed registry(string $index, mixed $value = null)
This method is used to registry container for global variables.
Parameters
index
The location to store the value, if value is not set, to load the value.
value
The object to store.
Return value
Return void
if the $value
parameter is set, or else return a mixed result according to the $index
parameter.
void log(string $message, array|Traversable $extra = array())
This method will output a log audit message in the debug block for user to view or debug.
Parameters
message
Log message.
extra
Extra message such as time. If it is not set, the application will get current time automatically.
Example
Pi::log('Audit test in shortcut way.');
Output:
03:59:10.317
[audit]
Audit test in shortcut way.
The above code will have the same effect with the following code:
Pi::service('log')->audit('Audit test in shortcut way.');
Pi\Application\Model\ModelAbstract model(string $name, string $module)
This method is used to get a handler relates to the table indicated by passed name parameter.
Parameters
name
Name of table, this parameter has a format such as {module name}/{table name}
, the module name can be ignored if you want to operate the system table. If you want to operate a module table, this parameter can be ignored, but you must set the $module
parameter.
module
Module name, optional.
The following two line will operate the same table:
$model = Pi::model('login/user');
$model = Pi::model('user', 'login');
If the table prefix is xe
, these codes will operate the table xe_login_user
.
The following code will operate the table xe_core_config
:
$model = Pi::model('config');
Please refer to database
for more information on how to operate with database.
The Nested Set Model
Generally, most users may encounter with hierarchical data in SQL database. A nested set model is a type of hierarchical data, in a nested set model, it uses left
, right
and depth
three fields to describe this model. You can refer to this
article for more knowledge of nested set model: Managing Hierarchical Data in MySQL <http://web.archive.org/web/20110606032941/http://dev.mysql.com/tech-resources/articles/hierarchical-data.html>
_.
The figure of the nested set model is:
.. image:: image/nest1.png
It also can use tree to describe:
.. image:: image/nest2.png
Therefore, you at least should include three field left
, right
and depth
in your table. Pi provides us a class named AbstractNest
to operate nest model database, the method in this class are list as:
void trim(int $start = 1, bool $leftVerified = false);
mixed add(array $data, mixed $objective = null, string $position = 'lastOf');
mixed remove(mixed $objective, bool $recursive = false);
bool move(mixed $objective, int $reference = null, string $position = 'lastof');
array getPosition(mixed $objective = null, string $position = 'lastOf')
int getDepth(mixed $objective);
Rowset getRoots(Where $where = null);
mixed getAncestors(mixed $objective, array $cols = null);
mixed getChildren(mixed $objective, array $cols);
1. Creating database for nested set model
A table is the basic requirement if you want to operate nested set model, then you should at least define three field named left
, right
, and depth
, the code to create table is list as follows:
CREATE TABLE `{table name}` (
`id` int(10) unsigned NOT NULL auto_increment,
`left` int(10) unsigned NOT NULL default '0',
`right` int(10) unsigned NOT NULL default '0',
`depth` smallint(3) unsigned NOT NULL default '0',
// add your own fields
PRIMARY KEY (`id`)
);
2. Creating a class inherit from Nest class
A Nest
class include methods to operate nested database, but it also need a handler which include the table information, therefore, it is necessary to creating a class inherits from Nest
class. You should follow three steps as follows:
- Creating a
Model
folder in themodule/{module name}/src/
folder; - Creating a PHP file to add a class, the file name should as same as the table name, and its first letter is uppercase;
- Setting the class's namespace, and let the class inherits from the
Nest
class.
For example:
namespace Module\Login\Model;
use Pi;
use Pi\Application\Model\Nest;
use Pi\Db\RowGateway\Node;
class Items extends Nest
{
}
3. Adding node in controller
In controller you should create an instance includes table information, by using the Pi::model()
API, you can initialize the class create in Model
folder, then you can call methods define in AbstractNest
class:
$modelItems = $this->getModel('items');
$resource = array(
'id' => null,
'name' => 'electronic',
);
$resourceId = $modelItems->add($resource);
- trim()
This method is used to strip empty positions starting from a specific position, it takes two parameters, the first one describes the start position and the second parameter tells to detect empty position on left side if it set to false.
- add()
This method is used to add a leaf node for nest set, its first parameter is an array type, it include data to insert into database; the second parameter is the target node ID or node, if you want to set root node, set this parameter to null
; the third parameter decides which position to insert, its value can be firstOf
, lastOf
, nextTo
and previousTo
.
$modelItems = $this->getModel('items');
// Adding a root node
$modelItems->add(array('id' => null, 'name' => 'root'));
// Adding a child node for 'root' by parent source
$parent = $modelItems->select(array('name' => 'root'))->current();
$itemsId = $modelItems->add($resource, $parent);
// Adding a child node for 'root' by parent ID
$parent = $modelItems->select(array('name' => 'root'))->current()->toArray();
$parentId = $parent['id'];
$modelItems->add(array('id' => null, 'name' => 'child-leaf'), $parentId);
- remove()
This method is used to remove a node by passed parameter. Its second parameter decides whether to delete all children nodes. It will return node deleted.
// Removing node including children by node resource
$deleteItem = $modelItems->select($where)->current();
$rowset = $modelItems->remove($deleteItem, true);
// Removing node only by node Id
$deleteItem = $modelItems->select($where)->current()->toArray();
$rowset = $modelItems->remove($deleteItem['id']);
- move()
This method is used to move a node to an indicated position, its second parameter describes the reference node.
$sourceNode = $modelItems->select($where);
$referenceNode = $modelItems->select($referWhere);
$modelItems->move($sourceNode, $referenceNode, 'firstOf');
- getDepth()
This method is used to calculate depth for a node.
// Getting depth by ID
$currentNode = $modelItems->select(array('name' => 'root'))->current()->toArray();
$test = $modelItems->getDepth($currentNode['id']);
// Getting depth by node resource
$currentNode = $modelItems->select(array('name' => 'root'))->current();
$test = $modelItems->getDepth($currentNode);
- getRoots()
This method is used to get root nodes by passing condition.
$root = getRoots(array('name' => 'cd'))->toArray();
- getAncestors()
This method is used to get all the ancestor nodes of current node. The second parameter decide which columns to fetch.
$currentNode = $modelItems->select(array('name' => '111'))->current();
$rowset = $modelItems->getAncestors($currentNode)->toArray();
$rowset = $modelItems->getAncestors($currentNode, array('name', 'title'))->toArray();
- getChildren()
This method is used to get all the children nodes of current node, its second parameter is also used to decide the columns to fetch.
$rowset = $modelItems->getChildren($currentNode)->toArray();
$rowset = $modelItems->getChildren($currentNode, array('name', 'title'));
Pi\Application\Db db()
This method is used to load a database identifier.
Return value
It will return a Pi\Application\Db
handler.
For example:
echo Pi::db()->prefix('user', 'login');
If the prefix is xe
, it will output:
'xe_login_user'
d()
d(mixed $data = '')
This method is used to display a debug message.
data
A variable or an object.
For example:
d('Hello');
Output:
[06:20:26.671 D:\wamp\www\Pi\usr\module\login\src\Controller\Admin\IndexController.php:39]
Hello
b()
This method displays backtrace messages.
b();
Parts of messages will be:
Backtrace at: 1344320700.7049
D:\wamp\www\Pi\www\admin.php(22): include()
D:\wamp\www\Pi\www\boot.php(34): Pi::boot()
D:\wamp\www\Pi\lib\Pi.php(293): Pi\Application\Engine\Standard::run()
D:\wamp\www\Pi\lib\Pi\Application\Engine\Standard.php(68): Zend\Mvc\Application::run()
...
dc()
dc(mixed $data)
This method is used to display a debug message during conditional debug. It should call denable()
method first to enable output.
data
Data to output, can be string, array or object.
For example:
// No output
dc(array('name', 'age'));
// No output
denable(false);
dc(array('name', 'age'));
// Output message
denable(true);
dc(array('name', 'age'));
Output:
[06:52:12.113 D:\wamp\www\Pi\usr\module\login\src\Controller\Admin\IndexController.php:40]
Conditional debug enabled
06:52:12.1131 D:\wamp\www\Pi\usr\module\login\src\Controller\Admin\IndexController.php:41
Array
(
[0] => name
[1] => age
)
string path(string $url)
Parameters
url
Deciding which path to fetch.
Return values
Return a path string. If url parameter is not equal to existed folder name, it will return the path begin with www
directory of Pi.
For example, the vendor
folder is exists in current package, and image
is not exists:
echo Pi::path('vendor');
echo Pi::path('image');
Output:
'D:/wamp/www/Pi/lib/vendor'
'D:/wamp/www/Pi/www/image'
Actual the second path is not exists.
Here are some general paths:
Pi::path('usr');
Pi::path('var');
Pi::path('module');
Pi::path('theme');
Pi::path('upload');
Pi::path('asset');
Pi::path('static');
Pi::path('vendor');
Pi::path('config');
Pi::path('cache');
Pi::path('log');
string url(string $url, bool $absolute = false)
Parameters
url
The url name to convert.
absolute
Whether convert to full URI.
Return values
Return a url string.
For example:
echo Pi::url('www');
Output:
'http://localhost/Pi/www'
Here are some general url:
echo Pi::url('www');
echo Pi::url('upload');
echo Pi::url('asset');
echo Pi::url('static');