Templates ↑ top
The template system built into the framework utilizes PHP's output buffer functionality to capture and parse the content of a page, replace certain variables in a separate template file with that content, then render the results. This functionality is optional and will only be available if a template file is defined before the framework is called.
Example:$ob_template = file_get_contents('templates/main.tpl');
- Site Level ↑ top
The site level template is used to easily build sites with a global template. This type of template file requires the variables %TITLE% and %BODY%. (Optional variable is %HEAD%.)
- Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>%TITLE%</title> %HEAD% </head> <body> <h1>%TITLE%</h1> %BODY% </body> </html>
The %TITLE% and %BODY% variables will both be replaced by the contents of their similarly named HTML tags;
<title>and<body>. Likewise, the contents of the<head>tag (minus the<title>tag) will replace the %HEAD% variable.- Example:
<?php $ob_template = file_get_contents('templates/main.tpl'); require_once('scripts/framework.php'); ?> <html> <head> <title>Lorem ipsum</title> <link type="text/css" rel="stylesheet" href="style.css" /> </head> <body> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam sed nibh quis enim pellentesque porttitor. Aenean vel turpis. Nam blandit velit ut est. Integer non sem a neque mollis aliquet. Nam magna. Nullam interdum, augue ut semper dignissim, massa massa adipiscing nulla, volutpat rutrum nisl lacus ac erat.</p> </body> </html>- Element ↑ top
Element templates are for displaying multiple, similarly structured elements of data with repeating HTML in conjunction with
$Template->Parse();and$Template->Render();. The below example shows a template that will render the contents of<!--{header:start|end}-->first, followed by either<!--{data:start|end}-->or<!--{nodata:start|end}-->and ending with<!--{footer:start|end}-->.- Example:
<!--{header:start}--> <div> <!--{header:end}--> <!--{data:start}--> <div class="bookmark"> <h3><a href="%URL%">%DESCRIPTION%</a></h3> <span class="dim">to %TAG%</span> </div> <!--{data:end}--> <!--{nodata:start}--> <p>No bookmarks.</p> <!--{nodata:end}--> <!--{footer:start}--> </div> <!--{footer:end}-->The data passed along with this template defines wether or not the
<!--{data:start|end}-->or<!--{nodata:start|end}-->section of the template is used. Below is an example of data that can be passed along with element templates.- Example:
$data = array(); $data[] = array('url'=>'http://www.latherrinserepeat.org/', 'description'=>'Lather Rinse Repeat', 'tag'=>'blog'); $data[] = array('url'=>'http://www.jemjabella.co.uk/', 'description'=>'Jemjabella.co.uk', 'tag'=>'blog'); $data[] = array('url'=>'http://www.justinshattuck.com/', 'description'=>'Justin Shattuck', 'tag'=>'blog'); $data[] = array('url'=>'http://chunkysoup.net/', 'description'=>'ChunkySoup.net', 'tag'=>'blog'); $data[] = array('url'=>'http://ejohn.org/', 'description'=>'John Resig', 'tag'=>'blog'); echo $Template->Render('template.tpl', $data);Based on the number of arrays within $data (above), the contents of
<!--{data:start|end}-->will be repeated four separate times, each time replacing the variables with the array's keys and values. If the array passed was empty, then the contents of<!--{data:start|end}-->will be returned. If you require that certain variables be replaced within the<!--{header:start|end}-->or<!--{footer:start|end}-->section of the template, setup the data array like the below example.- Example:
$data = array(); $data['header'][] = array('var'=>'All your items (4)'); $data['data'][] = array('url'=>'http://www.latherrinserepeat.org/', 'description'=>'Lather Rinse Repeat', 'tag'=>'blog'); $data['data'][] = array('url'=>'http://www.jemjabella.co.uk/', 'description'=>'Jemjabella.co.uk', 'tag'=>'blog'); $data['data'][] = array('url'=>'http://www.justinshattuck.com/', 'description'=>'Justin Shattuck', 'tag'=>'blog'); $data['data'][] = array('url'=>'http://chunkysoup.net/', 'description'=>'ChunkySoup.net', 'tag'=>'blog'); $data['data'][] = array('url'=>'http://ejohn.org/', 'description'=>'John Resig', 'tag'=>'blog'); $data['footer'][] = array('var'=>'All your items (4)'); echo $Template->Render('template.tpl', $data);
Constants ↑ top
When setting preset values for constants, define them before calling the framework. If the constant already exists on framework load, the preexisting constant will take precedence over the default.
- error_log ↑ top
The default value of
error_logis false. This should remain false if you don't want errors to be logged. Replacing false with a file name will send all errors to that file.- It is good programming practice to check to see if a constant already exists.
- Example:
if (!defined('error_log')) { define('error_log', 'errors.log'); }- Example:
echo constant(error_log);
- error_reporting ↑ top
The default value of
error_reportingis false. This should remain false if you don't want errors to display.- It is good programming practice to check to see if a constant already exists.
- Example:
if (!defined('error_reporting')) { define('error_reporting', false); }- Example:
echo constant('error_reporting');- int_microtime ↑ top
The default value of
int_microtimeis the Unix timestamp (with microseconds) of the time your application starts (used withendtime()).- The preset value of this constant should not be changed!
- Example:
echo constant('int_microtime');- lnbr ↑ top
The default value of
lnbrisPHP_EOL. This built in PHP constant reflects the new-line character of the server.- It is good programming practice to check to see if a constant already exists.
- The other possible values of this constant \n, \r, or \r\n must be surrounded by double quotes.
- Example:
if (!defined('lnbr')) { define('lnbr', "\n"); }- Example:
echo constant('lnbr');- maxview ↑ top
The default value of
maxviewis 10. This should be changed to reflect the default number of viewable items in your application (used with$Database->Table()).- It is good programming practice to check to see if a constant already exists.
- Example:
if (!defined('maxview')) { define('maxview', 10); }- Example:
echo constant('maxview');- page ↑ top
The default value of
pageis the value of$_SERVER['SCRIPT_NAME']plus$_SERVER['PATH_INFO']if it exists.- The preset value of this constant should not be changed!
- Example:
echo constant('page');- script ↑ top
The default value of
scriptis the value of$_SERVER['REQUEST_URI']minus$_SERVER['PATH_INFO']if it exists and any GET data.- The preset value of this constant should not be changed!
- Example:
echo constant('script');- url ↑ top
The default value of
urlis the address of the page your are currently on.- The preset value of this constant should not be changed!
- Example:
echo constant('url');
Functions ↑ top
The majority of the functions included in this framework are to allow for use in both PHP5 and PHP4 as some functions were not available until specific versions of PHP5.
- array_clean(array $array [, string $method]); ↑ top
Cleans values of an array (recursively) by either trimming values or clearing empty
- Attributes:
$array - Array to be processed.
$method - Default value is null. Alternate value is 'empty'.
- Example:
$array1 = array('value1', 'value1', 'value2', ' value2 ', ''); print_array(array_clean($array1));- Result:
Array ( [0] => value1 [1] => value1 [2] => value2 [3] => value2 [4] => )- Example:
$array1 = array('value1', 'value1', 'value2', ' value2 ', ''); print_array(array_clean($array1, 'empty'));- Result:
Array ( [0] => value1 [1] => value1 [2] => value2 [3] => value2 )- array_move(array $array, integer $key, integer $offset); ↑ top
Used to easily move values of an array.
- Only variables can be passed by reference for the first attribute.
- Attributes:
$array - Array to be modified.
$key - The key of the array value you want to move.
$offset - The position you want to move the array value to.
- Example:
$array = array('value1', 'value2', 'value3', 'value4'); print_array(array_move($array, 1, 2));- Result:
Array ( [0] => value1 [1] => value3 [2] => value2 [3] => value4 )- array_sort(array $array [, int $flag]); ↑ top
Sorts and returns an array.
- Only variables can be passed by reference for the first attribute.
- Attributes:
$array - Array to be modified.
$flag - Default value is null. Alternate values areSORT_REGULAR,SORT_NUMERIC,SORT_STRING, andSORT_LOCALE_STRING. More info on functionsort()
- Example:
$array = array('value2', 'value3', 'value1', 'value4'); print_array(array_sort($array));- Result:
Array ( [0] => value1 [1] => value3 [2] => value2 [3] => value4 )- array_walk_recursive(array $array, function $func); ↑ top
Runs a function on each value of the array recursively.
- Only variables can be passed by reference for the first attribute.
- Attributes:
$array - Array to be modified.
$func - Function each value of the array will be passed through.
- Example:
function custom($key, $value) { return trim($value); } $array = array(' username', 'password'); print_array(array_walk_recursive($array, 'custom'));- Result:
Array ( [0] => username [1] => password )- check_referer(); ↑ top
Checks the current URL against the HTTP referer.
- Example:
if (!check_referer() && count($_POST)) { echo 'The HTTP referer is invalid.'; }- dir_get_contents([string $dir, string $filter, constant $sort]); ↑ top
Returns a multi-dimensional array of all the files and directories recursively in a specific directory.
- Attributes:
$dir - Directory to search.
$filter - Use a regular expression to filter the results of the search.
$sort - Direction to sort the file types. (SORT_ASCorSORT_DESC)- Example:
$photos = dir_get_contents('photos/', '/(\/$|\.(jpg|jpeg|gif|png)$)/', SORT_ASC);- endtime(); ↑ top
Outputs time elapsed since script started.
- Example:
echo 'Script took ' . round(endtime(), 3) . ' second(s) to run.';
- Result:
Script took 0.016 second(s) to run.
- error(string $text); ↑ top
Used by functions to output or log errors (based on the
error_reportinganderror_logconstants).- Attributes:
$text - Text to send to the error buffer.
- Example:
error('Error: This is a sample error');- Result:
<p><b>Error:</b> This is a sample error</p>
- fetch_remote_file(string $file); ↑ top
Retrieves the contents of a remote file. Alternative to using
file_get_contents()when allow_url_fopen is disabled.- Attributes:
$file - The remote file's URL.
- Example:
echo fetch_remote_file('http://www.google.com/favicon.ico');- field_type(string $table, string $field); ↑ top
Outputs the field type of the specified
$fieldwithin$table.- Attributes:
$table - The name of the table you are querying.
$field - The name of the field you are querying.
- Example:
echo field_type('bookmarks', 'url');- Result:
varchar
- file_put_contents(string $file [, string $contents, int $flag]); ↑ top
Writes contents to specified file. Use the constant
FILE_APPENDin the last attribute to append the contents to already existing files.- Attributes:
$file - File you want to put contents into to.
$contents - Contents to be put into file.
$flag - Default value is null. Alternate value isFILE_APPEND.
- Example:
file_put_contents('log.txt', 'This is a test', FILE_APPEND);- is_date(string $value); ↑ top
Validates a date. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_date('0000-00-00')?'Valid':'Invalid';- is_email(string $value); ↑ top
Validates an email. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_date('username@domain.com')?'Valid':'Invalid';- is_empty(string $value); ↑ top
Validates empty variables. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_empty('')?'Empty':'Not Empty';- is_number(string $value); ↑ top
Validates a number. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_number(10.1)?'Valid':'Invalid';
- is_simple(string $value); ↑ top
Validates a simple string. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_simple('value')?'Valid':'Invalid';- is_simple_alpha(string $value); ↑ top
Validates a simple alpha string. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_simple_alpha('just1value')?'Valid':'Invalid';- is_simple_number(string $value); ↑ top
Validates a simple number. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_simple_number(10)?'Valid':'Invalid';
- is_web_address(string $value); ↑ top
Validates a web address. Returns boolean.
- Attributes:
$value - String to validate.
- Example:
echo is_web_address('http://overseercms.com/')?'Valid':'Invalid';- mysql_fetch_results(string $query [, array $results]); ↑ top
Returns the results of a MySQL query as an array.
- Attributes:
$query - MySQL query.
$results - Array to be returned with appended results.
- Example:
print_array(mysql_query_select('SELECT `id`, `url` FROM `test`.`bookmarks` LIMIT 5'));
- Result:
Array ( [0] => Array ( [id] => 1 [url] => http://www.latherrinserepeat.org/ ) [1] => Array ( [id] => 2 [url] => http://www.boagworld.com/forum/ ) [2] => Array ( [id] => 3 [url] => http://www.dlanham.com/ ) [3] => Array ( [id] => 4 [url] => http://www.jemjabella.co.uk/ ) [4] => Array ( [id] => 5 [url] => http://www.stripegenerator.com/ ) )- path_info([integer $offset]); ↑ top
Outputs the different parts of the
$_SERVER['PATH_INFO']variable.- Attributes:
$offset - Key of the path_info variable to be returned.
- Example:
echo path_info(1); // URL: http://neo-geek.net/index.php/journal/1
- Result:
1
- primary_key(string $table); ↑ top
Outputs the primary key of the specified
$table.- Attributes:
$table - The name of the table you are querying.
- Example:
echo primary_key('bookmarks');- Result:
id
- print_array(array $array [, array $array2, ..., array $array10]); ↑ top
Used to output multiple arrays surrounded by a
<pre>tag.- Attributes:
You can pass any number of arrays through this function.
- Example:
print_array(array('value1', 'value2'), array('value3'));
- Result:
Array ( [0] => value1 [1] => value2 ) Array ( [0] => value3 )- sanitize_data(array $data); ↑ top
Cleans the data being passed for use in a MySQL query.
- Attributes:
$data - Array to be processed.
- Example:
sanitize_data($_POST);
- set_location(string $url); ↑ top
Changes the location of the page by use of the
header()function in PHP. This function checks for previously sent headers and exists the script directly after setting the location.- Attributes:
$url - URL to set the header location to.
- Example:
set_location('/admin.php/dashboard');- timeago(timestamp $timestamp); ↑ top
Returns the time passed in "n day(s) ago."
- Attributes:
$timestamp - Timestamp you want to find the time passed from.
- Example:
echo timeago($timestamp);
- Result:
3 days ago
- url_query(array $replacements, string $return); ↑ top
Allows for simple modification of the current addresses query variables.
- Attributes:
$replacements - Array of replacement query variables.
$return - Default value is 'string'. Alternate value is null which returns the query variables as an array.
- Example:
echo url_query(array('db_limit'=>'50'));- Result:
?db_limit=50
Classes ↑ top
- $Database->resource ↑ top
Used to store the database connect resource from
$DB->Connector$DB->resource.- Example:
$Database->resource = $DB->resource;
- $Database->results ↑ top
Automatically stores the results of
$Database->DatabaseList(),$Database->TableList()and$Database->Table().- Example:
print_array($Database->results);
- $Database->DatabaseList(); ↑ top
Returns an array of available databases.
- Example:
$DB->Connect('localhost', 'root', 'root', 'test'); print_array($Database->DatabaseList());- Result:
Array ( [0] => Array ( [database] => information_schema ) [1] => Array ( [database] => mysql ) [2] => Array ( [database] => neogeek ) [3] => Array ( [database] => test ) )- $Database->TableList(string $database); ↑ top
Returns an array of tables in a certain database.
- Attributes:
$database - Database you are connecting to.
- Example:
$DB->Connect('localhost', 'root', 'root', 'test'); print_array($Database->TableList('test'));- Result:
Array ( [0] => Array ( [table] => bookmarks ) [1] => Array ( [table] => bug_reports ) )- $Database->Table(string $database, string $table, [, string $fields, string $clause]); ↑ top
Returns an array of values in a table. Additional attributes allows for filtering of values.
- Attributes:
$database - The name of the database you are connecting to.
$table - The name of the table you are querying.
$fields (optional) - The fields (comma separated) that you would like returned.
$clause (optional) - A simple where clause allowing for narrowing of the results.
- Example:
$DB->Connect('localhost', 'root', 'root', 'test'); print_array($Database->Table('test', 'bookmarks', 'id, url', 'WHERE `tag` = "blog"'));- Result:
Array ( [0] => Array ( [id] => 1 [url] => http://www.latherrinserepeat.org/ ) [1] => Array ( [id] => 4 [url] => http://www.jemjabella.co.uk/ ) [2] => Array ( [id] => 36 [url] => http://www.justinshattuck.com/ ) [3] => Array ( [id] => 58 [url] => http://chunkysoup.net/ ) [4] => Array ( [id] => 60 [url] => http://ejohn.org/ ) )- $Database->Process(string $database, string $table, array $variables); ↑ top
Saves information to a specific table with varaibles passed through
$variablesas an array.- The $variables attribute must contain the primary key of the table being modified if processing an update. If not, the values will be added as a new database record.
- Attributes:
$database - The name of the database you are connecting to.
$table - The name of the table you are querying.
$variables - The values (including tables primary key) that you want to update.
- Example:
$DB->Connect('localhost', 'root', 'root', 'test'); $Database->Process('test', 'bookmarks', array('shared'=>'no'));- $DB->resource ↑ top
Used to store the database connect resource from
$DB->Connect.- Example:
$DB->resource =
$DB->Connect;- $DB->results ↑ top
Automatically stores the results of
$DB->Query().- Example:
print_array($DB->results);
- $DB->instances ↑ top
Stores the number of instances of both
$DB->Connectand$DB->Query.- Example:
echo '$DB->Connect was called ' . $DB->instances['connect'] . ' time(s).<br />'; echo '$DB->Query was called ' . $DB->instances['query'] . ' time(s).<br />';
- $DB->Connect(string $server, string $username, string $password [, string $database, boolean $cache]); ↑ top
Connects to a database with the specified information. Cache allows the connection to be stored for use with other functions such as
$DB->Query().- Attributes:
$server - The name or IP address of the server you are connecting to.
$database - The name of the database you are connecting to.
$username - The username you are connecting with.
$password - The password you are connecting with.
$table - The name of the table you are querying. Default value is null.
$cache - Boolean for storing the resource of this connect statement in the DB class. Default value is true. Can be accessed through the $DB->resouce variable.
- Example:
$DB->Connect('localhost', 'root', 'root', 'test');- $DB->Query(string $query [, resource $resource, string $return, boolean $cache]); ↑ top
Runs a query on the default (specified in
$DB->Connect) or alternate database. Returns an array of results by default. Alternate returns are a basic boolean or the MySQL resource.- The $return variable is array by default. Alternative values are resource and boolean.
- Attributes:
$query - MySQL query.
$resource - Use a specific$DB->Connectresource or the default one stored in the DB class.
$queryreturn - MySQL query.
$cache - Boolean for storing the results of this query in the DB class. Default value is true. Can be accessed through the $DB->results variable.
- Example:
$DB->Connect('localhost', 'root', 'root', 'test'); print_array($DB->Query('SELECT `id`, `url` FROM `test`.`bookmarks` LIMIT 5'));- Result:
Array ( [0] => Array ( [id] => 1 [url] => http://www.latherrinserepeat.org/ ) [1] => Array ( [id] => 2 [url] => http://www.boagworld.com/forum/ ) [2] => Array ( [id] => 3 [url] => http://www.dlanham.com/ ) [3] => Array ( [id] => 4 [url] => http://www.jemjabella.co.uk/ ) [4] => Array ( [id] => 5 [url] => http://www.stripegenerator.com/ ) )- $DB->Close([resource $resource]); ↑ top
Closed a MySQL connection created by
$DB->Connect()or a resource passed through function.- Attributes:
$resource - Use a specific
$DB->Connectresource or the default one stored in the DB class.
- Example:
$DB->Close();
- $GFX->Resize(string $image [, integer $width, integer $height, string $output]); ↑ top
Resizes and crops JPG, GIF, and PNG image files on the fly using the built in PHP GD library.
- This function requires the GD library in order to function correctly. Use the
gdinfo()function to see if the GD library is installed and what version the server is running. - Attributes:
$width - The width of the new resized image. Does not need to be proportional to the
$height.
$height - The height of the new resized image. Does not need to be proportional to the$width.
$output - The folder where the resized images will be stored. If this attribute contains a value, the function will return a URL to the resized image. If this attribute is left blank, the function will output the image. For this to work the function must be called on a page that doesn't output anything minus the result of this function.- Example:
$GFX->Resize('images/test.png', 100, 100, 'cache/');- $Template->tools ↑ top
Appends HTML content into columns at the end of rows generated by
$Template->Generate.- The below code must come before
$Template->Generate()and should be cleared before calling$Template->Generate()again if the same tools are not needed. - Example:
$Template->tools[] = array('View', '<a href="?p=view&id=%ID%">View</a>'); $Template->tools[] = array('Edit', '<a href="?p=edit&id=%ID%">Edit</a>'); $Template->tools[] = array('Delete', '<a href="?p=del&id=%ID%">Delete</a>');- Example:
$Template->tools = array();
- $Template->Parse(string $template); ↑ top
Parses template files/strings. Notice:
$Template->Render()automatically parses a template file passed through the first attribute.- Attributes:
$template - Template file or string to be parsed.
- Example:
print_array($Template->Parse('templates/custom/bookmarks.tpl'));
- Result:
Array ( [header] => <div> [data] => <div class="bookmark"> <h3><a href="%URL%">%DESCRIPTION%</a></h3> <span class="dim">to %TAG%</span> </div> [footer] => </div> )- $Template->Render(string $template [, array $data]); ↑ top
Renders a template based on data passed through the
$dataattribute.- Attributes:
$template - Template file or string to be parsed.
$data - Array of data to replace template specific variables in the$template. Can also specify header and footer specific arrays for replacement.
- Example:
$results = $DB->Query('SELECT `id`, `url` FROM `test`.`bookmarks`'); echo $Template->Render('templates/custom/bookmarks.tpl', $results);- Example:
$results['header'][0] = array('variable'=>'replacement'); $results['data'] = $DB->Query('SELECT `id`, `url` FROM `test`.`bookmarks`'); $results['footer'][0] = array('variable'=>'replacement'); echo $Template->Render('templates/custom/bookmarks.tpl', $results);- $Template->Generate(array $data [, boolean $sortable, boolean $render]); ↑ top
Similar to
$Template->Render(), but this function creates a tabulator template on the fly.- Attributes:
$data - Array of data to built template with and replace template specific variables in the
$templateif$renderis true. See$Template->Renderfor more info.
$sortable - Allow for manual sorting of table values.
$render - Render generated template with data supplied.
- Example:
$results = $DB->Query('SELECT `id`, `url` FROM `test`.`bookmarks`'); echo $Template->Generate($results, true, true);- You can add tools to the end of each generated row by adding an array (below) to
$Template->toolsbefore calling$Template->Generate(). - $Template->Pagination([number $total_rows, boolean $single_page_display]); ↑ top
Outputs pagination based on the number passed through
$total_rows.- The math behind the pagination relies on both the
maxviewconstant and the number passed through$total_rows. - Attributes:
$total_rows - Number of total rows to be paginated with.
$single_page_display - Boolean to show or hide pagination if there is only one page.
- Example:
$results = $DB->Query('SELECT `id`, `url` FROM `test`.`bookmarks`'); echo $Template->Pagination(count($results), false);- $Template->Form(string $database, string $table [, array $data, array $fields]); ↑ top
Creates a form based on the table specified. Optional predefined data and fields can also be passed through the function.
- Example:
echo $Template->Form('test', 'bookmarks');- Elements in the form output can easily be replaced by regular expressions (see below). An example of usage would be replacing an input box with a select box.
- Attributes:
$database - The name of the database you are connecting to.
$table - The name of the table you are building a form with.
$data - Predefined values for displayed fields.
$fields - An array which can allow for only certain fields to display.
- Example:
$output = $Template->Form('test', 'bookmarks'); $output = preg_replace('/(<label(.*)>)Url(:<\/label>)/U', '\1<acronym title="Uniform Resource Locator">URL</acronym>\3', $output); echo $output;- Example:
$output = $Template->Form('test', 'bookmarks'); $output = preg_replace('/<input name="active" (.*)\/>/U', $form_active_select, $output); echo $output;