class Phi - lacockj/phi GitHub Wiki
On this page
These properties are typically set from the configuration file, but can set directly if that is your preference.
number $SESSION_LIFE -- Duration a user session will persist (in seconds)
string $ROUTES_INI -- Path/name of routes initialization files (relative to the document root)
Create a new instance of Phi, optionally passing the path to a Phi configuration file. Like all file path names in Phi, the path is relative to the $_SERVER('DOCUMENT_ROOT']
.
Signature
__construct ([ string $configFile ])
Returns
The newly-constructed Phi instance.
Example Usage
$phi = new \Phi( "../etc/phi.ini" );
Access Phi subclasses as object properties. All subclasses in the Phi namespace are "magically" intantiated when they are accessed as a Phi class property.
Signature
mixed __get ( string $name )
Parameter
$name
The name of the property to get.
Returns
The property value or object reference, or NULL if the property is not found.
Example Usages
$request = $phi->request;
$response = $phi->response;
if ( $phi->request->isXHR() ) ...
Configuration is normally done when Phi is instantiated, but can be done later with a separate call to configure
.
Signature
null configure ([ string $configFile ])
Parameter
$configFile
The filename of the Phi configuration file to load, relative to the document root.
Example Usage
$phi = new \Phi();
...
$phi->configure( "../etc/phi.ini" );
Add another directory in which to look for classes. For autoloading to work properly, PHP class files must have the same name as their classes. Classes in a namespace must all be in a subfolder named after the namespace. Learn more in the PHP spl_autoload_register manual.1
Signature
null addAutoloadDir ( string $dirname[, bool $toFront = false ])
Parameters
$dirname
Directory name to add to the list the autoloader looks in for not-yet-loaded classes.
$toFront
Whether or not to add the new directory to the front of the list to be checked first. By default, new directories are added to the end of the list as the last place to look for class files.
Example Usages
$phi->addAutoloadDir( "/lib/php/classes" );
$phi->addAutoloadDir( "/most/common/classes", true );
This method is a shortcut for the Phi\Request::loadRoutes
method. It also creates a new instance of Phi\Routes
in the current Phi
object if one doesn't already exist.
Signature
Phi\Request loadRoutes ([ string $routesIniFile ])
Parameter
$routesIniFile
Filename of the routes definition file to load, relative to the document root. If the $routsIniFile
parameter is not provided, Phi will attempt to use the current Phi::ROUTES_INI setting defined in the Phi configuration file.
Returns
A reference to the Phi\Request object.
Example Usages
$phiRequestObjectRef = $phi->loadRoutes( "../etc/routes.ini" );
$phi->loadRoutes( "../etc/routes.ini" )->run();
This method is a shortcut for the Phi\Request::run
method. It also creates a new instance of Phi\Routes
in the current Phi
object if one doesn't already exist, and attempts to load routes from the Phi::ROUTES_INI setting.
Attempting to execute Phi::run
before any routes have been loaded will result in an error.
Phi::run
will attempt to follow the request URI to one of the defined route endpoints, saving URI parameters along the way. Phi then calls that endpoint's handler, passing an array of URI parameters as the first argument, and the request input entity as the second argument if one exists.
Phi::run
can also be used in testing by passing optional "mock" URI, method, and request input parameters.
Signature
bool run ([ string $uri [, string $method [, mixed $input ]]])
Parameters
$uri
A mock request URI to run for testing.
$method
The mock request method (i.e. "GET", "POST", "PUT", "DELETE", "PATCH"). If a mock URI is provided without specifying a method, GET
is assumed.
$input
The mock request input parameters, in associative array form.
Returns
True if the request URI/method combination was found in the defined route handlers.
Example Usages
# Typical usage.
$phi->run();
# Check if route was found and executed.
if ( $phi->run() ) {
$phi->log( "Executed request for " . $phi->request->method() . " " . $phi->request->uri() );
} else {
$phi->log( "No route found for " . $phi->request->method() . " " . $phi->request->uri() );
}
# Mock a request for testing.
$phi->run( "/test" );
$phi->run( "/test", "POST", array( "example" => 1234 ) );
$phi->run( "/test/1234", "DELETE" );
Converts a relative path to the absolute path to a file, regardless of where the PHP script is that is asking for the file.
Signature
string pathTo ( string $relativeFileName )
Example Usage
$relativePathFilename = "../etc/alt-db.ini";
$absolutePathFilename = $phi->pathTo( $relativePathFilename );
# "/home/myusername/etc/alt-db.ini"
Pulls a portion of a string off of the full string up to a specified delimiter, returns the portion before the delimiter, and removes it from the original. Handy for processing request headers. The default separator is a space " " character.
Signature
string strpop ( string $str[, string $sep=" " ] )
Parameter | Description |
---|---|
$str | The string to split. |
Returns | Description |
---|---|
{string} | The portion of the string before the first occurrence of the delimiter, or the whole string if the delimiter is not found. |
Example Usage
$authorization = $phi->request->headers('Authorization');
# $authorization === "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
$authScheme = $phi->strpop( $authorization );
# $authScheme === "Basic"
# $authorization === "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
$credentials = base64_decode( $authorization );
# $credentials === "Aladdin:open sesame"
$username = $phi->strpop( $credentials, ":" );
$pass = $credentials;
# $username === "Aladdin"
# $pass === "open sesame"
Creates a deep copy of an array such that it is safe to modify the contents of either array without affecting the other.
Signature
array array_copy ( array $original )
Parameter | Description |
---|---|
$original | The array to copy. |
Returns | Description |
---|---|
{array} | An independent copy of the original array. |
Example Usage
$referencedArray = array( "a" => "apple", "b" => "banana" );
$original = array( &$referencedArray );
$copy = $phi->array_copy( $original );
$copy[0]["b"] = "berries";
# $original is still: array( array( "a" => "apple", "b" => "banana" ) )
# $copy is now: array( array( "a" => "apple", "b" => "berries" ) )
Checks and array to see that all the specified keys exist and are not empty. Handy for quickly making sure all the URI parameters you need are provided.
Signature
mixed pathTo ( array $subject[, string $key1[, string $key2[ , ... ] ] ] )
Parameter | Description |
---|---|
$subject | The array to check. |
$key | A key to verify. |
Returns | Description |
---|---|
true | All the specified keys exist within the subject array and are not empty. |
false | One or more keys are missing or their value is empty. |
null | The first parameter is not an array. |
Example Usage
if ( ! $phi->all_set( $uriParams, 'user_id', 'record_id', 'format' ) ) {
$phi->response->no_content( 400, "Missing Request Parameters" );
}
Logs a line of text to the debug log.
Signature
null log ( string $text )
Parameter | Description |
---|---|
$text | The text to add to the debug log. |
Example Usage
$phi->log( "At step B the value is $value" );
Logs a JSON-encodable object to the debug log.
Signature
null log_json ( mixed $thing )
Parameter | Description |
---|---|
$thing | A string, array, or Object implementing the JsonSerializable interface. |
Example Usage
$foo = array(
"alpha" => 123,
"beta" => "abc"
);
$phi->log_json( $foo );
Fetch the contents of a resource by its URL. Handy for interacting with third-party API.
Signature
mixed fetch ( string $url[, array $headers] )
Parameter | Description |
---|---|
$url | The URL of the resource to fetch, including protocol, host domain, path, file, etc. |
$headers | Optional. An associative array of headers to add to the request. |
Returns | Description |
---|---|
{string} | The response body. |
false | Unable to use cURL or file_get_contents to access the resource. |
Example Usage
$dataString = $phi->fetch( 'http://www.example.com/data.json?foo=bar', array(
"Authorization" => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"X-Access-Token" => "0123456789ABCDEF"
) );
# If fetching JSON, you will need to decode it.
$data = json_decode( $dataString, true );
- Class autoloading is accomplished with the PHP spl_autoload_register function. (PHP 5 >= 5.1.2, PHP 7)