### Composer Installation of Fat-Free Framework Core
Source: https://github.com/f3-factory/f3com-data/blob/master/3.8/getting-started/main.md
If you only need the core files of the Fat-Free Framework without the demo package, use this composer command. This is useful for experienced users who prefer a minimal setup.
```bash
require bcosca/fatfree-core
```
--------------------------------
### Composer Installation of Fat-Free Framework
Source: https://github.com/f3-factory/f3com-data/blob/master/3.8/getting-started/main.md
Install the Fat-Free Framework using Composer. This is the recommended method for managing project dependencies and ensuring you have the latest core files.
```bash
require bcosca/fatfree
```
--------------------------------
### PHP Fat-Free Framework: Hello World with Composer
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/getting-started/main.md
This snippet demonstrates setting up a "Hello, World!" route using the Fat-Free Framework when installed via Composer. It leverages autoloading, instantiates the framework, defines a GET route for the root URL, and runs the application. This method is recommended for managing dependencies.
```php
require 'vendor/autoload.php';
$f3 = \Base::instance();
$f3->route('GET /',
function() {
echo 'Hello, world!';
}
);
$f3->run();
```
--------------------------------
### Example PHP Version Output
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/getting-started/main.md
This is an example of the output you would expect when checking your PHP version using the command line. It confirms the version number, copyright, and the Zend Engine version, helping to identify if your PHP installation meets the Fat-Free Framework's requirements.
```text
PHP 5.6.22-1 (cli)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies
```
--------------------------------
### PHP Fat-Free Framework: Basic Hello World Route
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/getting-started/main.md
This snippet shows the basic setup for a "Hello, World!" route using the Fat-Free Framework. It requires the framework's base file, defines a GET route for the root URL, and runs the application. Ensure `base.php` is correctly included before any output.
```php
route('GET /',
function() {
echo 'Hello, world!';
}
);
$f3->run();
```
--------------------------------
### Check PHP Version using Command Line
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/getting-started/main.md
This command-line instruction allows you to verify your installed PHP version. Ensure you are running PHP 5.3 or later for compatibility with the Fat-Free Framework.
```bash
/path/to/php -v
```
--------------------------------
### PHP Hello World Route with Fat-Free Framework
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/getting-started/main.md
This snippet demonstrates how to set up a basic 'Hello, World!' route for the root URL using the Fat-Free Framework in PHP. It requires the framework's base file, defines a GET route for '/', and runs the application to listen for requests. Ensure 'base.php' is included before any output.
```php
route('GET /',
function() {
echo 'Hello, world!';
}
);
$f3->run();
```
--------------------------------
### Setup Pingback Listener Example (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.8/pingback/main.md
This example demonstrates setting up a Pingback listener in PHP using the F3 framework. It includes a callback handler, a route definition, and the function to bind the listener to the route.
```php
// the callback function called by the listen() function. Takes 2 parameters
function pingCallBackHandler($sourceURL, $reqBody) {
$logger = new Log('pings.log');
$logger->write('Incoming ping from '.$sourceURL);
// any processing on the $reqBody
$logger->write('Request body length is '.
\UTF::instance()->strlen($reqBody));
}
// a route as an example, e.g.
$f3->route('GET /listener','PingListener');
// the function to bind to the listener:
function PingListener($f3, $params) {
$pingback = new \Web\Pingback;
// bind it with our custom callback function
$pingback->listen('pingCallBackHandler');
return;
}
```
--------------------------------
### PHP F3 Factory CLI Mode Setup and Controller Example
Source: https://context7.com/f3-factory/f3com-data/llms.txt
Illustrates how to configure and utilize F3 Factory's Command Line Interface (CLI) mode. This includes defining CLI routes in a configuration file, understanding how shell commands are translated into GET requests, and providing an example of a CLI controller (`CLI\Cache`) that accesses arguments via the `$f3` object and implements confirmation prompts. It also shows how to detect and initialize for CLI mode.
```php
// CLI route definition (routes.ini)
/*
[routes]
GET /cache/clear [cli] = CLI\Cache->clear
GET /db/migrate [cli] = CLI\Database->migrate
GET /report/generate [cli] = CLI\Report->generate
GET /help/@command [cli] = CLI\Help->@command
*/
// Shell-style command execution
// php index.php cache clear -f --verbose
// Converts to: GET /cache/clear?f=&verbose=
// php index.php db migrate --env=production --force
// Converts to: GET /db/migrate?env=production&force=
// php index.php report generate --type=sales --year=2024 --format=pdf
// Converts to: GET /report/generate?type=sales&year=2024&format=pdf
// CLI Controller example
namespace CLI;
class Cache {
function clear($f3) {
// Access CLI options via GET
$force = $f3->exists('GET.f') || $f3->exists('GET.force');
$verbose = $f3->exists('GET.v') || $f3->exists('GET.verbose');
if ($verbose) {
echo "Clearing cache...\n";
}
if ($force || $this->confirm('Clear all cache entries?')) {
\Cache::instance()->reset();
echo "Cache cleared successfully.\n";
} else {
echo "Operation cancelled.\n";
}
}
private function confirm($message) {
echo "$message (y/n): ";
$handle = fopen("php://stdin", "r");
$line = trim(fgets($handle));
fclose($handle);
return strtolower($line) === 'y';
}
}
// Check if running in CLI mode
if ($f3->get('CLI')) {
// CLI-specific initialization
$f3->set('QUIET', TRUE);
error_reporting(E_ALL);
} else {
// Web-specific initialization
}
// Mock CLI requests for testing
$f3->mock('GET /cache/clear?force=1 [cli]');
```
--------------------------------
### Fat-Free Framework Hello World (PHP - Composer)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/getting-started/main.md
This PHP snippet shows how to set up a Fat-Free Framework application when using Composer for dependency management. It autoloader, instantiates the framework, and defines a route for the root URL to display 'Hello, world!'. This method is recommended for managing framework dependencies.
```php
require 'vendor/autoload.php';
$f3 = \Base::instance();
$f3->route('GET /',
function() {
echo 'Hello, world!';
}
);
$f3->run();
```
--------------------------------
### Jig (Flat-File) User Authentication Setup
Source: https://context7.com/f3-factory/f3com-data/llms.txt
Sets up user authentication with the Auth class using Jig, a flat-file database system. The example demonstrates creating a Jig mapper and initializing the Auth class with specified 'id' and 'pw' fields.
```php
// Jig (flat-file database) authentication
$db = new \DB\Jig('data/');
$userMapper = new \DB\Jig\Mapper($db, 'users');
$auth = new \Auth($userMapper, array('id' => 'username', 'pw' => 'password'));
```
--------------------------------
### MongoDB User Authentication Setup
Source: https://context7.com/f3-factory/f3com-data/llms.txt
Configures user authentication using the Auth class with a MongoDB backend. This example shows the instantiation of the MongoDB mapper and the Auth class, specifying the 'id' and 'pw' fields for authentication.
```php
// MongoDB authentication
$db = new \DB\Mongo('mongodb://localhost:27017', 'myapp');
$userMapper = new \DB\Mongo\Mapper($db, 'users');
$auth = new \Auth($userMapper, array('id' => 'email', 'pw' => 'password'));
```
--------------------------------
### Setup Pingback Listener Route and Function in PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/pingback/main.md
This example demonstrates how to set up an F3 route and bind it to a listener function that utilizes the Pingback::listen() method with a custom callback. This configures the application to receive and handle incoming pingbacks.
```php
// a route as an example, e.g.
$f3->route('GET /listener','PingListener');
// the function to bind to the listener:
function PingListener($f3, $params) {
$pingback = new \Web\Pingback;
// bind it with our custom callback function
$pingback->listen('pingCallBackHandler');
return;
}
```
--------------------------------
### Complete Authentication System Example (F3 Framework)
Source: https://context7.com/f3-factory/f3com-data/llms.txt
Provides a comprehensive example of an authentication system within the F3 framework. It includes a controller for login and logout actions, handling POST requests for login, verifying credentials against a SQL database, managing user sessions, and routing.
```php
// Complete login system example
class AuthController {
function login($f3) {
if ($f3->get('VERB') == 'POST') {
$db = $f3->get('DB');
$user = new \DB\SQL\Mapper($db, 'users');
$auth = new \Auth($user, array('id' => 'email', 'pw' => 'password'));
$email = $f3->get('POST.email');
$password = $f3->get('POST.password');
// Load user to check password
$user->load(array('email = ?', $email));
if (!$user->dry() && password_verify($password, $user->password)) {
$f3->set('SESSION.user_id', $user->id);
$f3->set('SESSION.username', $user->name);
$f3->set('SESSION.role', $user->role);
$f3->reroute('/dashboard');
} else {
$f3->set('error', 'Invalid credentials');
$f3->set('login_attempts', $f3->get('SESSION.login_attempts') + 1);
}
}
echo \Template::instance()->render('login.html');
}
function logout($f3) {
$f3->clear('SESSION');
$f3->reroute('/');
}
}
$f3->route('GET|POST /login', 'AuthController->login');
$f3->route('GET /logout', 'AuthController->logout');
```
--------------------------------
### Example SQL Options - PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/sql-mapper/main.md
Provides a practical example of using the $option array to define sorting, grouping, and pagination for SQL query results.
```php
array(
'order' => 'score DESC, team_name ASC',
'group' => 'score, player',
'limit' => 20,
'offset' => 0
)
```
--------------------------------
### Starting PHP Built-in Web Server
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/routing-engine/main.md
Provides the command to start PHP 5.4's built-in web server, specifying the host, port, and the document root for serving application files.
```bash
php -S localhost:80 -t /var/www/
```
--------------------------------
### XML: Example myview.xml
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/view/main.md
An example XML view template formatted as a sitemap, iterating over URLs from the data hive.
```xml
```
--------------------------------
### Preview Template Example
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/preview/main.md
Demonstrates the syntax for a lightweight template using PHP expressions wrapped in `{~ ~}` control characters. This example shows how to iterate over a collection and conditionally display elements within an HTML structure.
```html
```
--------------------------------
### PHP Example: Build URL with Named Route Alias
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/quick-reference/main.md
Illustrates how to construct a URL for a named route in F3 using the 'alias' directive. This example shows passing route parameters dynamically.
```php
{{ @name, 'a=5,b='.@id | alias }}
```
--------------------------------
### XML: Example XML view for URL list
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/view/main.md
An example of an XML view template structured for sitemaps. It iterates through a list of URLs and formats them within the XML structure.
```html
```
--------------------------------
### REST Interface Example
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/routing-engine/main.md
Demonstrates how to map HTTP methods to class methods for creating a RESTful interface.
```APIDOC
## POST /cart/@item
### Description
Handles POST requests to the /cart/@item endpoint, typically used for creating or updating an item in the cart.
### Method
POST
### Endpoint
/cart/@item
### Parameters
#### Path Parameters
- **item** (string) - Required - The identifier for the item in the cart.
### Request Body
(Details depend on specific implementation, e.g., item details for creation/update)
### Response
#### Success Response (200)
(Details depend on specific implementation, e.g., confirmation of action)
#### Response Example
```json
{
"status": "success",
"message": "Item added to cart successfully."
}
```
## GET /cart/@item
### Description
Handles GET requests to the /cart/@item endpoint, typically used for retrieving details of a specific item in the cart.
### Method
GET
### Endpoint
/cart/@item
### Parameters
#### Path Parameters
- **item** (string) - Required - The identifier for the item in the cart.
### Response
#### Success Response (200)
- **item_details** (object) - Description of the item.
#### Response Example
```json
{
"item_details": {
"id": "123",
"name": "Example Item",
"price": 19.99
}
}
```
## PUT /cart/@item
### Description
Handles PUT requests to the /cart/@item endpoint, typically used for updating an existing item in the cart.
### Method
PUT
### Endpoint
/cart/@item
### Parameters
#### Path Parameters
- **item** (string) - Required - The identifier for the item in the cart.
### Request Body
(Details depend on specific implementation, e.g., updated item details)
### Response
#### Success Response (200)
(Details depend on specific implementation, e.g., confirmation of update)
#### Response Example
```json
{
"status": "success",
"message": "Item updated successfully."
}
```
## DELETE /cart/@item
### Description
Handles DELETE requests to the /cart/@item endpoint, typically used for removing an item from the cart.
### Method
DELETE
### Endpoint
/cart/@item
### Parameters
#### Path Parameters
- **item** (string) - Required - The identifier for the item in the cart.
### Response
#### Success Response (200)
(Details depend on specific implementation, e.g., confirmation of deletion)
#### Response Example
```json
{
"status": "success",
"message": "Item deleted successfully."
}
```
```
--------------------------------
### SQL Mapper Options Structure and Example - PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/sql-mapper/main.md
Explains the structure of the `$option` argument used in SQL Mapper queries, which allows for specifying ordering, grouping, limits, and offsets. An example demonstrates how to combine these options.
```php
array(
'order' => string $orderClause,
'group' => string $groupClause,
'limit' => integer $limit,
'offset' => integer $offset
)
array(
'order' => 'score DESC, team_name ASC',
'group' => 'score, player',
'limit' => 20,
'offset' => 0
)
```
--------------------------------
### Send and Receive File Example - PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/web/main.md
A comprehensive example demonstrating both sending a file to the client using `send()` and receiving a file upload via a mocked PUT request using `receive()`. It includes setting up a route and handling the upload.
```php
$file=$f3->get('UI').'images/wallpaper.jpg';
ob_start();
// send the file without any download dialog
$web->send($file,NULL,512,FALSE);
$out=ob_get_clean();
// setup a route and its associated handler
$f3->set('UPLOADS',$f3->get('TEMP'));
$f3->route('PUT /upload/@filename',
function() use($web) { $web->receive(); }
);
// mock a request that will actually upload the file
$f3->mock('PUT /upload/'.basename($file),NULL,NULL,$f3->read($file));
if (is_file($target=$f3->get('UPLOADS').basename($file)))
echo 'Uploaded file done via PUT';
@unlink($target);
```
--------------------------------
### Jig Mapper Methods - PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/jig-mapper/main.md
Provides examples of using core Jig Mapper methods like `set`, `get`, `fields`, `cast`, `token`, `find`, `count`, `insert`, `update`, `erase`, and `copyfrom`.
```php
$mapper->foo = 'bar';
$mapper['foo'] = 'bar';
scalar|FALSE $val = $mapper->get( string $key );
NULL $res = $mapper->clear( string $key );
array $fields = $mapper->fields();
array $arr = $mapper->cast();
string $token = $mapper->token( string $str );
array|FALSE $records = $mapper->find( [ array $filter = NULL [, array $options = NULL [, int $ttl = 0 [, bool $log = TRUE ]]]] );
int $count = $mapper->count( [ array $filter = NULL [, $ttl = 0 ]] );
array $newRecord = $mapper->insert();
array $updatedRecord = $mapper->update();
bool $success = $mapper->erase( [ array $filter = NULL ] );
NULL $res = $mapper->copyfrom( array | string $var [, callback $func = NULL ] );
```
--------------------------------
### F3 Template Syntax Examples
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/views-and-templates/main.md
Provides examples of F3 template syntax for displaying variables, performing arithmetic and boolean expressions, using PHP constants, conditional selections, type casting, and accessing object properties.
```html
Hello, {{ @name }}!
```
```html
{{ @buddy[0] }}, {{ @buddy[1] }}, and {{ @buddy[2] }}
That is {{ preg_match('/Yes/i',@response)?'correct':'wrong' }}!
```
```html
{{ @obj->property }}
```
```html
{{ @func('hello','world') }}
```
--------------------------------
### PHP Template Engine Multilingual Example
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/views-and-templates/main.md
Shows how to display multilingual content using PHP as the template engine. It retrieves translated strings using `$f3->get()` and passes arguments for formatting.
```php
```
--------------------------------
### PHP: Using Extended Magic Class
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/magic/main.md
This example shows how to instantiate and use a class extended from the Magic class (like the User class). It illustrates setting and getting properties using both object property syntax and array-like access, demonstrating the functionality of the magic wrapper.
```php
$user = new User();
$user->name = 'John';
$user['age'] = 28;
$user->set('mail','john@email.com');
echo $user['name']; // John
echo $user->get('age'); // 28
echo $user->mail; // john@email.com
```
--------------------------------
### Execute F3 Route from CLI
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/routing-engine/main.md
This example shows how to execute a specific F3 framework route from the command line interface (CLI). By running `php index.php` followed by the desired route, you can simulate a GET request to that route for tasks like updates or testing.
```bash
cd /path/to/test/suite
php index.php /my-awesome-update-route
```
--------------------------------
### F3 Factory: Processing CLI Options (Syntax #1)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/routing-engine/main.md
An example of processing command-line options in F3 Factory using the '$f3->exists()' and '$f3->get()' methods. This approach allows for data validation and mixing short and long-form options.
```php
// syntax #1 (validating data, mixing short and long forms)
$opts=[
'force' => $f3->exists('GET.f'), // -f
'limit' => abs((int)$f3->get('GET.limit')) ?: 20, // --limit=N (default: 20)
'verbose' => $f3->exists('GET.v') || $f3->exists('GET.verbose'), // -v OR --verbose
];
```
--------------------------------
### Pingback Instantiation
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/pingback/main.md
Get an instance of the Pingback class using the Prefab factory wrapper.
```APIDOC
## Instantiation
**Return class instance**
```php
$pingback = Web\Pingback::instance();
```
The Pingback class uses the Prefab factory wrapper, so you can grab the same instance of that class at any point of your code.
```
--------------------------------
### HTML: Example HTML view for URL list
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/view/main.md
An example of an HTML view template that iterates through a list of URLs provided in the data hive and displays them in an HTML table.
```html
...
```
--------------------------------
### Get Last Inserted ID Example - PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/sql-mapper/main.md
Shows how to use the 'get()' method with the reserved '_id' key to retrieve the ID of the last inserted row or the last value from a sequence object.
```php
$lastInsertedID = $mapper->get('_id'); // get the ID of the last inserted row or the last value from a sequence object
```
--------------------------------
### Custom Mapper Model Example (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/cursor/main.md
An example demonstrating how to extend the Mapper class and use the `set` method within event handlers to safely modify mapper fields, avoiding issues with protected properties.
```php
class Model extends \DB\SQL\Mapper {
function __construct(){
parent::__construct(\Base::instance()->get('DB'),'test_model');
$this->beforeinsert(function($self){
$self->source='bar'; // fails due to protected property named 'source'
$self->set('source','bar'); // works - just use the setter directly
});
}}
```
--------------------------------
### Get Jig Profiler Log
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/jig/main.md
Returns the accumulated log entries from the Jig profiler. The example shows jotting a message and then retrieving the formatted log.
```php
string log ( )
```
```php
$db->jot('Merry Christmas');
echo $db->log(); // "Wed, 25 Dec 2013 08:27:58 +0100 Merry Christmas"
```
--------------------------------
### HTML: Example myview.html
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/view/main.md
A sample HTML view template that iterates over a list of URLs provided in the data hive and displays them in an HTML table.
```html
...
```
--------------------------------
### Integrating PSR-11 Container with F3 Framework
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/quick-reference/main.md
Provides an example of setting the CONTAINER variable to integrate a dependency injection container. This example shows how to use a callable to adapt a third-party container (like Dice) for use with F3's `Base->call()` and routing system.
```php
$dice = … // Configure the API-incompatible Level-2/Dice container.
$f3->set('CONTAINER', function ($class) use ($dice) {
return $dice->create($class);
});
```
--------------------------------
### Get Jig Connection UUID
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/jig/main.md
Returns a Universally Unique Identifier (UUID) hash that represents the current Jig connection. The example shows how to echo the generated UUID.
```php
string uuid ( )
```
```php
echo $db->uuid(); // e.g. "0dso6nqcdhr" (string, length 11)
```
--------------------------------
### Define Basic Routes in F3
Source: https://context7.com/f3-factory/f3com-data/llms.txt
Demonstrates how to define simple GET and POST routes for the homepage, login, and static pages using the F3 framework. Assumes F3 base library is included.
```php
$f3 = require('lib/base.php');
// Basic routes
$f3->route('GET /', function($f3) {
echo 'Welcome to the homepage';
});
$f3->route('POST /login', 'AuthController->login');
$f3->route('GET /about', 'PageController::show');
// Start the framework
$f3->run();
```
--------------------------------
### Emulating Web Routes from CLI with Shell Syntax
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/routing-engine/main.md
Explains how to use shell arguments and options to emulate HTTP GET requests from the command line. Spaces map to path components, and flags/options map to query string parameters. These are accessible via the `$_GET` global.
```bash
php index.php test
php index.php log show --limit=50 --full
php index.php cache clear -f -v -i -n=23
```
--------------------------------
### Preview Build Method Example
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/preview/main.md
Illustrates how the `build` method converts a template token like `{{ @book.title | esc }}` into executable PHP code: `esc($book['title']); ?>`. This is useful for creating custom template extensions.
```php
esc($book['title']); ?>
```
--------------------------------
### CSRF Token Usage Example (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/session/main.md
Provides a step-by-step guide on how to implement CSRF protection using the `csrf()` method. It covers obtaining the token, storing it in session, embedding it in a form, and validating it on submission.
```php
$sess=new DB\SQL\Session($db);
$f3->CSRF=$sess->csrf();
// Or via constructor:
// new DB\SQL\Session($db,'sessions',TRUE,NULL,'CSRF'); // now $f3->CSRF holds the token
$f3->copy('CSRF','SESSION.csrf');// the variable name is up to you
// HTML form:
//
// On submission:
if ($f3->get('POST.token')!=$f3->get('SESSION.csrf')) {
// CSRF attack detected
}
```
--------------------------------
### Web Request API
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/web/main.md
Allows sending HTTP requests to a server. Supports various options for configuring the request, including method, headers, timeouts, and proxies. Examples for GET, POST, and PUT requests are provided.
```APIDOC
## Web Request API
### Description
Performs an HTTP request to a specified URL with optional configuration.
### Method
`request(string $url, array $options = NULL)`
### Parameters
#### Path Parameters
* **url** (string) - Required - The URL to send the request to.
* **options** (array) - Optional - An array of options to configure the request. This can include:
* `timeout` (int) - Request timeout in seconds.
* `header` (array) - An array of headers to send with the request.
* `proxy` (string) - Proxy server to use for the request (protocols: http, https, socks4, socks4a, socks5, socks5h).
* `method` (string) - HTTP method (e.g., 'GET', 'POST', 'PUT').
* `content` (string) - The content to send in the request body.
### Request Example
**GET Request:**
```php
$url = 'http://www.mydomain.com/index.php?parameter1=value1¶meter2=value2';
$options = array('method' => 'GET');
$result = Web::instance()->request($url, $options);
```
**POST Request:**
```php
$url = 'http://www.mydomain.com/index.php';
$postVars = array(
'parameter1' => 'value1',
'parameter2' => 'value2'
);
$options = array(
'method' => 'POST',
'content' => http_build_query($postVars)
);
$result = Web::instance()->request($url, $options);
```
**PUT Request:**
```php
$f3 = \Base::instance();
$web = \Web::instance();
$url = 'http://www.mydomain.com/upload/';
$file = '/path/to/myFile.zip';
$options = array(
'method' => 'PUT',
'content' => $f3->read($file),
'header' => array('Content-Type: '.$web->mime($file))
);
$result = $web->request($url, $options);
```
### Response
#### Success Response (200)
Returns an array with the following keys:
* **body** (string) - The response body content.
* **headers** (array) - An array of response headers.
* **engine** (string) - The engine used for the request (e.g., 'cURL').
* **cached** (bool) - Indicates if the response was served from cache.
* **error** (string) - An empty string if no error occurred, otherwise contains error message.
#### Response Example
```json
{
"body": "IMAGE BINARY DATA",
"headers": [
"HTTP/1.1 200 OK",
"Server: nginx",
"Date: Thu, 18 Dec 2013 12:40:11 GMT",
"Content-Type: image/jpeg",
"Content-Length: 7761",
"Connection: close",
"Keep-Alive: timeout=3",
"Last-Modified: Fri, 22 Mar 2013 09:41:02 GMT",
"ETag: \"514c272e-1e51\"",
"X-UPSTREAM: www1.golem.de",
"Expires: Sun, 18 Jan 2014 12:40:11 GMT",
"Cache-Control: max-age=2678400",
"X-Cache-Status: HIT",
"Accept-Ranges: bytes"
],
"engine": "cURL",
"cached": false,
"error": ""
}
```
```
--------------------------------
### SMTP Instantiation
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/smtp/main.md
Provides details on how to instantiate the SMTP class with host, port, scheme, username, and password.
```APIDOC
## SMTP Instantiation
### Description
Instantiates the SMTP class, preparing it to send emails.
### Method
`__construct(string $host, int $port, string $scheme, string $user, string $pw)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```php
$smtp_ssl = new SMTP('smtp.example.com', 465, 'ssl', 'user@example.com', 'password');
$smtp_tls = new SMTP('smtp.example.com', 587, 'tls', 'user@example.com', 'password');
```
### Response
None (Constructor)
```
--------------------------------
### PHP Template Engine Language Variable Example for F3
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/views-and-templates/main.md
Shows how to display multilingual strings using PHP as the template engine within F3. It uses `$f3->get()` to retrieve translated strings and formatted values.
```php
```
--------------------------------
### Emulating Web Routes from CLI
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/routing-engine/main.md
Demonstrates how to execute specific web routes from the command line using the `php index.php` command. Supports passing arguments and query strings, which are converted into an emulated HTTP GET request.
```bash
cd /path/to/test/suite
php index.php /my-awesome-route
php index.php /my-awesome-route?foo=bar
```
--------------------------------
### Direct Field Access Example - PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/sql-mapper/main.md
Illustrates how to set and get field values using direct property access ($mapper->foo = 'bar') and ArrayAccess ($mapper['foo'] = 'bar'), leveraging the Magic and ArrayAccess interfaces.
```php
$mapper->foo = 'bar';
$mapper['foo'] = 'bar';
```
--------------------------------
### Setup Pingback Listener (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/pingback/main.md
The listen method sets up an XML-RPC listener. It requires a callback function to handle incoming pings, checks if the local page is pingback-enabled, verifies source content, and returns an XML-RPC response on success or failure.
```php
string listen ( callback $func [ , string $path = NULL ] )
```
```php
// Success
die(xmlrpc_encode_request(NULL,$source,$options));
```
```php
// No link to local page found in request body
die(xmlrpc_encode_request(NULL,0x11,$options));
```
```php
// Source failure: web request failed or received doc malformed
die(xmlrpc_encode_request(NULL,0x10,$options));
```
```php
// Local page doesn't exist or is not pingback-enabled
die(xmlrpc_encode_request(NULL,0x21,$options));
```
```php
// Access denied: request method is not 'pingback.ping' or request malformed
die(xmlrpc_encode_request(NULL,0x31,$options));
```
```php
// the callback function called by the listen() function. Takes 2 parameters
function pingCallBackHandler($sourceURL, $reqBody) {
$logger = new Log('pings.log');
$logger->write('Incoming ping from '.$sourceURL);
// any processing on the $reqBody
$logger->write('Request body length is '.
\UTF::instance()->strlen($reqBody));
}
// a route as an example, e.g.
$f3->route('GET /listener','PingListener');
// the function to bind to the listener:
function PingListener($f3, $params) {
$pingback = new \Web\Pingback;
// bind it with our custom callback function
$pingback->listen('pingCallBackHandler');
return;
}
```
--------------------------------
### PHP: Custom Filter with Additional Parameters
Source: https://github.com/f3-factory/f3com-data/blob/master/3.8/extended-templating/main.md
Illustrates how to create a custom filter that accepts additional parameters beyond the main value. This example demonstrates a 'crop' filter that limits the length of the output string.
```php
function crop($val,$len) {
return substr($val,0,$len);
}
```
--------------------------------
### Instantiate SQL Mapper - PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/sql-mapper/main.md
Demonstrates how to instantiate the SQL Mapper with a database connection and table name. It also shows how to create a model class extending the Mapper and load a record.
```php
$mapper = new \DB\SQL\Mapper(\$db, 'tablename' [, array|string $fields = NULL [, int $ttl = 60 ]] )
$f3->set('DB',new DBSQL('sqlite:db/database.sqlite'));
class User extends \DB\SQL\Mapper {
public function __construct() {
parent::__construct( \Base::instance()->get('DB'), 'users' );
}
}
$user = new User();
$user->load('id = 1');
```
--------------------------------
### Get Jig Profiler Log (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.8/jig/main.md
Retrieves the contents of the Jig profiler log. This log includes any entries added via the jot() method, prefixed with timestamps. The example shows jotting a message and then printing the log.
```php
string log ( )
// Example:
$db->jot('Merry Christmas');
echo $db->log(); // "Wed, 25 Dec 2013 08:27:58 +0100 Merry Christmas"
```
--------------------------------
### Get UTF-8 Byte Order Mark in PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/utf-unicode-string-manager/main.md
Returns the UTF-8 byte order mark (BOM) Unicode character. This is used to signal byte order and encoding. The BOM is optional and should appear at the start of a stream.
```php
string bom ( )
$bom = \UTF::instance()->bom(); // $bom = 0xefbbbf
echo '0x'.dechex(ord($bom[0])).dechex(ord($bom[1])).dechex(ord($bom[2])); // displays '0xefbbbf'
// convert/save a file with a BOM at its beginning
$f3->write( $filename, $bom . $f3->read($filename) );
```
--------------------------------
### Instantiate Bcrypt
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/bcrypt/main.md
Creates an instance of the Bcrypt class for password hashing operations. This is the starting point for using the Bcrypt plugin's functionalities.
```php
$crypt = \Bcrypt::instance();
```
--------------------------------
### Web Class Instantiation
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/web/main.md
Demonstrates how to get an instance of the Web class. The Web class uses a Prefab factory pattern, ensuring a single instance is available throughout the application.
```APIDOC
## Web Class Instantiation
### Description
Get an instance of the Web class. This class utilizes the Prefab factory, ensuring that only one instance of the class is available at any given time.
### Method
Instantiation (static method)
### Endpoint
N/A
### Parameters
None
### Request Example
```php
$web = \Web::instance();
```
### Response
Returns an instance of the Web class.
### Response Example
```php
// $web variable now holds an instance of the Web class
```
```
--------------------------------
### Event Handlers Example (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/cursor/main.md
Demonstrates how to use event handlers within a custom mapper class. It shows how to safely access and modify mapper fields using `get` and `set` methods to avoid unpredictable behavior.
```php
class Model extends \DB\SQL\Mapper {
function __construct(){
parent::__construct(\"DB\",'test_model');
$this->beforeinsert(function($self){
$self->source='bar'; // fails due to protected property named 'source'
$self->set('source','bar'); // works - just use the setter directly
});
}}
```
--------------------------------
### Navigating and Querying Records with DBSQLMapper in PHP
Source: https://github.com/f3-factory/f3com-data/blob/master/3.7/databases/main.md
This PHP example shows how to load records based on criteria using `DBSQLMapper`, including parameterized queries and database-agnostic syntax for different drivers like MongoDB and Jig. It also demonstrates navigation methods like `skip()`, `next()`, `prev()`, and checking result set boundaries with `dry()`.
```php
$user=new DB\SQL\Mapper($db,'users');
$user->load('visits>3');
// Rewritten as a parameterized query
$user->load(array('visits>?',3));
// For MongoDB users:
// $user=new DB\Mongo\Mapper($db,'users');
// $user->load(array('visits'=>array('$gt'=>3)));
// If you prefer Jig:
// $user=new DB\Jig\Mapper($db,'users');
// $user->load('@visits>?',3);
// Display the userID of the first record that matches the criteria
echo $user->userID;
// Go to the next record that matches the same criteria
$user->skip(); // Same as $user->skip(1);
// Back to the first record
$user->skip(-1);
// Move three records forward
$user->skip(3);
// Use $user->next() as a substitute for $user->skip()
// Use $user->prev() as a substitute for $user->skip(-1)
// Check if maneuvered beyond limits
$user->dry();
```
--------------------------------
### POST /listen
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/pingback/main.md
Sets up an XML-RPC listener to receive pingbacks, verify the source, and process the ping using a callback function.
```APIDOC
## POST /listen
### Description
Receive ping, check if local page is pingback-enabled, verify source contents, and return XML-RPC response. This function allows you to setup a XML-RPC listener. You need to define a F3 route and bind it to this function.
### Method
POST
### Endpoint
`/listen`
### Parameters
#### Path Parameters
None
#### Query Parameters
- **path** (string) - Optional - If not provided, the value of the BASE system variable is used.
#### Request Body
- **func** (callback) - Required - The name of your callback function to use to handle the request/ping.
- **source** (string) - Required - The URL of the source.
### Request Example
```php
// Assuming a route is set up and bound to a handler function that calls listen()
// The callback function called by the listen() function.
function pingCallBackHandler($sourceURL, $reqBody) {
$logger = new Log('pings.log');
$logger->write('Incoming ping from '.$sourceURL);
// any processing on the $reqBody
$logger->write('Request body length is '.
\UTF::instance()->strlen($reqBody));
}
// The function to bind to the listener:
function PingListener($f3, $params) {
$pingback = new \Web\Pingback;
// bind it with our custom callback function
$pingback->listen('pingCallBackHandler');
return;
}
// Example route binding:
$f3->route('POST /my-pingback-endpoint', 'PingListener');
```
### Response
#### Success Response (200)
Returns an XML-RPC encoded response on success. The exact content depends on the success of the callback function and the `xmlrpc_encode_request` function.
#### Response Example
```xml
Success message or null
```
#### Error Responses
- **0x11**: No link to local page found in request body.
- **0x10**: Source failure: web request failed or received doc malformed.
- **0x21**: Local page doesn't exist or is not pingback-enabled.
- **0x31**: Access denied: request method is not 'pingback.ping' or request malformed.
These errors are returned as XML-RPC encoded responses using `xmlrpc_encode_request`.
```
--------------------------------
### Register WebSocket Event Handler (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.9/websocket/main.md
Demonstrates how to register a callback function for a specific WebSocket event. The 'on' method binds a callable to an event name, replacing any existing handlers for that event. The example shows registering a handler for the 'start' event.
```php
$server->on('start', function(){
echo 'Server started';
});
```
--------------------------------
### Setup Pingback Listener (PHP)
Source: https://github.com/f3-factory/f3com-data/blob/master/3.6/pingback/main.md
Sets up a XML-RPC listener by binding it to an F3 route. This function receives pingbacks, verifies the local page's pingback enablement and source content, and uses a callback function to process the ping. It returns an XML-RPC response or an error code.
```php
string listen ( callback $func [ , string $path = NULL ] )
```
```php
// Success
die(xmlrpc_encode_request(NULL,$source,$options));
```
```php
die(xmlrpc_encode_request(NULL,0x11,$options)); // No link to local page found in request body
```
```php
die(xmlrpc_encode_request(NULL,0x10,$options)); // Source failure: web request failed or received doc malformed
```
```php
die(xmlrpc_encode_request(NULL,0x21,$options)); // Local page doesn't exist or is not pingback-enabled
```
```php
die(xmlrpc_encode_request(NULL,0x31,$options)); // Access denied: request method is not 'pingback.ping' or request malformed
```
```php
// the callback function called by the listen() function. Takes 2 parameters
function pingCallBackHandler($sourceURL, $reqBody) {
$logger = new Log('pings.log');
$logger->write('Incoming ping from '.$sourceURL);
// any processing on the $reqBody
$logger->write('Request body length is '.
\UTF::instance()->strlen($reqBody));
}
// a route as an example, e.g.
$f3->route('GET /listener','PingListener');
// the function to bind to the listener:
function PingListener($f3, $params) {
$pingback = new \Web\Pingback;
// bind it with our custom callback function
$pingback->listen('pingCallBackHandler');
return;
}
```
--------------------------------
### XML View Template Example
Source: https://github.com/f3-factory/f3com-data/blob/master/3.8/view/main.md
An XML view template designed for generating sitemaps, iterating over URLs and formatting them within the sitemap XML structure.
```xml
```
--------------------------------
### Preview Token Method Example
Source: https://github.com/f3-factory/f3com-data/blob/master/3.5/preview/main.md
Demonstrates the `token` method, which converts a template token like `My {{@color}} car looks nice` into a PHP string with variable interpolation syntax, resulting in `My $color car looks nice`.
```php
echo $template->token ('My {{@color}} car looks nice');
```