FastSitePHP\Application

The Application Class contains the core code for FastSitePHP. It includes global error handling, template rendering, request routing, application events, basic response methods, sending of the response, and more.

源代码

GitHub

示例代码

Hello World with FastSitePHP

<?php
// Only two files are required to run FastSitePHP and they can
// be in the same directory as [index.php] or the contents can
// be embedded in the main php page.
require 'Application.php';
require 'Route.php';

// Create the Application Object and optionally setup
// Error Handling and a Timezone.
$app = new FastSitePHP\Application();
$app->setup('UTC');

// Define the 'Hello World' default route
$app->get('/', function() {
    return 'Hello World!';
});

// Return a JSON Response by returning an Object or an Array
$app->get('/json', function() {
    return ['Hello' => 'World'];
});

// For all other requests, return the URL as a plain text response.
// The [use] keyword makes the [$app] variable available to the function.
$app->get('/*', function() use ($app) {
    $app->header('Content-Type', 'text/plain');
    return $app->requestedPath();
});

// Run the App
$app->run();

Application Object - Defining Basic Routes

// The Application Object is the key Object in FastSitePHP. It is used to
// define routes, provide request info, render templates, send the response,
// and more. If you are using a copy of this site or a starter site the
// Application Object will be available as the variable [$app] and routes
// are defined in the page [app.php].

// Basic Route
// Send an HTML Response when either '/about' or '/about/' is requested
$app->get('/about', function() {
    return '<h1>About Page</h1>';
});

// By default URL's are case-sensitive however this can be
// turned off and then '/ABOUT' would match the above route.
$app->case_sensitive_urls = false;

// If setting URL strict mode then the above URL would only match
// to '/about' and '/about/' would have to be explicitly defined.
$app->strict_url_mode = true;
$app->get('/about/', function() {
    return '<h1>About Directory</h1>';
});

// The about call using [get()] matches only 'GET' requests. If you would like
// to handle both 'GET' and 'POST' or other methods with the same route you
// can define the route using the [route()] function then check the if there is
// data sent with the request as shown below. The [route()] function will accept
// all request methods.
$app->route('/form', function() {
    if ($_POST) {
        // Handle posted form data
    }
    // Handle GET request, return rendered template, etc
});

// In addition to GET Requests you can handle [ POST, PUT, PATH, and DELETE]
// Requests using named functions.
$app->get('/method', function() { return 'get()'; });
$app->post('/method', function() { return 'post()'; });
$app->put('/method', function() { return 'put()'; });
$app->patch('/method', function() { return 'patch()'; });
$app->delete('/method', function() { return 'delete()'; });

// The same URL can be defined multiple times and the first matching response
// will stop additional routes from being evaluated. In this example the route
// '/example' will return the text 'Example 2'.
$app->get('/example', function() { return null; });
$app->get('/example', function() { return 'Example 2'; });
$app->get('/example', function() { return 'Example 3'; });

// In addition to returning a response you can also simply output a response
// using [echo] or other functions.
$app->get('/echo-response', function() {
    echo 'Output';
});

Define a Route that maps to a Controller Class

// Defining routes with callback functions allows for fast prototyping
// and works well when minimal logic is used. As code grows in size it
// can be organized into controller classes.

// Optionally specify the Controller Class Root Namespace. When using this if a
// class 'Examples' is created then it will map to 'App\Controllers\Examples'.
$app->controller_root = 'App\Controllers';

// Similar to [controller_root] is [middleware_root] which applies to
// [Route->filter()] and [$app->mount()] functions.
$app->middleware_root = 'App\Middleware';

// The two format options are 'class' and 'class.method'. When using only
// class name then the route function [route(), get(), post(),  put(), etc]
// will be used for the method name of the matching controller.
$app->get('/:lang/examples', 'Examples');
$app->get('/:lang/examples/:page', 'Examples.getExample');

// Controller Class Example
class Examples
{
    public function get(Application $app, $lang) { }
    public function getExample(Application $app, $lang, $page) { }
}

