cityphp 0.4.0 Manual

  1. Introduction
  2. Installation
  3. Loading Files
  4. Templates
  5. HTML Snippets
  6. Form Validation
  7. Database
  8. URL Routing
  9. Datetimes
  10. Reference

Introduction

cityphp is a full featured PHP 5.3.0+ web application library. It's a directory of PHP classes and functions. It has no dependencies. You can use it standalone to develop any web application. Or you can combine it with any other code. cityphp is PSR-1 compliant and it's available on composer.

The library contains facilities for SQL databases, form validation, HTML snippets, bcrypt hashing, token generation, pagination, URL routing and datetimes.

The cityphp source code is available on GitHub. All the code in this manual is available in the tests directory. For more example code see this site and vanilla.

Installation

To install cityphp, use composer. See the next section for an example.

Loading Files

To load files with cityphp use composer. Specify cityphp and your project package in composer.json. And then run composer install in the directory that contains composer.json. All the code in this manual uses the following composer.json:

{
    "require": {
        "cityphp/cityphp": "0.4.0"
    },
    "autoload": {
        "psr-0": {"purple\\": "src/"},
        "files": [
            "src/purple/thing.php",
            "src/purple/html/dummyForm.php",
            "src/purple/html/dummyForm2.php",
            "src/purple/html/myForm.php"
        ]
    }
}

Include the composer autoloader to use any class or function from cityphp or the project package. For example, if we have this function:

function thing() {
    return 'thing';
}

and this class:

namespace purple;
 
class Monster {
    public function talk() {
        return 'Me purple Monster';
    }
}

then we can access all our functions and classes via the composer autoloader:

//enable access to cityphp and project files
require 'vendor/autoload.php';
 
//use a function from cityphp
$token = sha1Token();
 
//use a class from cityphp
class Validator extends cityphp\forms\FormValidator {
    public function __construct() {
        parent::__construct(array(
            'username',
            'password'));
    }
}
 
$validator = new Validator();
 
//use a function from the project package
$thing = thing();
 
//use a class from the project package
$monster = new purple\Monster();
 
echo implode("<br/>\n", array(
    $token,
    print_r($validator->values(), true),
    $thing,
    $monster->talk()));

Templates

cityphp does not come with or use a specific template engine. You can use any template engine.

Here is one way to use plain PHP for a template engine. We'll use two concepts for this template engine: HTML document templates and PHP functions. The HTML document templates use only an HTML document and short tag echoed PHP variables. The PHP functions, or views, take data in via function parameters and return HTML.

Let's look at HTML document templates first. Here's template.php:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title><?=$title?></title>
    </head>
    <body><?=$content?></body>
</html>

Set the template variables before including the template:

$title = 'Page Title';
$content = 'page content';
 
include 'src/purple/html/template.php';

Use PHP functions to set template variables. For example, use blist() to set $content:

require 'vendor/autoload.php';
 
$title = 'Page Title';
$content = blist(array('one', 'two', 'three'));
 
include 'src/purple/html/template.php';

It's a common pattern to use one view function inside another. For example, we can write a dummyForm() that uses input():

function dummyForm() {
    return
        '<form method="post">'
 
        . input(array(
            'id' => 'input1'),
            'Input 1')
 
        . input(array(
            'type' => 'submit',
            'value' => 'Submit'))
 
        . '</form>';
}

Now use dummyForm() to set $content:

require 'vendor/autoload.php';
 
$title = 'Page Title';
$content = dummyForm();
 
include 'src/purple/html/template.php';

HTML Snippets

cityphp comes with PHP functions that return common HTML snippets. You can find descriptions, parameter explanations and example code for each HTML snippet function in the reference: input(), textarea(), select(), checkboxes(), radioButtons(), attributes(), blist() and autofocus().

Besides the info in the reference, there are a couple more things worth mentioning about HTML snippets. First, by default checkboxes and radio buttons display to the right of their label. If you want them to display to the left of their label, then use CSS. Let's do an example. Here's dummyForm2():

function dummyForm2() {
    return
        '<form method="post">'
 
        . input(array(
            'id' => 'input1',
            'type' => 'checkbox'),
            'Input 1')
 
        . input(array(
            'id' => 'input2',
            'type' => 'checkbox'),
            'Input 2')
 
        . checkboxes(
            array('a', 'b', 'c'),
            'input3',
            array(),
            'Input 3')
 
        . checkboxes(
            array('a', 'b', 'c'),
            'input4',
            array(),
            'Input 4')
 
        . input(array(
            'type' => 'submit',
            'value' => 'Submit'))
 
        . '</form>';
}

We need a more general template in order to load style sheets:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <?=$head?>
    </head>
    <body><?=$content?></body>
</html>

Here's the CSS to make the checkboxes display on the left:

/*container*/
#c_input2, #c_input4 div {
    unicode-bidi:embed;
    direction:rtl;
    text-align:left;
}
 
/*everything inside container*/
#c_input2 *, #c_input4 div * {
    unicode-bidi:embed;
    direction:ltr;
}

Display the form with the CSS applied:

