### AI Initialization Prompt Example
Source: https://docs.flightphp.com/en/v3/single-page
Example output showing the interactive setup process for LLM credentials.
```text
Welcome to AI Init!
Which LLM API do you want to use? [1] openai, [2] grok, [3] claude: 1
Enter the base URL for the LLM API [https://api.openai.com]:
Enter your API key for openai: sk-...
Enter the model name you want to use (e.g. gpt-4, claude-3-opus, etc) [gpt-4o]:
Credentials saved to .runway-creds.json
```
--------------------------------
### Install via Composer
Source: https://docs.flightphp.com/en/v3/single-page
Command to install the library.
```bash
composer require flightphp/active-record
```
--------------------------------
### Install Simple Job Queue
Source: https://docs.flightphp.com/en/v3/single-page
Install the job queue library via Composer.
```bash
composer require n0nag0n/simple-job-queue
```
--------------------------------
### Basic Flight PHP Application Setup
Source: https://docs.flightphp.com/en/v3
A minimal Flight PHP application demonstrating route definition and starting the application. Ensure you have the autoloader or Flight.php included.
```php
'world'
]);
});
Flight::start();
```
--------------------------------
### Basic Usage and Example Routes
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates how to register the session service and use it within Flight routes for setting, getting, and clearing session data.
```APIDOC
## Basic Usage
Here’s a simple example of how to use the `flightphp/session` plugin in your Flight application:
```php
require 'vendor/autoload.php';
use flight\Session;
$app = Flight::app();
// Register the session service
$app->register('session', Session::class);
// Example route with session usage
Flight::route('/login', function() {
$session = Flight::session();
$session->set('user_id', 123);
$session->set('username', 'johndoe');
$session->set('is_admin', false);
echo $session->get('username'); // Outputs: johndoe
echo $session->get('preferences', 'default_theme'); // Outputs: default_theme
if ($session->get('user_id')) {
Flight::json(['message' => 'User is logged in!', 'user_id' => $session->get('user_id')]);
}
});
Flight::route('/logout', function() {
$session = Flight::session();
$session->clear(); // Clear all session data
Flight::json(['message' => 'Logged out successfully']);
});
Flight::start();
```
### Key Points
* **Non-Blocking** : Uses `read_and_close` for session start by default, preventing session locking issues.
* **Auto-Commit** : Enabled by default, so changes are saved automatically on shutdown unless disabled.
* **File Storage** : Sessions are stored in the system temp directory under `/flight_sessions` by default.
```
--------------------------------
### Install PHP on Ubuntu
Source: https://docs.flightphp.com/en/v3/install
Install the default or a specific version of PHP via apt.
```bash
sudo apt install php
```
```bash
sudo apt install php8.1
```
--------------------------------
### Self-host the MCP server
Source: https://docs.flightphp.com/en/v3/single-page
Commands to clone, install dependencies, and start the MCP server instance.
```bash
git clone https://github.com/flightphp/mcp.git
cd mcp
composer install
php server.php
```
--------------------------------
### Installation
Source: https://docs.flightphp.com/en/v3/single-page
Install the ActiveRecord library using Composer.
```APIDOC
## Installation
Simply install with Composer
```bash
composer require flightphp/active-record
```
```
--------------------------------
### Install Migration Tools
Source: https://docs.flightphp.com/en/v3/single-page
Commands to install the migration library or CLI tool via Composer.
```bash
composer require "byjg/migration"
```
```bash
composer require "byjg/migration-cli"
```
--------------------------------
### Install Composer locally
Source: https://docs.flightphp.com/en/v3/single-page
Downloads the Composer installer and executes it with PHP to create a local composer.phar file.
```bash
$ curl -sS https://getcomposer.org/installer | php
```
--------------------------------
### Install Flight PHP Skeleton App with Composer
Source: https://docs.flightphp.com/en/v3
Use Composer to create a new project based on the Flight PHP skeleton. This provides a structured starting point with pre-configured files.
```bash
# Create the new project
composer create-project flightphp/skeleton my-project/
# Enter your new project directory
cd my-project/
# Bring up the local dev-server to get started right away!
composer start
```
--------------------------------
### Traditional Script-Based Routing Example
Source: https://docs.flightphp.com/en/v3/single-page
Illustrates a less organized, script-by-script approach to handling different URLs and their associated actions using GET parameters. This method can become difficult to manage as the application grows.
```php
// /user/view_profile.php?id=1234
if ($_GET['id']) {
$id = $_GET['id'];
viewUserProfile($id);
}
// /user/edit_profile.php?id=1234
if ($_GET['id']) {
$id = $_GET['id'];
editUserProfile($id);
}
// etc...
```
--------------------------------
### Example AI Configuration Prompt
Source: https://docs.flightphp.com/en/v3/single-page
An example of the interactive terminal session used to define project characteristics for AI instruction generation.
```text
Please describe what your project is for? My awesome API
What database are you planning on using? MySQL
What HTML templating engine will you plan on using (if any)? latte
Is security an important element of this project? (y/n) y
...
AI instructions updated successfully.
```
--------------------------------
### Install Flight Skeleton
Source: https://docs.flightphp.com/en/v3/install
Creates a new project with a pre-configured structure, autoloading, and tools.
```bash
composer create-project flightphp/skeleton my-project/
```
--------------------------------
### APM Configuration Example
Source: https://docs.flightphp.com/en/v3/single-page
An example of the .runway-config.json file generated after running the initialization wizard. It specifies source and destination database DSNs.
```json
{
"apm": {
"source_type": "sqlite",
"source_db_dsn": "sqlite:/tmp/apm_metrics.sqlite",
"storage_type": "sqlite",
"dest_db_dsn": "sqlite:/tmp/apm_metrics_processed.sqlite"
}
}
```
--------------------------------
### Initialize and run database migrations
Source: https://docs.flightphp.com/en/v3/single-page
Example of setting up a connection, registering a database driver, and executing reset or update commands.
```php
addCallbackProgress(function ($action, $currentVersion, $fileInfo) {
echo "$action, $currentVersion, ${fileInfo['description']}\n";
});
// Restore the database using the "base.sql" script
// and run ALL existing scripts for up the database version to the latest version
$migration->reset();
// Run ALL existing scripts for up or down the database version
// from the current version until the $version number;
// If the version number is not specified migrate until the last database version
$migration->update($version = null);
```
--------------------------------
### Install PHP on Rocky Linux
Source: https://docs.flightphp.com/en/v3/single-page
Commands to configure repositories and install PHP versions using dnf.
```bash
sudo dnf install epel-release
```
```bash
sudo dnf install https://rpms.remirepo.net/enterprise/remi-release-8.rpm
sudo dnf module reset php
```
```bash
sudo dnf install php
```
```bash
sudo dnf module install php:remi-7.4
```
```bash
sudo dnf module reset php
sudo dnf module enable php:remi-8.0
sudo dnf install php
```
```bash
php -v
```
--------------------------------
### Install Swoole extension
Source: https://docs.flightphp.com/en/v3/single-page
Commands to install the required Swoole extension for asynchronous execution.
```bash
# using pecl
pecl install swoole
# or openswoole
pecl install openswoole
# or with a package manager (Debian/Ubuntu example)
sudo apt-get install php-swoole
```
--------------------------------
### Full Database Operations Example
Source: https://docs.flightphp.com/en/v3/single-page
A comprehensive example within a FlightPHP route demonstrating various database operations including fetching all rows, streaming results, fetching a single row, fetching a single value, using IN() placeholders, inserting, updating, deleting, and getting affected row counts.
```php
Flight::route('/users', function () {
// Get all users
$users = Flight::db()->fetchAll('SELECT * FROM users');
// Stream all users
$statement = Flight::db()->runQuery('SELECT * FROM users');
while ($user = $statement->fetch()) {
echo $user['name'];
}
// Get a single user
$user = Flight::db()->fetchRow('SELECT * FROM users WHERE id = ?', [123]);
// Get a single value
$count = Flight::db()->fetchField('SELECT COUNT(*) FROM users');
// Special IN() syntax
$users = Flight::db()->fetchAll('SELECT * FROM users WHERE id IN (?)', [[1,2,3,4,5]]);
$users = Flight::db()->fetchAll('SELECT * FROM users WHERE id IN (?)', ['1,2,3,4,5']);
// Insert a new user
Flight::db()->runQuery("INSERT INTO users (name, email) VALUES (?, ?)", ['Bob', 'bob@example.com']);
$insert_id = Flight::db()->lastInsertId();
// Update a user
Flight::db()->runQuery("UPDATE users SET name = ? WHERE id = ?", ['Bob', 123]);
// Delete a user
Flight::db()->runQuery("DELETE FROM users WHERE id = ?", [123]);
// Get the number of affected rows
$statement = Flight::db()->runQuery("UPDATE users SET name = ? WHERE name = ?", ['Bob', 'Sally']);
$affected_rows = $statement->rowCount();
});
```
--------------------------------
### Layout Template Files
Source: https://docs.flightphp.com/en/v3/single-page
Example structure for header, body, and layout files.
```php
= $heading ?>
```
```php
= $body ?>
```
```php
= $title ?>
= $headerContent ?>
= $bodyContent ?>
```
--------------------------------
### Install CommentTemplate Package
Source: https://docs.flightphp.com/en/v3/single-page
Install the CommentTemplate templating engine using Composer.
```bash
composer require knifelemon/comment-template
```
--------------------------------
### Full Database Usage Example
Source: https://docs.flightphp.com/en/v3/single-page
A comprehensive example showcasing various database operations including fetching all rows, fetching a single row, inserting, updating, and deleting records.
```APIDOC
## Full Database Example
### Description
Demonstrates a wide range of database operations within a Flight route.
### Method
Various methods from `flight\database\PdoWrapper` are used.
### Endpoint
`/users` (Example route)
### Parameters
None for the route itself, but methods use parameters as shown.
### Request Example
```php
Flight::route('/users', function () {
// Get all users
$users = Flight::db()->fetchAll('SELECT * FROM users');
// Stream all users
$statement = Flight::db()->runQuery('SELECT * FROM users');
while ($user = $statement->fetch()) {
echo $user['name'];
}
// Get a single user
$user = Flight::db()->fetchRow('SELECT * FROM users WHERE id = ?', [123]);
// Get a single value
$count = Flight::db()->fetchField('SELECT COUNT(*) FROM users');
// Special IN() syntax
$users = Flight::db()->fetchAll('SELECT * FROM users WHERE id IN (?)', [[1,2,3,4,5]]);
$users = Flight::db()->fetchAll('SELECT * FROM users WHERE id IN (?)', ['1,2,3,4,5']);
// Insert a new user
Flight::db()->runQuery("INSERT INTO users (name, email) VALUES (?, ?)", ['Bob', 'bob@example.com']);
$insert_id = Flight::db()->lastInsertId();
// Update a user
Flight::db()->runQuery("UPDATE users SET name = ? WHERE id = ?", ['Bob', 123]);
// Delete a user
Flight::db()->runQuery("DELETE FROM users WHERE id = ?", [123]);
// Get the number of affected rows
$statement = Flight::db()->runQuery("UPDATE users SET name = ? WHERE name = ?", ['Bob', 'Sally']);
$affected_rows = $statement->rowCount();
});
```
### Response
Responses vary depending on the operation. For example, fetching users returns an array of Collections. Insert operations return the last inserted ID. Update/Delete operations can provide the row count.
```
--------------------------------
### APM System with Before and After Hooks
Source: https://docs.flightphp.com/en/v3/single-page
Implement a basic Application Performance Monitoring system by recording request start time before starting and logging the duration after completion.
```php
// In your services.php file
Flight::before('start', function() {
Flight::set('start_time', microtime(true));
});
Flight::after('start', function() {
$end = microtime(true);
$start = Flight::get('start_time');
Flight::log()->info('Request '.Flight::request()->url.' took ' . round($end - $start, 4) . ' seconds');
// You could also add your request or response headers
// to log them as well (be careful as this would be a
// lot of data if you have a lot of requests)
Flight::log()->info('Request Headers: ' . json_encode(Flight::request()->headers));
Flight::log()->info('Response Headers: ' . json_encode(Flight::response()->headers));
});
```
--------------------------------
### Install PHP on Ubuntu
Source: https://docs.flightphp.com/en/v3/single-page
Commands to update packages, install PHP, and manage versions on Ubuntu systems.
```bash
sudo apt update
```
```bash
sudo apt install php
```
```bash
sudo apt install php8.1
```
```bash
sudo apt install php8.1-mysql
```
```bash
sudo update-alternatives --set php /usr/bin/php8.1
```
```bash
php -v
```
--------------------------------
### Run Built-in Server
Source: https://docs.flightphp.com/en/v3/single-page
Start the PHP development server pointing to the public directory.
```bash
php -S localhost:8000 -t public/
```
--------------------------------
### Runway CLI Installation
Source: https://docs.flightphp.com/en/v3/single-page
Instructions on how to install the Runway CLI application for managing FlightPHP applications.
```APIDOC
## Installation
### Description
Install the Runway CLI application using composer.
### Method
Composer
### Command
```bash
composer require flightphp/runway
```
```
--------------------------------
### Install Homebrew
Source: https://docs.flightphp.com/en/v3/install
Installs the Homebrew package manager on macOS.
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
--------------------------------
### Install Async plugin
Source: https://docs.flightphp.com/en/v3/single-page
Composer command to add the async package to a Flight project.
```bash
composer require flightphp/async
```
--------------------------------
### Install PHP on Rocky Linux
Source: https://docs.flightphp.com/en/v3/install
Install the default PHP version or a specific version from the Remi module.
```bash
sudo dnf install php
```
```bash
sudo dnf module install php:remi-7.4
```
--------------------------------
### Install PHP via Homebrew
Source: https://docs.flightphp.com/en/v3/install
Commands to install and manage PHP versions on macOS.
```bash
brew install php
```
```bash
brew tap shivammathur/php
brew install shivammathur/php/php@8.1
```
```bash
brew unlink php
brew link --overwrite --force php@8.1
```
```bash
php -v
```
--------------------------------
### Run Built-in PHP Server
Source: https://docs.flightphp.com/en/v3/install
Starts the local development server for testing the application.
```bash
php -S localhost:8000
# or with the skeleton app
composer start
```
```bash
php -S localhost:8000 -t public/
# with the skeleton app, this is already configured
composer start
```
--------------------------------
### Install PHP Modules on Ubuntu
Source: https://docs.flightphp.com/en/v3/install
Add specific extensions like MySQL support to an existing PHP installation.
```bash
sudo apt install php8.1-mysql
```
--------------------------------
### Install Supervisord
Source: https://docs.flightphp.com/en/v3/single-page
Commands to install the supervisor process control system on various Linux distributions and macOS.
```bash
# On Ubuntu/Debian
sudo apt-get install supervisor
# On CentOS/RHEL
sudo yum install supervisor
# On macOS with Homebrew
brew install supervisor
```
--------------------------------
### Install overclokk/cookie
Source: https://docs.flightphp.com/en/v3/single-page
Use composer to install the overclokk/cookie library for managing cookies.
```bash
composer require overclokk/cookie
```
--------------------------------
### Model Definition Example
Source: https://docs.flightphp.com/en/v3/single-page
Example of how to define an ActiveRecord class for a 'users' table, including property type hints.
```APIDOC
## Basic Example
Let's assume you have the following table:
```sql
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
password TEXT
);
```
Now you can setup a new class to represent this table:
```php
/**
* An ActiveRecord class is usually singular
*
* It's highly recommended to add the properties of the table as comments here
*
* @property int $id
* @property string $name
* @property string $password
*/
class User extends flight\ActiveRecord {
public function __construct($database_connection)
{
// you can set it this way
parent::__construct($database_connection, 'users');
// or this way
parent::__construct($database_connection, null, [ 'table' => 'users']);
}
}
```
```
--------------------------------
### Install Ghostff/Session with Composer
Source: https://docs.flightphp.com/en/v3/single-page
Use Composer to install the Ghostff/Session plugin. This is the standard method for adding the library to your PHP project.
```bash
composer require ghostff/session
```
--------------------------------
### FlightPHP Async Package - Swoole Example
Source: https://docs.flightphp.com/en/v3/single-page
A quick example demonstrating how to use the FlightPHP Async package with Swoole for asynchronous request handling.
```APIDOC
## FlightPHP Async Package with Swoole
### Description
This section provides a minimal setup example for using the FlightPHP Async package with Swoole, allowing the same codebase to run with both PHP-FPM and Swoole.
### Requirements
- PHP 7.4 or higher
- Flight framework 3.16.1 or higher
- Swoole extension
### Installation
Install via composer:
```bash
composer require flightphp/async
```
Install Swoole extension (example using pecl):
```bash
pecl install swoole
# or openswoole
pecl install openswoole
```
### Example Files
#### `index.php` (Development Mode)
This file forces the application to run in PHP mode for development.
```php
route('/', function() use ($app) {
$app->json(['hello' => 'world']);
});
if (!defined('NOT_SWOOLE')) {
// Require the SwooleServerDriver class when running in Swoole mode.
require_once __DIR__ . '/SwooleServerDriver.php';
Swoole\Runtime::enableCoroutine();
$Swoole_Server = new SwooleServerDriver('127.0.0.1', 9501, $app);
$Swoole_Server->start();
} else {
$app->start();
}
```
#### `SwooleServerDriver.php`
(Content of `SwooleServerDriver.php` is assumed to be present and handles Swoole server logic.)
```
--------------------------------
### Install Tracy Debugger
Source: https://docs.flightphp.com/en/v3/single-page
Installs the Tracy Debugger library using Composer. This is a prerequisite for using the Tracy integration features.
```bash
composer require tracy/tracy
```
--------------------------------
### Install EasyQuery with Composer
Source: https://docs.flightphp.com/en/v3/single-page
Use Composer to add the EasyQuery library to your project dependencies.
```bash
composer require knifelemon/easy-query
```
--------------------------------
### Identify common output buffering pitfalls
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates potential errors when echoing content before or after the framework's start hook.
```php
// index.php
require 'vendor/autoload.php';
// just an example
define('START_TIME', microtime(true));
function hello() {
echo 'Hello World';
}
Flight::map('hello', 'hello');
Flight::after('hello', function(){
// this will actually be fine
echo 'This Hello World phrase was brought to you by the letter "H"
';
});
Flight::before('start', function(){
// things like this will cause an error
echo 'My Page';
});
Flight::route('/', function(){
// this is actually just fine
echo 'Hello World';
// This should be just fine as well
Flight::hello();
});
Flight::after('start', function(){
// this will cause an error
echo 'Your page loaded in '.(microtime(true) - START_TIME).' seconds
';
});
```
--------------------------------
### Install Composer globally
Source: https://docs.flightphp.com/en/v3/single-page
Moves the local composer.phar file to a system-wide directory and makes it executable.
```bash
$ mv composer.phar /usr/local/bin/composer
$ chmod +x composer
```
--------------------------------
### Create a Production-Ready Worker Script
Source: https://docs.flightphp.com/en/v3/single-page
A robust worker script example that includes logging and error handling for production environments.
```php
addQueueConnection($PDO);
// Set the pipeline to watch
$Job_Queue->watchPipeline('send_important_emails');
// Log start of worker
echo date('Y-m-d H:i:s') . " - Worker started\n";
while(true) {
$job = $Job_Queue->getNextJobAndReserve();
if(empty($job)) {
usleep(500000); // Sleep for 0.5 seconds
continue;
}
echo date('Y-m-d H:i:s') . " - Processing job {$job['id']}\n";
$payload = json_decode($job['payload'], true);
try {
$result = doSomethingThatDoesSomething($payload);
if($result === true) {
$Job_Queue->deleteJob($job);
echo date('Y-m-d H:i:s') . " - Job {$job['id']} completed successfully\n";
} else {
$Job_Queue->buryJob($job);
echo date('Y-m-d H:i:s') . " - Job {$job['id']} failed, buried\n";
}
} catch(Exception $e) {
$Job_Queue->buryJob($job);
echo date('Y-m-d H:i:s') . " - Exception processing job {$job['id']}: {$e->getMessage()}\n";
}
}
```
--------------------------------
### Example of Filtering a Custom Method
Source: https://docs.flightphp.com/en/v3/single-page
This example demonstrates mapping a custom method, adding before and after filters to modify its parameters and output, and then invoking the method.
```php
// Map a custom method
Flight::map('hello', function (string $name) {
return "Hello, $name!";
});
// Add a before filter
Flight::before('hello', function (array &$params, string &$output): bool {
// Manipulate the parameter
$params[0] = 'Fred';
return true;
});
// Add an after filter
Flight::after('hello', function (array &$params, string &$output): bool {
// Manipulate the output
$output .= " Have a nice day!";
return true;
});
// Invoke the custom method
echo Flight::hello('Bob');
```
--------------------------------
### Basic Flight Route Example
Source: https://docs.flightphp.com/en/v3/single-page
Defines a simple GET route that returns a JSON response. This is a fundamental example for setting up routes in Flight PHP.
```php
Flight::route('GET /api/hello', function() {
Flight::json(['message' => 'Hello World!']);
});
```
--------------------------------
### Start Dashboard on Custom Port
Source: https://docs.flightphp.com/en/v3/single-page
If the default port 8001 is in use, you can start the dashboard on a different port using the `--port` option. This example uses port 8080.
```bash
--port 8080
```
--------------------------------
### Initialize Project Directory
Source: https://docs.flightphp.com/en/v3/single-page
Commands to create the project folder and navigate into it.
```bash
mkdir flight-blog
cd flight-blog
```
--------------------------------
### Install Latte Template Engine
Source: https://docs.flightphp.com/en/v3/single-page
Use Composer to add the Latte library to your project dependencies.
```bash
composer require latte/latte
```
--------------------------------
### Configure Multiple Pipelines
Source: https://docs.flightphp.com/en/v3/single-page
Example of defining multiple worker programs in a single Supervisord configuration file.
```ini
[program:email_worker]
command=php /path/to/email_worker.php
# ... other configs ...
[program:notification_worker]
command=php /path/to/notification_worker.php
# ... other configs ...
```
--------------------------------
### Create Public Directory
Source: https://docs.flightphp.com/en/v3/single-page
Create the web root directory for the application entry point.
```bash
mkdir public
```
--------------------------------
### Basic Session Usage in FlightPHP
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates registering the session service and using it within routes to set, get, and clear session data. Includes examples for login and logout functionality.
```php
require 'vendor/autoload.php';
use flight\Session;
$app = Flight::app();
// Register the session service
$app->register('session', Session::class);
// Example route with session usage
Flight::route('/login', function() {
$session = Flight::session();
$session->set('user_id', 123);
$session->set('username', 'johndoe');
$session->set('is_admin', false);
echo $session->get('username'); // Outputs: johndoe
echo $session->get('preferences', 'default_theme'); // Outputs: default_theme
if ($session->get('user_id')) {
Flight::json(['message' => 'User is logged in!', 'user_id' => $session->get('user_id')]);
}
});
Flight::route('/logout', function() {
$session = Flight::session();
$session->clear(); // Clear all session data
Flight::json(['message' => 'Logged out successfully']);
});
Flight::start();
```
--------------------------------
### Middleware Example: Session Authentication
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates how to protect routes using session-based authentication with the FlightPHP Session plugin.
```APIDOC
## POST /admin
### Description
Protect routes with session-based authentication.
### Method
GET
### Endpoint
/admin
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **message** (string) - Welcome message for authenticated users.
#### Response Example
```json
{
"message": "Welcome to the admin panel"
}
```
### Error Handling
- **403 Forbidden**: Access denied if the user is not authenticated as an admin.
```
--------------------------------
### Notify About New Users
Source: https://docs.flightphp.com/en/v3/single-page
This example shows how to notify users upon registration. A listener is set up to send a welcome message, triggered by the signup route. This separates user creation logic from notification tasks.
```php
// Listener for new registrations
Flight::onEvent('user.registered', function ($email, $name) {
// Simulate sending an email
echo "Email sent to $email: Welcome, $name!";
});
// Trigger it when someone signs up
Flight::route('/signup', function () {
$email = 'jane@example.com';
$name = 'Jane';
Flight::triggerEvent('user.registered', $email, $name);
echo "Thanks for signing up!";
});
```
--------------------------------
### Example Model Relationships
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates setting up HAS_MANY and HAS_ONE relationships for a User model, and BELONGS_TO relationships for a Contact model, referencing each other.
```php
class User extends ActiveRecord{
protected array $relations = [
'contacts' => [ self::HAS_MANY, Contact::class, 'user_id' ],
'contact' => [ self::HAS_ONE, Contact::class, 'user_id' ],
];
public function __construct($database_connection)
{
parent::__construct($database_connection, 'users');
}
}
class Contact extends ActiveRecord{
protected array $relations = [
'user' => [ self::BELONGS_TO, User::class, 'user_id' ],
'user_with_backref' => [ self::BELONGS_TO, User::class, 'user_id', [], 'contact' ],
];
public function __construct($database_connection)
{
parent::__construct($database_connection, 'contacts');
}
}
```
--------------------------------
### Quick Start: Build and Execute a Query
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates building a SELECT query with WHERE, ORDER BY, and LIMIT clauses, then executing it using Flight's SimplePdo. The build() method returns SQL and parameters for prepared statements.
```php
use KnifeLemon\EasyQuery\Builder;
$q = Builder::table('users')
->select(['id', 'name', 'email'])
->where(['status' => 'active'])
->orderBy('created_at DESC')
->limit(10)
->build();
// Use with Flight's SimplePdo
$users = Flight::db()->fetchAll($q['sql'], $q['params']);
```
--------------------------------
### Install FlightPHP APM
Source: https://docs.flightphp.com/en/v3/single-page
Use Composer to install the APM package.
```bash
composer require flightphp/apm
```
--------------------------------
### FlightPHP Cache Installation
Source: https://docs.flightphp.com/en/v3/single-page
Install the FlightPHP Cache module using Composer.
```APIDOC
## Installation
Install via composer:
```
composer require flightphp/cache
```
```
--------------------------------
### Initialize AI Integration
Source: https://docs.flightphp.com/en/v3/single-page
Use the CLI command to configure LLM provider credentials for the project.
```bash
php runway ai:init
```
--------------------------------
### Define Basic Routes in index.php
Source: https://docs.flightphp.com/en/v3/single-page
A standard entry point file demonstrating basic text and JSON response routing.
```php
'world'
]);
});
Flight::start();
```
--------------------------------
### Install defuse/php-encryption
Source: https://docs.flightphp.com/en/v3/single-page
Use composer to install the defuse/php-encryption library for secure data encryption.
```bash
composer require defuse/php-encryption
```
--------------------------------
### Get a Cache Value
Source: https://docs.flightphp.com/en/v3/single-page
Retrieve a cached value using the `get()` method or `refreshIfExpired()` for convenience.
```APIDOC
### Get a Cache Value
You use the `get()` method to get a cached value. If you want a convenience method that will refresh the cache if it is expired, you can use `refreshIfExpired()`.
```
// Get cache instance
$cache = Flight::cache();
$data = $cache->refreshIfExpired('simple-cache-test', function () {
return date("H:i:s"); // return data to be cached
}, 10); // 10 seconds
// or
$data = $cache->get('simple-cache-test');
if(empty($data)) {
$data = date("H:i:s");
$cache->set('simple-cache-test', $data, 10); // 10 seconds
}
```
```
--------------------------------
### Configure Repositories on Rocky Linux
Source: https://docs.flightphp.com/en/v3/install
Enable EPEL and Remi repositories to access various PHP versions.
```bash
sudo dnf install epel-release
```
```bash
sudo dnf install https://rpms.remirepo.net/enterprise/remi-release-8.rpm
sudo dnf module reset php
```
--------------------------------
### Configure index.php for development
Source: https://docs.flightphp.com/en/v3/single-page
Entry point file configured to force PHP mode for development.
```php
// index.php
createVersion();
```
--------------------------------
### Start Databases for Integration Tests
Source: https://docs.flightphp.com/en/v3/single-page
Use Docker Compose to bring up the necessary databases (PostgreSQL, MySQL, MSSQL) for running integration tests.
```bash
docker-compose up -d postgres mysql mssql
```
--------------------------------
### Initialize APM Configuration
Source: https://docs.flightphp.com/en/v3/single-page
Run this command to start the interactive wizard for creating your .runway-config.json file. It will prompt for metric sources and destinations.
```bash
php vendor/bin/runway apm:init
```
--------------------------------
### Install Firebase PHP JWT
Source: https://docs.flightphp.com/en/v3/single-page
Install the Firebase PHP JWT library using Composer. This is the first step to enable JWT functionality.
```bash
composer require firebase/php-jwt
```
--------------------------------
### Install Flight PHP Core with Composer
Source: https://docs.flightphp.com/en/v3
Use Composer to install the Flight PHP core package. This is the recommended method for managing dependencies.
```bash
composer require flightphp/core
```
--------------------------------
### Create index.php
Source: https://docs.flightphp.com/en/v3/install
Basic entry point for a Flight application.
```php
addOption('name', 'The name of the example', null);
}
```
--------------------------------
### Use Classes and Methods as Controllers
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates various ways to map routes to class methods, including static calls and object instances.
```php
class GreetingController {
public function hello() {
echo 'hello world!';
}
}
Flight::route('/', [ 'GreetingController','hello' ]);
// or
Flight::route('/', [ GreetingController::class, 'hello' ]); // preferred method
// or
Flight::route('/', [ 'GreetingController::hello' ]);
// or
Flight::route('/', [ 'GreetingController->hello' ]);
```
```php
use flight\Engine;
// GreetingController.php
class GreetingController
{
protected Engine $app
public function __construct(Engine $app) {
$this->app = $app;
$this->name = 'John Doe';
}
public function hello() {
echo "Hello, {$this->name}!";
}
}
// index.php
$app = Flight::app();
$greeting = new GreetingController($app);
Flight::route('/', [ $greeting, 'hello' ]);
```
--------------------------------
### Install FlightPHP Session Plugin
Source: https://docs.flightphp.com/en/v3/single-page
Install the FlightPHP Session plugin using Composer. This plugin provides a lightweight, file-based session handler for the Flight PHP Framework.
```bash
composer require flightphp/session
```
--------------------------------
### Install PHPUnit with Composer
Source: https://docs.flightphp.com/en/v3/single-page
Install PHPUnit as a development dependency using Composer. This command ensures that PHPUnit is available for your project's testing needs without being deployed to production.
```bash
composer require --dev phpunit/phpunit
```
--------------------------------
### Get Shared vs. New Instance
Source: https://docs.flightphp.com/en/v3/single-page
By default, `Flight::register` provides a shared instance. Pass `false` as a parameter to `Flight::db()` to get a new instance instead.
```php
// Shared instance of the class
$shared = Flight::db();
// New instance of the class
$new = Flight::db(false);
```
--------------------------------
### Install FlightPHP Runway CLI
Source: https://docs.flightphp.com/en/v3/single-page
Install the Runway CLI tool using Composer to manage your Flight applications. This tool helps with tasks like generating controllers and displaying routes.
```bash
composer require flightphp/runway
```
--------------------------------
### Run Runway CLI Commands
Source: https://docs.flightphp.com/en/v3/single-page
Execute Runway CLI commands from your project's root directory. Use `php runway [command]` for local installations or `vendor/bin/runway [command]` for package installations.
```bash
php runway
```
```bash
php runway routes --help
```
--------------------------------
### Insecure SQL Query Example (Illustrates SQL Injection Risk)
Source: https://docs.flightphp.com/en/v3/single-page
This example demonstrates a vulnerable SQL query construction that is susceptible to SQL injection. It highlights why using prepared statements is essential for security.
```php
// end user fills out a web form.
// for the value of the form, the hacker puts in something like this:
$username = "' OR 1=1; -- ";
$sql = "SELECT * FROM users WHERE username = '$username' LIMIT 5";
$users = Flight::db()->fetchAll($sql);
// After the query is build it looks like this
// SELECT * FROM users WHERE username = '' OR 1=1; -- LIMIT 5
// It looks strange, but it's a valid query that will work. In fact,
// it's a very common SQL injection attack that will return all users.
var_dump($users); // this will dump all users in the database, not just the one single username
```
--------------------------------
### Project Structure
Source: https://docs.flightphp.com/en/v3/single-page
Recommended directory layout for the blog application.
```text
flight-blog/
├── app/
│ ├── config/
│ └── views/
├── data/
├── public/
│ └── index.php
├── vendor/
└── composer.json
```
--------------------------------
### Add Security Headers using a Filter
Source: https://docs.flightphp.com/en/v3/single-page
Apply common security headers to all responses by adding them within a Flight::before('start') filter. This ensures headers are set before the application starts processing requests.
```php
// Add the headers in a filter
Flight::before('start', function() {
Flight::response()->header('X-Frame-Options', 'SAMEORIGIN');
Flight::response()->header("Content-Security-Policy", "default-src 'self'");
Flight::response()->header('X-XSS-Protection', '1; mode=block');
Flight::response()->header('X-Content-Type-Options', 'nosniff');
Flight::response()->header('Referrer-Policy', 'no-referrer-when-downgrade');
Flight::response()->header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
Flight::response()->header('Permissions-Policy', 'geolocation=()');
});
```
--------------------------------
### Define Database Schema
Source: https://docs.flightphp.com/en/v3/single-page
Example SQL schema for a users table.
```sql
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
password TEXT
);
```
--------------------------------
### Specify PHP Path
Source: https://docs.flightphp.com/en/v3/single-page
If the system cannot find your PHP executable, use the `--php-path` option to specify the correct path. This example uses `/usr/bin/php`.
```bash
--php-path /usr/bin/php
```
--------------------------------
### Verify PHP Installation
Source: https://docs.flightphp.com/en/v3/install
Check the currently active PHP version in the terminal.
```bash
php -v
```