// In addition to organizing code into controller classes you can also separate
// routes into separate files using the [mount()] function. The mount function
// will load a file in the same directory only if the starting part of the
// Requested URL matches the Mount URL. An optional 3rd parameter accepts a
// callback function or string of 'Class.method' and if false is returned
// then the file won't be loaded.
$app->mount('/data/', 'routes-data.php');
$app->mount('/secure/', 'routes-secure.php', function() {
    // Logic ...
    return false;
});
$app->mount('/sysinfo/', 'routes-secure.php', 'Env.isLocalhost');

属性

名称 数据类型 默认 描述
template_dir string
null
null Location of the template files that get rendered when using the [render()] function.
header_templates string
array
null
null Header template file or or an array of file names. If defined the template or templates will be rendered prior to the file or files specified in the [render()] function.
error_template string
array
null
null Error template file or or an array of file names. The error template will be rendered when the Applications throws an uncaught Exception or triggers an unhandled error and the response status code returned with an error template is 500. If not set then then the default [error.php] template located under the [Templates] directory will be used.
not_found_template string
array
null
null Not Found template file or or an array of file names. The not-found template will be rendered when the client requests a page that has not matched route or if they request with the wrong method (example GET instead of a POST); the response status codes returned with a not-found template are either [404 => 'Not Found'] or [405 => 'Method Not Allowed']. If this property is left as the default null and an [error_template] is specified then the template specified in [error_template] will be used. If not set then the default [error.php] template located under the [Templates] directory will be used.
show_detailed_errors bool false If set to [true] then full error details will be displayed on the default error template. When using the default error template if running directly on localhost (both client and server) then full error details will automatically be displayed. These rules would only apply to custom error templates if they are setup the same.
error_page_title string
null
"An error has occurred" Title for 500 Error Responses, available as [$page_title] for the error template.
error_page_message string
null
"An error has occurred while processing your request." Message for 500 Error Responses, available as [$message] for the error template.
not_found_page_title string
null
"404 - Page Not Found" Title for 404 'Not Found' Responses, available as [$page_title] for the template.
not_found_page_message string
null
"The requested page could not be found." Message for 404 'Not Found' Responses, available as [$message] for the template.
method_not_allowed_title string
null
"Error - Method Not Allowed" Title for 405 'Method Not Allowed' Responses, available as [$page_title] for the template.
method_not_allowed_message string
null
"A [{method}] request was submitted however this route only allows for [{allowed_methods}] methods." Message for 405 'Method Not Allowed' Responses, available as [$message] for the template.
strict_url_mode bool false The property [strict_url_mode] when set to the default value of false allows for requested URL's to have an ending [/] character at the end of the URL and still be matched to the route. For example, a request for '/about/' with route '/about' will match by default, however if [strict_url_mode] is set to true then '/about/' and '/about' would be separate URL's.
case_sensitive_urls bool true The property [case_sensitive_urls] allows for URL's to be matched using exact upper/lower case letters or for URL's to be matched regardless of case. For example a request for '/ABOUT' with route '/about' will not match by default, however if [case_sensitive_urls] is set to false then the request would match the route.
allow_options_requests bool true The property [allow_options_requests] which defaults to true allows for the application to automatically handle HTTP OPTIONS requests. When set to false OPTIONS requests would be handled as a standard request and it would be up to the application to handle.