require 'vendor/autoload.php';
 
$head = '<link rel="stylesheet" href="css/checkbox-align.css"/>';
$content = dummyForm2();
 
include 'src/purple/html/template2.php';

The other thing worth mentioning about HTML snippets is how to properly use autofocus(). It's important to put the autofocus snippet at the end of your HTML body. For example, our template would look like this:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <?=$head?>
    </head>
    <body>
        <?=$content?>
        <?=$autofocus?>
    </body>
</html>

Now we can autofocus the input in dummyForm():

require 'vendor/autoload.php';
 
$content = dummyForm();
$autofocus = autofocus('input1');
 
include 'src/purple/html/template3.php';

Form Validation

You can validate forms by extending FormValidator. Let's do an example. Here's our form view with three text inputs and some checkboxes:

function myForm(array $inputValues, $errors = array()) {
    return
        '<form method="post">'
 
        . blist($errors, array('style' => 'color:red;'))
 
        . input(array(
            'id' => 'input1',
            'value' => $inputValues['input1']),
            'Input 1')
 
        . input(array(
            'id' => 'input2',
            'value' => $inputValues['input2']),
            'Input 2')
 
        . input(array(
            'id' => 'input3',
            'value' => $inputValues['input3']),
            'Input 3')
 
        . checkboxes(
            array('pear', 'cookie', 'chips', 'shrimp', 'a drink', 'waffle'),
            'food',
            $inputValues['food'],
            'Food')
 
        . input(array(
            'type' => 'submit',
            'value' => 'Submit'))
 
        . '</form>';
}

Next create a form validator class. Here's what we need to do:

Here's the form validator:

namespace purple\forms;
 
use cityphp\forms\FormValidator;
 
class MyValidator extends FormValidator {
    public function __construct() {
        parent::__construct(
 
            //set the input names and default values
            //the first one is the same as 'input1' => ''
            array(
                'input1',
                'input2' => '',
                'input3' => 'default value',
                'food' => array()),
 
            //set the optional inputs
            array('food'));
    }
 
    protected function validate_input1($value) {
        if(!preg_match('/^[a-z0-9]{1,10}$/i', $value)) {
            return 'Input 1 must be 1-10 characters; letters and numbers only';
        }
    }
 
    protected function validate_input2($value) {
        if(strlen($value) < 6) {
            return 'Input 2 must be 6 or more characters';
        }
    }
 
    //input3 is always valid since there is no validate_input3()
 
    protected function validate_food($value) {
        if(count($value) != 4) {
            return 'Choose 4 foods';
        }
    }
 
    //perform more validation using any input value
    //if invalid, return an error message or an array of error messages
    protected function validateMore($values) {
        if($values['input2'] != $values['input3']) {
            return 'Inputs 2 and 3 must be the same';
        }
    }
}

There are two methods to call on form validator objects: values() and validate(). values() returns the default input values. validate() returns the submitted values and errors if all the required inputs were submitted, otherwise validate() returns null. Let's use the form validator:

require 'vendor/autoload.php';
 
$validator = new purple\forms\MyValidator();
 
if(list($inputValues, $errors) = $validator->validate()) {
    $content = $errors
        ? myForm($inputValues, $errors)
        : '<pre>' . print_r($inputValues, true) . '</pre>';
}
else {
    $content = myForm($validator->values());
    $autofocus = autofocus('input1');
}
 
include 'src/purple/html/template3.php';

By default a form validator will validate against $_POST. However, you can supply any data set using the third parameter of the FormValidator constructor. For example:

namespace purple\forms;
 
use cityphp\forms\FormValidator;
 
class MyValidator extends FormValidator {
    public function __construct() {
        parent::__construct(
            array(
                'input1',
                'input2',
                'input3',
                'food' => array()),
 
            array('food'),
 
            array(
                'input1' => 'aaaaaa',
                'input2' => 'bbbbbb',
                'input3' => 'bbbbbb',
                'food' => array(0, 1, 2, 3)));
    }
 
    ...
}

Database

The cityphp database system connects to SQL databases. There is support for MySQL, PostgreSQL and SQLite. There is a database handle class for each of these database vendors. There's also a higher level model factory structure.

First let's go over database handles and then we'll look at the model factory. Database handle instantiation connects to the database. A database handle constructor has the same parameters as the wrapped PHP database extension plus two additional parameters(an error message and a debug flag). These constructor signatures are in the reference: Mysql, Pgsql and Sqlite. You can call five methods on a database handle object: exec(), query(), esc(), conn() and error(). Let's write some example code to see how database handles work. For these examples we'll use MySQL(there are PostgreSQL and SQLite examples in the tests/ directory). We will use some constants in consts.php:

define('MYSQL_HOST', 'localhost');
define('MYSQL_USERNAME', 'ryry');
define('MYSQL_PASSWORD', 'ryry');
define('MYSQL_DBNAME', 'test2');
define('PGSQL_CONN_STRING', 'dbname=example2 user=postgres password=postgres');
define('SQLITE_FILENAME', 'mydb.db');
define('DB_DEBUG', true);
 
define('TABLE_EVENTS', 'events');
define('TABLE_WORDS', 'words');

You can use exec(), query() and esc() for almost all of your database tasks:

require 'const.php';
require 'vendor/autoload.php';
 
//connect to db
$db = new cityphp\db\Mysql(
    MYSQL_HOST,
    MYSQL_USERNAME,
    MYSQL_PASSWORD,
    MYSQL_DBNAME);
 
//exec() executes a result-less query
$db->exec('CREATE TABLE ' . TABLE_WORDS . ' (
    word_id INT AUTO_INCREMENT PRIMARY KEY,
    word VARCHAR(32))');
 
$db->exec(sprintf('INSERT INTO %s (word)
    VALUES("was"), ("jump"), ("hello")',
    TABLE_WORDS));
 
//escape strings with esc()
$db->exec(sprintf('INSERT INTO %s (word) VALUES("%s")',
    TABLE_WORDS,
    $db->esc('&><\/"')));
 
//query() returns a 2d array of results
var_dump($db->query('SELECT * FROM ' . TABLE_WORDS));

A database handle handles database errors for you. When a database error occurs the error message is displayed via die(). Set the error message using the constructor:

$db = new cityphp\db\Mysql(
    MYSQL_HOST,
    MYSQL_USERNAME,
    MYSQL_PASSWORD,
    MYSQL_DBNAME,
    null,
    null,
    'my database error');

If debug is true then the error message is the internal database error message:

$db = new cityphp\db\Mysql(
    MYSQL_HOST,
    MYSQL_USERNAME,
    MYSQL_PASSWORD,
    MYSQL_DBNAME,
    null,
    null,
    'my database error',
    DB_DEBUG);

You can use conn() to access the underlying database API. You must use error() with conn() where appropriate in order to keep the error handling mechanism consistent(error() is called for you in exec() and query()):

require 'const.php';
require 'vendor/autoload.php';
 
$db = new cityphp\db\Mysql(
    MYSQL_HOST,
    MYSQL_USERNAME,
    MYSQL_PASSWORD,
    MYSQL_DBNAME);
 
if($status = mysqli_stat($db->conn())) {
    echo $status;
}
else {
    $db->error();
}

Now that you understand database handle we can move on to the model factory. You should use the model factory almost all the time, as opposed to raw database handles like above. To create a model factory extend AdapterFactory and define a databaseHandle() method that returns a database handle:

namespace purple\db;
 
use cityphp\db\AdapterFactory;
use cityphp\db\Mysql;
 
class ModelFactory extends AdapterFactory {
    protected static function databaseHandle() {
 
        //all models share a single instance of this object
        return new Mysql(
            MYSQL_HOST,
            MYSQL_USERNAME,
            MYSQL_PASSWORD,
            MYSQL_DBNAME);
    }
}

Next, build a model class that extends DatabaseAdapter. In your model class write methods that call database handle methods via $this:

namespace purple\db;
 
use cityphp\db\DatabaseAdapter;
 
class WordModel extends DatabaseAdapter {
    public function install() {
        $this->exec('CREATE TABLE ' . TABLE_WORDS . ' (
            word_id INT AUTO_INCREMENT PRIMARY KEY,
            word VARCHAR(32))');
    }
 
    public function create(array $words) {
        if($words) {
            $this->exec(sprintf('INSERT INTO %s (word) VALUES("%s")',
                TABLE_WORDS,
                implode('"), ("', array_map(array($this, 'esc'), $words))));
        }
    }
 
    public function get() {
        return $this->query('SELECT * FROM ' . TABLE_WORDS);
    }
 
    public function update($from, $to) {
        $this->exec(sprintf('UPDATE %s SET word = "%s" WHERE word = "%s"',
            TABLE_WORDS,
            $this->esc($to),
            $this->esc($from)));
    }
 
    public function delete($word) {
        $this->exec(sprintf('DELETE FROM %s WHERE word = "%s"',
            TABLE_WORDS,
            $this->esc($word)));
    }
}

Get models from the model factory and call model methods:

require 'const.php';
require 'vendor/autoload.php';
 
use purple\db\ModelFactory;
 
//must pass full namespace to get()
$wordModel = ModelFactory::get('purple\db\WordModel');
 
$wordModel->install();
$wordModel->create(array('red', 'swim', 'apple', 'red'));
$wordModel->update('red', 'coal');
$wordModel->delete('swim');
 
var_dump($wordModel->get());

Use static variables in your model factory to control databaseHandle(). For example, use an $isJson to control the error message:

namespace purple\db;
 
use cityphp\db\AdapterFactory;
use cityphp\db\Mysql;
 
class ModelFactory2 extends AdapterFactory {
    public static $isJson;
 
    protected static function databaseHandle() {
        $errorMessage = self::$isJson
            ? json_encode(array(
                'success' => false,
                'payload' => 'database error'))
 
            : '<html><body>database error</body></html>';
 
        return new Mysql(
            MYSQL_HOST,
            MYSQL_USERNAME,
            MYSQL_PASSWORD,
            MYSQL_DBNAME,
            null,
            null,
            $errorMessage);
    }
}