OPTIONS requests are most commonly used for Cross-Origin Resource Sharing (CORS) and for custom Web API's. A standard web site used only by a browser and no CORS services will typically not need to handle OPTIONS requests.
allow_methods_override string
null
null String value that if defined will override the default 'Allow' Header Response Field for an OPTIONS Request. For example if the default 'Allow' Header for a specific route returns the value 'HEAD, GET, POST, OPTIONS' but you would prefer to have it return 'HEAD, GET, PUT, OPTIONS' then the values would go here.
controller_root string
null
null Specify a root class path for route controllers that use a string callback. For example if [$app->get('/page', 'Page')] is used with this value set to 'App\Controllers' then the class 'App\Controllers\Page' will be loaded for
the route.
middleware_root string
null
null Specify a root class path for middleware classes that use a string callback. This applies to [Route->filter()] and [$app->mount()] callbacks. For example if [$route->filter('Auth.isUser')] is used with this value set to 'App\Middleware' then 'App\Middleware\Auth->isUser()' will be called on matching routes.
lang string
null
null Specify a language for the application. This is set automatically if using the class [FastSitePHP\Lang\I18N].
json_options int 0 Specify options for [json_encode()] when a JSON Response is returned. Example:
    $app->json_options = (JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

When using PHP 5.4 or above this will be set to JSON_UNESCAPED_UNICODE on the response if no changes are made.
locals array [] The locals property contains an array of variables that can be set throughout the application and used in the render() function from PHP Templates and custom rendering engines. The locals property is a basic PHP array so adding a new variable is handled simply by setting it (e.g.: [$app->locals['name'] = 'FastSitePHP';] and then the variable [$name] would become available from a template called in the render() function).
config array [] The config property contains an array of variables that can be set and used throughout a website or application. There is no requirement to use this however using it allows for site specific configuration values to be organized and easy to find. A few classes included as part of the FastSitePHP Framework do use this including I18N and Crypto.

方法

setup($timezone)

Setup error handling and optionally set a time-zone for the application.

Errors and Exceptions: PHP has an error and exception model that is unique when compared to many other programming languages. Basically PHP 5 contains both errors and exceptions and they both must be handled differently by an application if all errors and exceptions are to be handled.  Additionally PHP provides support for different error reporting levels and using the default PHP server settings not all errors will be handled so if a developer is coming from another language then it can cause a lot of confusion. Examples of this include an undefined variable that would prevent a compiled program from compiling will only raise an error notice warning in PHP and depending upon settings the script can continue while a divide by zero error that might raise an exception or cause a runtime error in another language causes an error type of a warning and can allow for the script to continue. FastSitePHP helps simplify handling errors and exceptions by treating all errors as exceptions that can be handled with a try/catch code block, allowing for all errors and exceptions to be handled using an error() callback function, and rendering all errors and exceptions to the same template with a 500 'Internal Server Error' response code.

Time-zone: Setting a time-zone is required when calling PHP date/time functions. If no time-zone is defined and a date/time function is called then PHP will trigger E_NOTICE or E_WARNING errors. If null is passed as the parameter to this function then it will not setup the time-zone otherwise the time-zone will get set and if the value is not valid then an error or exception will occur and the default error template would be rendered. The $timezone parameter if defined must be set to either a valid time-zone for the PHP function date_default_timezone_set() or to the value 'date.timezone' which use the [php.ini] configuration setting 'date.timezone' for the time-zone. By default the value would be blank when PHP is installed. If PHP is installed on Windows through Microsoft's Web Platform Installer then the [php.ini] setting value will likely be set to the server's timezone.

exceptionHandler($e)

Application defined exception handler function. This function is set as the exception handler when the function [setup()] is called. Passing an exception to this function will run any [error()] callback functions and send a 500 Response Code with the error template to the client. FastSitePHP provides a default error template and allows for customs error template to be assigned from the property [error_template]. This function is public so PHP can call it but in most cases this function would not be called directly from a website or application but rather it is used to handle exceptions that are thrown. For PHP 5 the parameter $e needs to be an instance of an Exception Object and in PHP 7 an instance of a Throwable Object.

errorHandler($severity, $message, $file, $line)

Application defined error handler function. This function is set as an error handler when the function [setup()] is called. For errors that are not ignored by using the [@] error control operator this function will convert the error to an ErrorException object and throw the exception which then gets handled by the [exceptionHandler()] function. This function is public so PHP can call it but in most cases this function would not be called directly from a website or application but rather it is used to handle errors that are raised.

返回类型: bool

shutdown()

Application defined error handler function for fatal errors. This function is set as an error handler when the function [setup()] is called. This function is executed by PHP when script execution is finishing and allows for fatal errors not caught by the error handler function to be handled. This function converts the errors to an ErrorException object and calls the [exceptionHandler()] function which then allows for the website or application to handle the error. This function is public so PHP can call it but it should not be called directly.

__call($name, $arguments)

Allow for methods/functions to be added dynamically to the Application Object using a PHP 'magic method'. In PHP this is called method overloading however the term is used differently in PHP than most programming languages. Objects can always have properties dynamically added however if a function/closure is dynamically added it cannot be called unless the magic method [__call()] is implemented. This implementation of [__call()] allows for functions to be defined in a manner similar to how a function can be added dynamically in JavaScript. One difference in PHP is that a function added dynamically to the Application object will not have access to the [$this] variable that built-in functions have.

JavaScript Example - This works to add a function dynamically to an object:

    var obj = {};
    obj.test = function() { alert('test'); };
    obj.test()

PHP Example - The property can be added but the function cannot be called and the following code would trigger an error. However using the [__call()] magic method if the following function were defined for a class then it can be called.

    $obj = new \stdClass;
    $obj->test = function() { echo 'test'; };
    $obj->test();

返回类型: mixed

methodExists($name)

Return true if either a built-in or dynamic a named method exists for the Application object. Typically [method_exists()] can be used however this Class allows for dynamic methods to be defined.

返回类型: bool

__get($name)

PHP Magic Method which is called if a property is accessed that doesn't exist on the object. It is used here to check for properties defined from [lazyLoad()] and create them the first time they are used.

返回类型: mixed

lazyLoad($name, \Closure $function)

Define a lazy load property which will call a function the first time the property is accessed. This is ideal for a site that has multiple or optional database connections so they can be connected to only when used.

返回类型: $this

statusCode($new_value = null)

Getter / Setter属性

Get or set the response status code by number (for example 200 for 'OK' or 404 for 'Not Found'). By default the PHP will set a status of 200 so setting a status code is usually only needed for other status codes other than 200. This gets sent when the response is sent to the client. If this function is called without a status code passed as a parameter then it will return the current status code otherwise when setting a status code it will return the Application object so it can be used in chainable methods.

返回类型: $this | int | null

header($name, $value = null)

Getter / Setter属性

Define an HTTP Header to be sent with the Response. Additionally previously defined Header fields can be read and cleared using this function. To set a Header field specify both $name and $value parameters. To read the value of a Header field specify only the $name parameter; if the value has been defined it will be returned otherwise if it has not been defined then null will be returned. To clear a Header field pass an empty string '' for the $value parameter. If setting or clearing a Header field then the Application Object will be returned so it can be called as a chainable method.

The Class [\FastSitePHP\Web\Response] also has this function defined. The difference is that Application version is used for basic responses and headers are not validated. If a Response Object is used then headers defined by the Application Object will not be sent. This function is defined here so that responses can be sent without having to load and create a full Response Object.

Examples:
    Set the Response Header 'Content-Type' to 'text/plain'
    $app->header('Content-Type', 'text/plain')

    Get the Response Header 'Content-Type' that has been set.
    If no value has been set then null will be returned.
    $value = $app->header('Content-Type')

    Clear the Response Header 'Content-Type' that has been set
    $app->header('Content-Type', '')

返回类型: $this | mixed | null

headers()

Return an array of Headers fields defined from the header() function that will be or have been sent with the HTTP Response if a basic string or array response is used. If a Response Object is used then headers defined by the Application Object will not be sent.

返回类型: array

noCache($no_cache = true)

Getter / Setter属性

Set Response Headers that tell the browser or client to not cache the response.

This function defines the following response headers:
    Cache-Control: no-cache, no-store, must-revalidate
    Pragma: no-cache
    Expires: -1

For most clients and all modern browsers 'Cache-Control' will take precedence over 'Expires' when both tags exist. The 'Expires' header per HTTP Specs must be defined as an HTTP-Date value, and when an invalid value such as '0' is used then the client should treat the content as already expired, however in reality certain older versions of Internet Explorer may end up caching the response if '0' is used so '-1' is used for the 'Expires' header. At the time of writing both Google and Microsoft use 'Expires: -1' for their homepages. The header 'Pragma' is for old HTTP 1.0 clients that do not support either 'Cache-Control' or 'Expires'.

This function exists in both [FastSitePHP\Application] and [FastSitePHP\Web\Response] classes; calling the function from the Application object specifies the headers only when a route returns a basic response and calling the function from the Response object specifies the headers only when the route returns a Response object.

返回类型: $this | mixed

cors($origin_or_headers = null)

Getter / Setter属性

Get or set a values for Cross-Origin Resource Sharing (CORS) Response Headers. For security reasons browsers will restrict content that is from a different domain when using JavaScript (for example: calling a Web Service from XMLHttpRequest). CORS is a web standard that allows for restricted resources to work on domains other than the domain where the resource is hosted.

This function is flexible and allows for setting the most common header 'Access-Control-Allow-Origin' as a string value or it can set multiple CORS Headers by specifying an array. To clear any CORS Headers call this function with an empty string and to get defined CORS Headers call this function without any parameters.

CORS Headers are sent with both the OPTIONS request method and the calling method. Because OPTIONS requests are required for certain response types the cors() function should often be called in a filter() function or a before() event function.

Examples:
    $app->cors(*);

    $app->cors(array(
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Authorization',
    ));

返回类型: $this | null | array

Define a cookie to be sent with the response along with the response headers. Internally this calls the PHP function setcookie(). To delete a cookie use the function [clearCookie()]. To read cookies use the [cookie()] function of the [FastSitePHP\Web\Request] Object or use the PHP superglobal array $_COOKIE.

The [$expire] parameter defaults to 0 which makes the cookie expire at the end of the session. Additionally if PHP 7.3 or higher is used then an array of [$options] can be used as the [$expire] parameter and no other parameters are required. [$options] allows for the `SameSite` Attribute.

返回类型: $this

clearCookie($name, $path_or_options = '', $domain = '', $secure = false, $httponly = false, $samesite = null)

Send an empty value for a named cookie and expired time to tell the browser or client to clear the cookie.

返回类型: $this

cookies()

Return the Array of Cookies that will be sent with the response.

返回类型: array

escape($text)

Convert special characters to HTML entities. This function is a wrapper for the php function:
    htmlspecialchars($text, ENT_QUOTES, 'UTF-8', true)

Characters escaped are:
    " = &quot;
    & = &amp;
    ' = &#039;
    < = &lt;
    > = &gt;

返回类型: string

engine(\Closure $callback)

Define a callback closure function for rendering template files using variables passed by the application. This allows for custom rendering engines to be used in addition to the native PHP and Text file templates. The required callback definition for defining a rendering engine is [function($file, array $data = null)]; the actual variable names can be different however the array typehint and optional 2nd parameter must be defined. For an example of defining a custom rending engine see Quick Reference Page.

返回类型: $this

render($files, array $data = null)

Render a single template file or an array of template files using variables specified in the $data parameter and also variables defined from the [locals] property. In addition templates rendered using PHP or a custom rendering engine will have the variable [$app] defined as a reference to this Application Object Instance. The default format used for templates are PHP templates, however including plain text files works as well. To override the default view engine define one using the [engine()] function before calling [render()]. Template files call be specified by name as long as the property [template_dir] is defined. Addition properties related to this function are [header_templates], [footer_templates], [error_template], and [not_found_template].

返回类型: string

errorPage($page_title, $message, $e = null)

Render the html error template using a custom page title, message, and optional exception. This function only renders the HTML and does not set status code or send the response.

返回类型: string

pageNotFound()

Set the status code to 404 'Not found' and render and return the 404 error template. This function will render template specified in the property [not_found_template] if one is defined otherwise the default 404 page. Custom [page_title] and [message] variables can be defined for the template from properties [not_found_page_title] and [not_found_page_message].

返回类型: string

sendPageNotFound()

Send a 404 'Not found' response to the client and end script execution. This uses the same template that would be returned from calling [$app->pageNotFound()].

before(\Closure $callback)

Add closure functions that will be called from the [run()] function prior to any routes being matched. Closure functions passed to the [before()] function should be defined as [function()] because no parameters are passed. If multiple functions are defined then they are called in the order that they were added. An example of using a [before()] function is to check the session for logged in user permissions that can then be checked against route filter functions to see if the user has access to the request resource.

返回类型: $this

notFound(\Closure $callback)

Add closure functions that will be called from the [run()] function after all routes have been checked with no routes matching the requested resource. Closure functions passed to the [notFound()] function take no parameters and if they return a response then it be handled as a standard route and will call any defined [beforeSend()] functions afterwards. If no value is returned from the function then each function is checked in order added and if none of the [notFound()] functions return a response then a 404 'Not found' response is sent to the client. Examples of using a [notFound()] function would be to define rules dynamic routing where the application would handle routes mapped to dynamic controllers or to log 404 response codes.

返回类型: $this

beforeSend(\Closure $callback)

Add closure functions that will be called from the [run()] function after a route has been matched to the requested resource. Closure functions passed to the [beforeSend()] function should be defined as [function($content)] and they must return a response otherwise a 404 'Not found' response will be sent to the client. The [$content] parameter defined in the callback is the contents of the response that will be sent to the client. If multiple functions are defined then they are called in the order that they were added. An example of using a [beforeSend()] function would be adding a CSRF Token (Cross-Site Request Forgery) to all html forms and then also adding a [before()] function that checks if the token is present on each Form POST.

返回类型: $this

after(\Closure $callback)

Add closure functions that will be called from the [run()] function after the response has been sent to the client. Closure functions passed to the [after()] function should be defined as [function($content)]; the [$content] parameter defined in the callback is the contents of the response that was sent to the client. If multiple functions are defined then they are called in the order that they were added. If FastSitePHP is set to handle errors and exceptions from the [setup()] function then functions defined here get called after the error response has been sent. The only way that [after()] functions will not get called is if there script is terminated early from PHP's exit() statement or if error handling is not setup and an error occurs.

返回类型: $this

error(\Closure $callback)

Add closure functions that will be called from the private function [sendErrorPage()] function if an error or an exception occurs and the FastSitePHP is set to handle errors and exceptions from the [setup()] function. Closure functions passed to the [error()] function should be defined as [function($response_code, $e, $page_title, $message)]. The [error()] function allow for an application to log error responses however it does not prevent the error response from rendering. To override the error template and 500 status code and send a different response a closure function defined here would need to handle the response and call PHP's exit() statement.

返回类型: $this

onRender(\Closure $callback)

Add closure functions that will be called whenever [render()] is called. The events will run before templates are rendered but once template paths are confirmed to be valid. This is usefull for making sure that specific variables are included in [$app->locals] prior to template rendering.

返回类型: $this

mount($url_path, $file, $condition = null)

Load a PHP file based on the requested URL and an optional condition closure function. The [$url_path] parameter accepts the starting part of a URL. For example [/api] will match all requested URL's starting with [/api]. This allows for routes or functions related to specific routes to be loaded only if they are needed. The optional condition function should return true or false if defined and allows for the mount path to be skipped even if the requested URL matches. An example of this would be allowing for certain routes to only load on specific environments such as localhost. The [$file] parameter accepts either a file name which will then cause the file to be loaded in the same directory of the calling file or a full file path.

返回类型: $this

route($pattern, $callback, $method = null)

Add a route for an HTTP Request, if the parameter $method is not specified then the route will match all requests with the matching url. To map to a specific HTTP method the method would be included in the parameter (e.g.: 'GET') or in the case of common methods the function named the same name as the route could be used instead [e.g.: $app->get($path, $func)]. When the route is matched [e.g.: requested url = '/about' and route = $app->route('/about', $callback)] then the callback method will get called based on filter logic from the $app->run() function.

返回类型: Route

get($pattern, $callback)

Add a route for an HTTP 'GET' Request

返回类型: Route

post($pattern, $callback)

Add a route for an HTTP 'POST' Request

返回类型: Route

put($pattern, $callback)

Add a route for an HTTP 'PUT' Request

返回类型: Route

delete($pattern, $callback)

Add a route for an HTTP 'DELETE' Request

返回类型: Route

patch($pattern, $callback)

Add a route for an HTTP 'PATCH' Request

返回类型: Route

routes()

Return the Array of Defined Routes

返回类型: array

redirect($url, $status_code = 302)

Redirect the user to another page or site. This must be called prior to headers and content being sent to the user. Calling this function ends the script execution however any events defined by the [after()] function will run.

Status Code can optionally be specified as the 2nd parameter. The default Status Code used is [302 'Found'] (Temporary Redirect). If Status Code [301 'Moved Permanently'] is used Web Browsers will typically cache the result so careful testing and consideration should be done if using a Status Code of 301. Other supported Status Codes are: [303 'See Other'], [307 'Temporary Redirect'], and [308 'Permanent Redirect'].

Example:

    // User makes this request
    $app->get('/page1', function() use ($app) {
        $app->redirect('page2');
    });

    // User will then see this URL and Response
    $app->get('/page2', function() {
        return 'page2';
    });

requestedPath()

Return the Requested Path (Page only, excluding site, base directory, query strings, etc). This will return the same result regardless of the Web Server used and it will be based on where the [index.php] or entry PHP file is located.

Request Examples:
    https://www.example.com/index.php/test/test?test=test
    https://www.example.com/index.php/test/test
    https://www.example.com/test/test/
    https://www.example.com/test/test
    https://www.example.com/site1/index.php/test/test

Returns:
    '/test/test'

In the above example both '/test/test/' and '/test/test' return '/test/test' when using the default property [$app->strict_url_mode = false] otherwise the exact URL would be returned.

返回类型: string | null

rootUrl()

Return the Site Root URL; the URL returned is the base URL for all pages.

Examples:

    # [index.php] specified in the URL
    Request: https://www.example.com/index.php/page
    Request: https://www.example.com/index.php/page/page2
    Returns: https://www.example.com/index.php/

    # [index.php] Located in Root Folder
    Request: https://www.example.com/page
    Request: https://www.example.com/page/page2
    Returns: https://www.example.com/

    # [index.php] Located under [site1]
    Request: https://www.example.com/site1/page
    Request: https://www.example.com/site1/page/page2
    Returns: https://www.example.com/site1/

返回类型: string | null

rootDir()

Return the Site Root Directory; the Directory returned is generally the base Directory for all resources (JS, CSS, IMG Files, etc).

Request Examples:
    https://www.example.com/index.php/page
    https://www.example.com/index.php/page/page2
    https://www.example.com/page

Returns:
    https://www.example.com/

返回类型: string

param($name, $validation, $converter = null)

Define validation and conversion rules for a route variable. The definition of the parameter variable defined here gets checked by the function [routeMatches()] when [run()] is called.

返回类型: $this

routeMatches($pattern, $path)

Check if a the current url path matches a defined route. This function returns an array or parsed arguments if the route matches and boolean value of false if it does not match. If the route matches and there are no defined parameters then the array returned is an empty array. A wild-card character '*' can be used at the very end of the route definition and then the url path must match up until the wild-card character. Specific variables will be validated or converted if defined in the function $app->param(). Optional variables can be defined with a '?' character at the end of the variable name. A request for '/about/' with route '/about' will match by default, however if [strict_url_mode] is set to true then '/about/' and '/about' would be separate URL's.

Examples:
    $app->routeMatches('/page1', '/page2');
        returns false

    $app->routeMatches('/show-all', '/show-all');
        returns array()

    # [string] data type returned
    $app->routeMatches('/record/:id', '/record/123');
        returns array('123')

    # [int] data type based on param()
    $app->param(':id', 'int');
    $app->routeMatches('/record/:id', '/record/123');
        returns array(123)

    # Only a ':' character is required to indicate a variable
    $app->routeMatches('/record/:', '/record/123');
        returns array('123')

    $app->routeMatches('/:record/:view/:id', '/orders/edit/123');
        returns array('orders', 'edit', '123')

    # Optional variables ending with '?'
    $app->routeMatches('/search-by-date/:year?/:month?/:day?', '/search-by-date/2015/12');
        returns array('2015', '12')

    $app->routeMatches('/page-list/*', '/page-list/page1/page2')
        returns array()

返回类型: array | bool

run()

This is the main function that processes the request, determines the route, and sends a response. Routes, settings, validation rules, etc need to be defined prior to calling this function.

runAfterEvents($content)

Call all closure functions defined from [after()]. This function is public however it would normally not be called. It is used by FastSitePHP internally after sending the response.