Set $isJson and output JSON:

require 'const.php';
require 'vendor/autoload.php';
 
use purple\db\ModelFactory2;
 
header('Content-Type:application/json');
ModelFactory2::$isJson = true;
$wordModel = ModelFactory2::get('purple\db\WordModel');
 
$wordModel->install();
$wordModel->create(array('book', 'curtain', 'lawn'));
 
echo json_encode(array(
    'success' => true,
    'payload' => $wordModel->get()));

URL Routing

Routing executes one PHP script depending on a value. To do this we use route() and include. The default routing value is $_GET["r"]. Let's look at an example. First we need this template4.php:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title><?=$title?></title>
    </head>
    <body>
        <div><ul>
            <li><a href="test23-url-routing.php">Word List</a></li>
            <li><a href="test23-url-routing.php?r=add">Add Word</a></li>
            <li><a href="test23-url-routing.php?r=about">About</a></li>
        </ul></div>
        <div><?=$content?></div>
        <?=$autofocus?>
    </body>
</html>

Here's the front controller that calls route():

require 'const.php';
require 'vendor/autoload.php';
 
use purple\db\ModelFactory;
 
$wordModel = ModelFactory::get('purple\db\WordModel');
 
include 'src/purple/routes/' . route(array(
    null => 'word-list.php',
    'add' => 'add-word.php',
    'about' => 'about.php'));
 
include 'src/purple/html/template4.php';

All that's left are the three routes. Here's word-list.php:

$title = 'Word List';
$content = blist(
    array_map(
        function($word) {
            return htmlspecialchars($word['word']);
        },
        $wordModel->get()));

add-word.php:

$validator = new purple\forms\MyValidator();
 
if(list($inputValues, $errors) = $validator->validate()) {
    if($errors) {
        $content = myForm($inputValues, $errors);
    }
    else {
        $words = $inputValues;
        $words['food'] = implode('|', $words['food']);
        $wordModel->create($words);
        $content = 'Success. These words were added:'
            . implode(
                array_map(
                    function($word) {
                        return '<br/>' . htmlspecialchars($word);
                    },
                    $words));
    }
}
else {
    $content = myForm($validator->values());
    $autofocus = autofocus('input1');
}
 
$title = 'Add Word';

about.php:

$title = 'About';
$content = 'Routing test app for cityphp.';

Datetimes

You can use datetimeNow() and datetimeTo() as your datetime handling system. Use datetimeNow() to get the current UTC datetime. Use datetimeTo() to convert a UTC datetime to a time zone and date format. Daylight saving time and time zones will be correctly handled for you. You don't have to bother with PHP or database time zone settings. Let's do a datetime database example:

require 'const.php';
require 'vendor/autoload.php';
 
$db = new cityphp\db\Mysql(
    MYSQL_HOST,
    MYSQL_USERNAME,
    MYSQL_PASSWORD,
    MYSQL_DBNAME);
 
$db->exec('CREATE TABLE ' . TABLE_EVENTS . ' (
    name VARCHAR(32),
    time DATETIME)');
 
//use datetimeNow() to store the current time
$db->exec(sprintf('INSERT INTO %1$s (name, time) VALUES
    ("one", "%2$s"),
    ("two", "%2$s" - INTERVAL 2 MINUTE),
    ("three", "%2$s" - INTERVAL 2 DAY)',
    TABLE_EVENTS,
    datetimeNow()));
 
//use datetimeTo() to convert the stored time
echo implode('<br/>', array_map(
    function($event) {
        return sprintf('%s = %s',
            htmlspecialchars($event['name']),
            datetimeTo($event['time'], 'America/Los_Angeles', 'M j, Y g:ia'));
    },
    $db->query('SELECT * FROM ' . TABLE_EVENTS)));

Reference

The reference contains descriptions, parameter explanations and example code for cityphp functions and methods. There are the HTML snippet functions: input(), textarea(), select(), checkboxes(), radioButtons(), attributes(), blist() and autofocus(). The datetime functions: datetimeNow() and datetimeTo(). Some miscellaneous functions: bcryptHash(), clamp(), paginate(), route() and sha1Token(). And the database handle constructors: Mysql, Pgsql and Sqlite.

attributes

Description

string attributes ( array $attributes )

attributes() converts an array into tag attributes.

Parameters

attributes

An array of attributes. The array key is the attribute name and the array value is the attribute value. Empty string values will be ignored. If the array key is an integer then only the value will show. The attribute value is escaped. The attribute name is not escaped.

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode("\n\n", array(
    sprintf('<tag%s/>', attributes(array(
        'name1' => 'value1',
        'name2' => '"value2"',
        'value3'))),
 
    sprintf('<tag%s></tag>', attributes(array(
        'name1' => 'value1',
        'name2' => ''))),
 
    sprintf('<tag%s/>', attributes(array(
        '<value1>',
        false ? 'value2' : '',
        true ? 'value3' : '')))));
<tag name1="value1" name2="&quot;value2&quot;" value3/>
 
<tag name1="value1"></tag>
 
<tag &lt;value1&gt; value3/>

autofocus

Description

string autofocus ( string $id )

autofocus() returns JavaScript that calls focus() on an input id.

Parameters

id

The id of the input to call JavaScript focus() on. This value is not escaped.

Examples

Example #1
require 'vendor/autoload.php';
 
echo autofocus('input1');
<script>document.getElementById('input1').focus();</script>

bcryptHash

Description

string bcryptHash ( string $input, mixed $salt )

bcryptHash() returns a crypt() blowfish hash.

Parameters

input

The string to be hashed, for example a password.

salt

Either an integer cost value, or a previously obtained bcryptHash(). The cost value must be between 4-31 inclusive.

Examples

Example #1
require 'vendor/autoload.php';
 
$signUpPassword = 'password';
$loginPassword = 'password';
 
//store this value in a database
$signUpHash = bcryptHash($signUpPassword, 10);
 
//get hash using previous hash
$loginHash = bcryptHash($loginPassword, $signUpHash);
 
$correct = ($signUpHash == $loginHash);
 
echo implode("<br/>\n", array(
    '$signUpHash = ' . $signUpHash,
    '$loginHash = ' . $loginHash,
    '$correct = ' . var_export($correct, true)));
$signUpHash = $2a$10$KKzYp73JrogGWwCiR8tWF.j0QHtZbQ36oQfyCvYbffj8l6nkjkNEy<br/>
$loginHash = $2a$10$KKzYp73JrogGWwCiR8tWF.j0QHtZbQ36oQfyCvYbffj8l6nkjkNEy<br/>
$correct = true

blist

Description

string blist ( mixed $items , array $listAttributes = array() , bool $isOrdered = false )

blist() returns a single-level unordered or ordered HTML list.

Parameters

items

A single value or an array for the list items. If an array value is an array, then the array key will be the li content and the array value will be the li attributes. If an array value is not an array, then the array value will be the li content. The li content is not escaped.

listAttributes

An array of attributes for the ul or ol tag. These attributes will be displayed like in attributes().

isOrdered

true is ol and false is ul.

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode("\n\n", array(
    blist('jan'),
 
    blist(array('feb', 'mar', 'apr')),
 
    blist(array(
        'may' => array('style' => 'font-size:3em;'),
        'jun',
        'jul' => array('id' => 'last-item'))),
 
    blist(array('fall', 'winter', 'spring'),
        array('class' => 'seasons')),
 
    blist(array('castle', 'ship', 'forest'),
        array('type' => 'A'),
        true)));
<ul><li>jan</li></ul>
 
<ul><li>feb</li><li>mar</li><li>apr</li></ul>
 
<ul><li style="font-size:3em;">may</li><li>jun</li><li id="last-item">jul</li></ul>
 
<ul class="seasons"><li>fall</li><li>winter</li><li>spring</li></ul>
 
<ol type="A"><li>castle</li><li>ship</li><li>forest</li></ol>

checkboxes

Description

string checkboxes ( array $checkboxes , string $name , array $checkedValues = array() , string $title = "" , bool $isContainer = true , array $containerAttributes = array() )

checkboxes() returns a string that's a title span and a set of checkbox input()s wrapped in a div tag. The title span and container div are optional. You can set the container div attributes. All other attributes are set automatically(see the name parameter).

Parameters

checkboxes

An array representing the checkboxes. The array key is the checkbox value and the array value is the checkbox label.

name

The name to use for the checkbox inputs. Two other attributes will be set automatically using name:

checkedValues

An array for the values that are checked by default.

title

The title span content. If it's the empty string then there will be no span tag. This value is not escaped.

isContainer

If false then there will be no container div.

containerAttributes

An array of attributes for the container div tag. These attributes will be displayed like in attributes().

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode("\n\n", array(
    checkboxes(
        array('apple', 'pear', 'kiwi'),
        'fruit'),
 
    checkboxes(
        array(1 => 'html', 'css', 'php', 'c++'),
        'skills',
        array(1, 4),
        'Skills'),
 
    checkboxes(
        array('circle', 'square', 'triangle'),
        'shapes',
        array(),
        'Shapes',
        true,
        array('style' => 'color:green;'))));
<div id="c_fruit"><div id="c_fruit0"><label id="l_fruit0" for="fruit0">apple</label><input id="fruit0" name="fruit[]" type="checkbox" value="0"/></div><div id="c_fruit1"><label id="l_fruit1" for="fruit1">pear</label><input id="fruit1" name="fruit[]" type="checkbox" value="1"/></div><div id="c_fruit2"><label id="l_fruit2" for="fruit2">kiwi</label><input id="fruit2" name="fruit[]" type="checkbox" value="2"/></div></div>
 
<div id="c_skills"><span id="t_skills">Skills</span><div id="c_skills0"><label id="l_skills0" for="skills0">html</label><input id="skills0" name="skills[]" type="checkbox" value="1" checked/></div><div id="c_skills1"><label id="l_skills1" for="skills1">css</label><input id="skills1" name="skills[]" type="checkbox" value="2"/></div><div id="c_skills2"><label id="l_skills2" for="skills2">php</label><input id="skills2" name="skills[]" type="checkbox" value="3"/></div><div id="c_skills3"><label id="l_skills3" for="skills3">c++</label><input id="skills3" name="skills[]" type="checkbox" value="4" checked/></div></div>
 
<div style="color:green;" id="c_shapes"><span id="t_shapes">Shapes</span><div id="c_shapes0"><label id="l_shapes0" for="shapes0">circle</label><input id="shapes0" name="shapes[]" type="checkbox" value="0"/></div><div id="c_shapes1"><label id="l_shapes1" for="shapes1">square</label><input id="shapes1" name="shapes[]" type="checkbox" value="1"/></div><div id="c_shapes2"><label id="l_shapes2" for="shapes2">triangle</label><input id="shapes2" name="shapes[]" type="checkbox" value="2"/></div></div>

clamp

Description

mixed clamp ( mixed $value, mixed $min, mixed $max )

clamp() returns a value clamped to a range.

Parameters

value

The value to clamp.

min

The minimum allowed value.

max

The maximum allowed value.

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode(', ', array(
    clamp(5, 1, 10),
    clamp(0, 1, 10),
    clamp(11, 1, 10),
    clamp(11, 1, 10.4),
    clamp('d', 'c', 'f'),
    clamp('a', 'c', 'f'),
    clamp('i', 'c', 'f')));
5, 1, 10, 10.4, d, c, f

datetimeNow

Description

string datetimeNow ()

datetimeNow() returns the current UTC datetime in YYYY-MM-DD HH:MM:SS format.

Examples

Example #1
require 'vendor/autoload.php';
 
echo 'datetimeNow(): ' . datetimeNow();
datetimeNow(): 2013-12-05 10:48:53

datetimeTo

Description

string datetimeTo ( string $datetime, string $timezone, string $format )

datetimeTo() converts a UTC datetime to a time zone and date format.

Parameters

datatime

A UTC datetime string to convert.

timezone

The time zone to convert to.

format

The date format to use for the conversion.

Examples

Example #1
require 'vendor/autoload.php';
 
$utcNow = datetimeNow();
$laNow = datetimeTo($utcNow, 'America/Los_Angeles', 'M j, Y g:ia');
echo "utcNow = $utcNow, laNow = $laNow";
utcNow = 2013-12-06 04:52:07, laNow = Dec 5, 2013 8:52pm

input

Description

string input ( array $inputAttributes = array() , string $label = "" , bool $isContainer = true , array $labelAttributes = array() , array $containerAttributes = array() )

input() returns a string that's a label tag and an input tag wrapped in a div tag. The label and div tags are optional. You can set the label, input and div attributes. Some attributes are set automatically(see the inputAttributes parameter).

Parameters

inputAttributes

An array of attributes for the input tag. These attributes will be displayed like in attributes(). If the id key of this array is set, then the following four attributes will be set automatically:

label

The label text. If it's the empty string then there will be no label tag. This value is escaped.

isContainer

If false then there will be no container div.

labelAttributes

An array of attributes for the label tag. These attributes will be displayed like in attributes().

containerAttributes

An array of attributes for the container div tag. These attributes will be displayed like in attributes().

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode("\n\n", array(
    input(),
 
    input(array('id' => 'username')),
 
    input(array('id' => 'email'), 'Email'),
 
    input(
        array('id' => 'city'),
        'City',
        false,
        array('style' => 'color:pink;')),
 
    input(
        array('name' => 'zip'),
        'Zip Code',
        true,
        array('style' => 'color:pink;'),
        array(
            'style' => 'background:#000000;',
            'onclick' => 'alert("container");'))));
<div><input/></div>
 
<div id="c_username"><input id="username" name="username"/></div>
 
<div id="c_email"><label id="l_email" for="email">Email</label><input id="email" name="email"/></div>
 
<label style="color:pink;" id="l_city" for="city">City</label><input id="city" name="city"/>
 
<div style="background:#000000;" onclick="alert(&quot;container&quot;);"><label style="color:pink;">Zip Code</label><input name="zip"/></div>

paginate

Description

array paginate ( int $numItems, int $itemsPerPage, int $currentPageNum )

paginate() returns the number of pages and the clamped current page number.

Parameters

numItems

Total number of items to paginate.

itemsPerPage

The number of items per page.

currentPageNum

The raw current page number.

Examples

Example #1
require 'vendor/autoload.php';
 
$numItems = 87;
$itemsPerPage = 10;
$rawCurrentPageNum = 20;
 
list($numPages, $currentPageNum) = 
    paginate($numItems, $itemsPerPage, $rawCurrentPageNum);
 
printf('num pages = %d, current page num = %d',
    $numPages, $currentPageNum);
num pages = 9, current page num = 9

radioButtons

Description

string radioButtons ( array $radioButtons , string $name , mixed $checkedValue = null , string $title = "" , bool $isContainer = true , array $containerAttributes = array() )

radioButtons() returns a string that's a title span and a set of radio button input()s wrapped in a div tag. The title span and container div are optional. You can set the container div attributes. All other attributes are set automatically(see the name parameter).

Parameters

radioButtons

An array representing the radio buttons. The array key is the radio button value and the array value is the radio button label.

name

The name to use for the radio button inputs. Two other attributes will be set automatically using name:

checkedValue

The value that is checked by default.

title

The title span content. If it's the empty string then there will be no span tag. This value is not escaped.

isContainer

If false then there will be no container div.

containerAttributes

An array of attributes for the container div tag. These attributes will be displayed like in attributes().

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode("\n\n", array(
    radioButtons(
        array('all', 'active', 'none'),
        'mode'),
 
    radioButtons(
        array('a' => 'buzz', 'b' => 'dreads', 'c' => 'rat tail'),
        'hair',
        'b',
        'Hair Style'),
 
    radioButtons(
        array(1 => 'breakfast', 'lunch', 'dinner'),
        'meal',
        3,
        'Favorite Meal',
        true,
        array('style' => 'color:gray;'))));
<div id="c_mode"><div id="c_mode0"><label id="l_mode0" for="mode0">all</label><input id="mode0" name="mode" type="radio" value="0"/></div><div id="c_mode1"><label id="l_mode1" for="mode1">active</label><input id="mode1" name="mode" type="radio" value="1"/></div><div id="c_mode2"><label id="l_mode2" for="mode2">none</label><input id="mode2" name="mode" type="radio" value="2"/></div></div>
 
<div id="c_hair"><span id="t_hair">Hair Style</span><div id="c_hair0"><label id="l_hair0" for="hair0">buzz</label><input id="hair0" name="hair" type="radio" value="a"/></div><div id="c_hair1"><label id="l_hair1" for="hair1">dreads</label><input id="hair1" name="hair" type="radio" value="b" checked/></div><div id="c_hair2"><label id="l_hair2" for="hair2">rat tail</label><input id="hair2" name="hair" type="radio" value="c"/></div></div>
 
<div style="color:gray;" id="c_meal"><span id="t_meal">Favorite Meal</span><div id="c_meal0"><label id="l_meal0" for="meal0">breakfast</label><input id="meal0" name="meal" type="radio" value="1"/></div><div id="c_meal1"><label id="l_meal1" for="meal1">lunch</label><input id="meal1" name="meal" type="radio" value="2"/></div><div id="c_meal2"><label id="l_meal2" for="meal2">dinner</label><input id="meal2" name="meal" type="radio" value="3" checked/></div></div>

route

Description

mixed route ( array $array, mixed $key = $_GET["r"] )

route() returns one value from an array, i.e. it returns array[key].

Parameters

array

The array to get a value from.

key

The array key to use.

Examples

Example #1
require 'vendor/autoload.php';
 
//when routing you'd replace echo with include
 
//route on $_GET['r']
echo route(array(
    null => 'home.php',
    'contact' => 'contact.php'));
 
print ', ';
 
//use a base path
echo 'src/purple/routes/' . route(array(
    null => 'word-list.php',
    'about' => 'about.php'));
 
print ', ';
 
//route on a POST variable
echo route(array(
    null => 'one.php',
    'two' => 'two.php'),
    $_POST['r']);
 
print ', ';
 
//route on some value for testing
echo route(array(
    null => 'home.php',
    'chess' => 'chess.php',
    'golf' => 'golf.php'),
    'golf');
home.php, src/purple/routes/word-list.php, one.php, golf.php

select

Description

string select ( array $options , array $selectAttributes = array() , string $label = "" , mixed $selectedValues = array() , bool $isContainer = true , array $labelAttributes = array() , array $containerAttributes = array() )

select() returns a string that's a label tag and a select tag wrapped in a div tag. The label and div tags are optional. You can set the label, select and div attributes. Some attributes are set automatically(see the selectAttributes parameter). select() supports single select and multi select.

Parameters

options

An array for the option tags inside the select tag. The array key is the option tag value, and the array value is the option tag content. Both the option tag value and content are escaped.

selectAttributes

An array of attributes for the select tag. These attributes will be displayed like in attributes(). If the id key of this array is set, then the following four attributes will be set automatically:

label

The label text. If it's the empty string then there will be no label tag. This value is escaped.

selectedValues

The option values that are selected by default. This must be an array for multi select and a scalar value for single select.

isContainer

If false then there will be no container div.

labelAttributes

An array of attributes for the label tag. These attributes will be displayed like in attributes().

containerAttributes

An array of attributes for the container div tag. These attributes will be displayed like in attributes().

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode("\n\n", array(
    select(array('red', 'blue', 'gold')),
 
    select(
        array(1, 2, 3, 4),
        array('id' => 'numbers')),
 
    select(
        array(1 => 'dog', 'cat', 'bird'),
        array('id' => 'animals'),
        'Animals'),
 
    select(
        array(1 => 'dog', 'cat', 'bird'),
        array('id' => 'pets'),
        'Pets',
        2),
 
    select(
        array('a', 'b', 'c', 'd', 'e', 'f', 'g'),
        array('id' => 'notes', 'size' => 7, 'multiple'),
        'Notes',
        array(0, 1, 6),
        false),
 
    select(
        array(1, 3, 5),
        array('name' => 'odds'),
        'Odds',
        -1,
        true,
        array('class' => 'big-label')),
 
    select(
        array('run', 'jump', 'swim'),
        array('id' => 'verbs', 'multiple'),
        'Verbs',
        array(),
        true,
        array('style' => 'color:white;'),
        array('style' => 'background:brown'))));
<div><select><option value="0">red</option><option value="1">blue</option><option value="2">gold</option></select></div>
 
<div id="c_numbers"><select id="numbers" name="numbers"><option value="0">1</option><option value="1">2</option><option value="2">3</option><option value="3">4</option></select></div>
 
<div id="c_animals"><label id="l_animals" for="animals">Animals</label><select id="animals" name="animals"><option value="1">dog</option><option value="2">cat</option><option value="3">bird</option></select></div>
 
<div id="c_pets"><label id="l_pets" for="pets">Pets</label><select id="pets" name="pets"><option value="1">dog</option><option value="2" selected>cat</option><option value="3">bird</option></select></div>
 
<label id="l_notes" for="notes">Notes</label><select id="notes" size="7" multiple name="notes[]"><option value="0" selected>a</option><option value="1" selected>b</option><option value="2">c</option><option value="3">d</option><option value="4">e</option><option value="5">f</option><option value="6" selected>g</option></select>
 
<div><label class="big-label">Odds</label><select name="odds"><option value="0">1</option><option value="1">3</option><option value="2">5</option></select></div>
 
<div style="background:brown" id="c_verbs"><label style="color:white;" id="l_verbs" for="verbs">Verbs</label><select id="verbs" multiple name="verbs[]"><option value="0">run</option><option value="1">jump</option><option value="2">swim</option></select></div>

sha1Token

Description

string sha1Token ()

sha1Token() returns a random SHA-1 hash.

Examples

Example #1
require 'vendor/autoload.php';
 
echo sha1Token();
d449cf9d3b93d6caf177acda5d118f8a74b498c0

textarea

Description

string textarea ( array $textareaAttributes = array() , string $content = "" , string $label = "" , bool $isContainer = true , array $labelAttributes = array() , array $containerAttributes = array() )

textarea() returns a string that's a label tag and a textarea tag wrapped in a div tag. The label and div tags are optional. You can set the label, textarea and div attributes. Some attributes are set automatically(see the textareaAttributes parameter).

Parameters

textareaAttributes

An array of attributes for the textarea tag. These attributes will be displayed like in attributes(). If the id key of this array is set, then the following four attributes will be set automatically:

content

The textarea tag default content. This value is escaped.

label

The label text. If it's the empty string then there will be no label tag. This value is escaped.

isContainer

If false then there will be no container div.

labelAttributes

An array of attributes for the label tag. These attributes will be displayed like in attributes().

containerAttributes

An array of attributes for the container div tag. These attributes will be displayed like in attributes().

Examples

Example #1
require 'vendor/autoload.php';
 
echo implode("\n\n", array(
    textarea(),
 
    textarea(array('id' => 'story')),
 
    textarea(array('id' => 'answer'), 'blah blah blah'),
 
    textarea(
        array('name' => 'thoughts'),
        '',
        'Thoughts'),
 
    textarea(
        array('id' => 'entry'),
        '',
        'Entry',
        false,
        array('style' => 'color:brown;')),
 
    textarea(
        array('name' => 'bio'),
        'I was born in east LA.',
        'Bio',
        true,
        array('style' => 'color:brown;'),
        array(
            'style' => 'background:#aaaaff;',
            'class' => 'glow'))));
<div><textarea></textarea></div>
 
<div id="c_story"><textarea id="story" name="story"></textarea></div>
 
<div id="c_answer"><textarea id="answer" name="answer">blah blah blah</textarea></div>
 
<div><label>Thoughts</label><textarea name="thoughts"></textarea></div>
 
<label style="color:brown;" id="l_entry" for="entry">Entry</label><textarea id="entry" name="entry"></textarea>
 
<div style="background:#aaaaff;" class="glow"><label style="color:brown;">Bio</label><textarea name="bio">I was born in east LA.</textarea></div>

Mysql::__construct

Description

public Mysql::__construct ( string $host = null , string $username = null , string $password = null , string $databaseName = "" , int $port = null , string $socket = null , string $errorMessage = "database error" , bool $debug = false )

Mysql::__construct() connects to a MySQL database using mysqli.

Pgsql::__construct

Description

public Pgsql::__construct ( string $connectionString , int $connectType = null , string $errorMessage = "database error" , bool $debug = false )

Pgsql::__construct() connects to a PostgreSQL database using pg_connect().

Sqlite::__construct

Description

public Sqlite::__construct ( string $filename , int $flags = 6 , string $encryptionKey = "" , string $errorMessage = "database error" , bool $debug = false )

Sqlite::__construct() connects to an SQLite database using SQLite3.