### LLM Credentials Setup Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/ai.md
This example shows the interactive prompts and expected inputs for the `ai:init` command to configure LLM API 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 and Run Flight Documentation
Source: https://github.com/flightphp/docs/blob/master/README.md
Commands to clone the repository, install dependencies, and start the local development server.
```bash
# Clone the repo
git clone https://github.com/flightphp/docs flight-docs/
cd flight-docs/
# Install the dependencies
composer install
# Copy the config file
cp app/config/config_sample.php app/config/config.php
# Start the server (if you have PHP >8.2 installed)
composer start
# Or if you have a different version of PHP installed, you can use the built-in server
php82 -S localhost:8000 -t public/
```
--------------------------------
### Basic PHP Migration Setup and Execution
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/migrations.md
Use this snippet to set up a database connection, register the database driver, and perform migration actions like reset and update. It includes an example of adding a callback for progress updates.
```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 version is not specified migrate until the last database version
$migration->update($version = null);
```
--------------------------------
### Basic FlightPHP index.php Setup
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
A minimal index.php file to get started with FlightPHP. It includes Composer's autoloader, defines a simple route, and starts the framework.
```php
'world'
]);
});
Flight::start();
```
--------------------------------
### Install EasyQuery
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/easy_query.md
Install the package via Composer.
```bash
composer require knifelemon/easy-query
```
--------------------------------
### Install byjg/migration-cli
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/migrations.md
Install the standalone command-line interface for database migrations globally.
```bash
composer require "byjg/migration-cli"
```
--------------------------------
### Installation
Source: https://github.com/flightphp/docs/blob/master/content/v3/zh/awesome-plugins/php_file_cache.md
Install the flightphp/cache library using Composer.
```APIDOC
## Installation
Install via composer:
```bash
composer require flightphp/cache
```
```
--------------------------------
### Install Simple Job Queue
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/simple_job_queue.md
Use Composer to install the Simple Job Queue library. This command should be run in your project's root directory.
```bash
composer require n0nag0n/simple-job-queue
```
--------------------------------
### APM with Before and After Hooks
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/extending.md
Implement basic Application Performance Monitoring by using `Flight::before('start', ...)` to record the start time and `Flight::after('start', ...)` to calculate and log the request duration.
```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 Composer locally
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/unit_testing_and_solid_principles.md
Downloads and installs Composer into the current project directory.
```bash
$ curl -sS https://getcomposer.org/installer | php
```
--------------------------------
### Install Flight PHP Skeleton App with Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/about.md
Use Composer to create a new project based on the Flight PHP skeleton application. 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://github.com/flightphp/docs/blob/master/content/v3/en/learn/why_frameworks.md
Illustrates a basic, unorganized approach to handling different URLs using if statements and 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...
```
--------------------------------
### Start Built-in PHP Development Server (Skeleton App)
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Use this Composer command to start the built-in PHP development server for the skeleton application.
```bash
composer start
```
--------------------------------
### Install Permissions Module
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/permissions.md
Install the package via Composer.
```bash
composer require flightphp/permissions
```
--------------------------------
### Output Buffering Issues in v3
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/migrating_to_v3.md
This example demonstrates potential issues with output buffering in v3 when echoing content outside of callables and controllers, such as in hooks or before the framework starts.
```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
';
});
```
--------------------------------
### AI Instructions Generation Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/ai.md
This example demonstrates the interactive prompts for the `ai:generate-instructions` command, where you provide project details to generate tailored AI coding instructions.
```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.
```
--------------------------------
### Basic FlightPHP Session Usage Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/session.md
Demonstrates registering the session service and using session methods like set(), get(), and clear() within Flight routes. Sessions are stored in files by default.
```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();
```
--------------------------------
### Quick Start with EasyQuery
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/easy_query.md
Construct a query and execute it using Flight's SimplePdo.
```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 Flight PHP via Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/guides/blog.md
Install the Flight PHP core library using Composer.
```bash
composer require flightphp/core
```
--------------------------------
### Full Filtering Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/filtering.md
This example demonstrates mapping a custom method, adding both before and after filters to modify 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');
```
--------------------------------
### Install Latest PHP (Ubuntu)
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Installs the default, latest available PHP version from the Ubuntu repositories.
```bash
sudo apt install php
```
--------------------------------
### Install Swoole Extension
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/async.md
Install the required Swoole extension using PECL or system package managers.
```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
```
--------------------------------
### Install Homebrew on macOS
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Run this command in the Terminal to install Homebrew, a package manager for macOS, if it's not already installed.
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
--------------------------------
### Install CommentTemplate with Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/comment_template.md
Use composer to install the CommentTemplate package. This is the first step before configuring the engine.
```bash
composer require knifelemon/comment-template
```
--------------------------------
### Simple Event Listener Example - FlightPHP
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/events.md
This example shows how to register a listener for the 'user.login' event. When triggered, it will output a welcome message and can include additional logic like sending an email.
```php
Flight::onEvent('user.login', function ($username) {
echo "Welcome back, $username!";
// you can send an email if the login is from a new location
});
```
--------------------------------
### Install Ghostff/Session with Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/ghost_session.md
Install the Ghostff/Session library using Composer. This is the standard method for adding PHP packages to your project.
```bash
composer require ghostff/session
```
--------------------------------
### Install PHP Module (Ubuntu)
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Installs an additional PHP module, like MySQL support for PHP 8.1, using apt.
```bash
sudo apt install php8.1-mysql
```
--------------------------------
### Database Connection Examples
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/active_record.md
Examples of establishing database connections using PDO for SQLite and MySQL, and mysqli for MySQL. These connections are required to instantiate ActiveRecord classes.
```php
// for sqlite
$database_connection = new PDO('sqlite:test.db'); // this is just for example, you'd probably use a real database connection
```
```php
// for mysql
$database_connection = new PDO('mysql:host=localhost;dbname=test_db&charset=utf8bm4', 'username', 'password');
```
```php
// or mysqli
$database_connection = new mysqli('localhost', 'username', 'password', 'test_db');
```
```php
// or mysqli with non-object based creation
$database_connection = mysqli_connect('localhost', 'username', 'password', 'test_db');
```
--------------------------------
### Install byjg/migration PHP Library
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/migrations.md
Use this Composer command to install the PHP library for managing migrations within your project.
```bash
composer require "byjg/migration"
```
--------------------------------
### Latte Template and Route Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/templates.md
Example of a Latte template file and the corresponding route definition in Flight.
```html
{$title ? $title . ' - '}My App
Hello, {$name}!
```
```php
// routes.php
Flight::route('/@name', function ($name) {
Flight::render('home.latte', [
'title' => 'Home Page',
'name' => $name
]);
});
```
--------------------------------
### Install Supervisord
Source: https://github.com/flightphp/docs/blob/master/content/v3/zh/awesome-plugins/simple_job_queue.md
Install Supervisord on Ubuntu/Debian, CentOS/RHEL, or macOS using Homebrew to manage long-running processes.
```bash
# 在 Ubuntu/Debian 上
sudo apt-get install supervisor
# 在 CentOS/RHEL 上
sudo yum install supervisor
# 在 macOS 上使用 Homebrew
brew install supervisor
```
--------------------------------
### APM: Record Request Start Time
Source: https://github.com/flightphp/docs/blob/master/content/v3/pt/learn/extending.md
Implement basic Application Performance Monitoring by using `Flight::before('start', ...)` to record the request's start time using `microtime(true)` and store it using `Flight::set()`.
```php
// Em seu arquivo services.php
Flight::before('start', function() {
Flight::set('start_time', microtime(true));
});
```
--------------------------------
### Install Supervisord
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/simple_job_queue.md
Commands to install Supervisord on different operating systems. Use the appropriate command for your environment (Ubuntu/Debian, CentOS/RHEL, or macOS with Homebrew).
```bash
# On Ubuntu/Debian
sudo apt-get install supervisor
# On CentOS/RHEL
sudo yum install supervisor
# On macOS with Homebrew
brew install supervisor
```
--------------------------------
### Install Default PHP (Rocky Linux)
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Installs the default PHP version available through the enabled repositories on Rocky Linux using dnf.
```bash
sudo dnf install php
```
--------------------------------
### Install Encryption Library
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/php_encryption.md
Use Composer to add the defuse/php-encryption library to your project.
```bash
composer require defuse/php-encryption
```
--------------------------------
### Install Runway CLI
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/runway.md
Install the Runway CLI application using Composer. This command adds the necessary packages to your project.
```bash
composer require flightphp/runway
```
--------------------------------
### Define Route and Controller
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/unit_testing.md
Example of a route handler and a controller class designed for dependency injection.
```php
// index.php
$app->route('POST /register', [ UserController::class, 'register' ]);
// UserController.php
class UserController {
protected $app;
public function __construct(flight\Engine $app) {
$this->app = $app;
}
public function register() {
$email = $this->app->request()->data->email;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return $this->app->json(['status' => 'error', 'message' => 'Invalid email']);
}
return $this->app->json(['status' => 'success', 'message' => 'Valid email']);
}
}
```
--------------------------------
### Install Composer globally
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/unit_testing_and_solid_principles.md
Moves the composer.phar file to a system-wide directory and makes it executable.
```bash
$ mv composer.phar /usr/local/bin/composer
$ chmod +x composer
```
--------------------------------
### Example APM Configuration JSON
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/apm.md
This is an example of the `.runway-config.json` file generated by `php vendor/bin/runway apm:init`. It specifies the types and Data Source Names (DSNs) for both raw metric storage (source) and processed data storage (destination).
```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"
}
}
```
--------------------------------
### Full FlightPHP Database Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/simple_pdo.md
This comprehensive example demonstrates various database operations including fetching all rows, streaming results, fetching single rows/values/columns/pairs, using IN() syntax, inserting, updating, deleting, and transactions.
```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');
// Get a single column
$ids = Flight::db()->fetchColumn('SELECT id FROM users');
// Get key-value pairs
$userNames = Flight::db()->fetchPairs('SELECT id, name FROM users');
// Special IN() syntax
$users = Flight::db()->fetchAll('SELECT * FROM users WHERE id IN (?)', [[1,2,3,4,5]]);
// Insert a new user
$id = Flight::db()->insert('users', [
'name' => 'Bob',
'email' => 'bob@example.com'
]);
// Bulk insert users
Flight::db()->insert('users', [
['name' => 'Bob', 'email' => 'bob@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com']
]);
// Update a user
$affected = Flight::db()->update('users', ['name' => 'Bob'], 'id = ?', [123]);
// Delete a user
$deleted = Flight::db()->delete('users', 'id = ?', [123]);
// Use a transaction
$result = Flight::db()->transaction(function($db) {
$db->insert('users', ['name' => 'John', 'email' => 'john@example.com']);
$db->insert('audit_log', ['action' => 'user_created']);
return $db->lastInsertId();
});
});
```
--------------------------------
### Install Async via Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/async.md
Use Composer to add the async package to your project dependencies.
```bash
composer require flightphp/async
```
--------------------------------
### Blade Template Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/templates.md
A simple Blade template file demonstrating variable interpolation.
```blade
'Hello World!']);
});
```
--------------------------------
### Install Cookie Library
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/php_cookie.md
Use Composer to add the cookie management library to your project.
```bash
composer require overclokk/cookie
```
--------------------------------
### Initialize LLM Credentials
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/ai.md
Use the `ai:init` command to set up credentials for connecting your project to an LLM provider. You will be prompted to choose a provider, enter your API key, and specify the model name.
```bash
php runway ai:init
```
--------------------------------
### Register a Custom Router Class in FlightPHP
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/extending.md
Replace the default Router with a custom implementation by extending the base Router class and registering it with Flight. This example shows a custom router that disables the pass route feature for GET requests.
```php
// create your custom Router class
class MyRouter extends \flight\net\Router {
// override methods here
// for example a shortcut for GET requests to remove
// the pass route feature
public function get($pattern, $callback, $alias = '') {
return parent::get($pattern, $callback, false, $alias);
}
}
// Register your custom class
Flight::register('router', MyRouter::class);
// When Flight loads the Router instance, it will load your class
$myRouter = Flight::router();
$myRouter->get('/hello', function() {
echo "Hello World!";
}, 'hello_alias');
```
--------------------------------
### FlightPHP CRUD API for Users with EasyQuery
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/easy_query.md
This example demonstrates how to implement a full CRUD API for managing users using FlightPHP and EasyQuery. It includes routes for GET, POST, PUT, and DELETE operations, utilizing EasyQuery's fluent interface for building SQL queries.
```php
use KnifeLemon\EasyQuery\Builder;
// List users with pagination
Flight::route('GET /users', function() {
$page = (int) (Flight::request()->query['page'] ?? 1);
$perPage = 20;
$q = Builder::table('users')
->select(['id', 'name', 'email', 'created_at'])
->where(['status' => 'active'])
->orderBy('created_at DESC')
->limit($perPage, ($page - 1) * $perPage)
->build();
$users = Flight::db()->fetchAll($q['sql'], $q['params']);
Flight::json(['users' => $users, 'page' => $page]);
});
// Create user
Flight::route('POST /users', function() {
$data = Flight::request()->data;
$q = Builder::table('users')
->insert([
'name' => $data->name,
'email' => $data->email,
'created_at' => Builder::raw('NOW()')
])
->build();
Flight::db()->runQuery($q['sql'], $q['params']);
Flight::json(['id' => Flight::db()->lastInsertId()]);
});
// Update user
Flight::route('PUT /users/@id', function($id) {
$data = Flight::request()->data;
$q = Builder::table('users')
->update([
'name' => $data->name,
'email' => $data->email,
'updated_at' => Builder::raw('NOW()')
])
->where(['id' => $id])
->build();
Flight::db()->runQuery($q['sql'], $q['params']);
Flight::json(['success' => true]);
});
// Delete user
Flight::route('DELETE /users/@id', function($id) {
$q = Builder::table('users')
->delete()
->where(['id' => $id])
->build();
Flight::db()->runQuery($q['sql'], $q['params']);
Flight::json(['success' => true]);
});
```
--------------------------------
### Full Example Usage
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/simple_pdo.md
Demonstrates various functionalities of the SimplePdo class, including fetching data, inserting, updating, deleting records, and using transactions.
```APIDOC
## Flight::route('/users', function () { ... });
### Description
This example route showcases multiple database operations using the FlightPHP SimplePdo wrapper.
### Code 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');
// Get a single column
$ids = Flight::db()->fetchColumn('SELECT id FROM users');
// Get key-value pairs
$userNames = Flight::db()->fetchPairs('SELECT id, name FROM users');
// Special IN() syntax
$users = Flight::db()->fetchAll('SELECT * FROM users WHERE id IN (?)', [[1,2,3,4,5]]);
// Insert a new user
$id = Flight::db()->insert('users', [
'name' => 'Bob',
'email' => 'bob@example.com'
]);
// Bulk insert users
Flight::db()->insert('users', [
['name' => 'Bob', 'email' => 'bob@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com']
]);
// Update a user
$affected = Flight::db()->update('users', ['name' => 'Bob'], 'id = ?', [123]);
// Delete a user
$deleted = Flight::db()->delete('users', 'id = ?', [123]);
// Use a transaction
$result = Flight::db()->transaction(function($db) {
$db->insert('users', ['name' => 'John', 'email' => 'john@example.com']);
$db->insert('audit_log', ['action' => 'user_created']);
return $db->lastInsertId();
});
});
```
```
--------------------------------
### Install Latest PHP with Homebrew
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
After installing Homebrew, use this command to install the latest stable version of PHP on your macOS system.
```bash
brew install php
```
--------------------------------
### Start Docker Databases for Testing
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/migrations.md
Launch the necessary databases (PostgreSQL, MySQL, MSSQL) for integration testing using Docker Compose.
```bash
docker-compose up -d postgres mysql mssql
```
--------------------------------
### Apply ORDER BY, GROUP BY, and LIMIT in PHP
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/easy_query.md
Examples for sorting results, grouping aggregate data, and implementing pagination limits.
```php
$q = Builder::table('users')
->orderBy('created_at DESC')
->build();
// ORDER BY created_at DESC
```
```php
$q = Builder::table('orders')
->select(['user_id', 'COUNT(*) as order_count'])
->groupBy('user_id')
->build();
// SELECT user_id, COUNT(*) as order_count FROM orders GROUP BY user_id
```
```php
$q = Builder::table('users')
->limit(10)
->build();
// LIMIT 10
$q = Builder::table('users')
->limit(10, 20) // limit, offset
->build();
// LIMIT 10 OFFSET 20
```
--------------------------------
### Install Tracy with Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/tracy.md
Install the Tracy error handler using Composer. It's recommended to install the non-dev version for production error handling.
```bash
composer require tracy/tracy
```
--------------------------------
### SELECT Query Examples
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/easy_query.md
Construct SELECT queries with optional column selection and table aliasing.
```php
// Select all columns
$q = Builder::table('users')->build();
// SELECT * FROM users
// Select specific columns
$q = Builder::table('users')
->select(['id', 'name', 'email'])
->build();
// SELECT id, name, email FROM users
// With table alias
$q = Builder::table('users')
->alias('u')
->select(['u.id', 'u.name'])
->build();
// SELECT u.id, u.name FROM users AS u
```
--------------------------------
### Install Specific PHP Version with Homebrew
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
To install a specific PHP version (e.g., 8.1) on macOS, first tap the required repository, then install the version.
```bash
brew tap shivammathur/php
brew install shivammathur/php/php@8.1
```
--------------------------------
### Bootstrap Swoole Server
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/async.md
Initialize the Flight application and conditionally start the Swoole driver if not in development mode.
```php
// swoole_server.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();
}
```
--------------------------------
### Run Built-in Development Server
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/guides/blog.md
Start PHP's built-in development server, pointing to the public directory.
```bash
php -S localhost:8000 -t public/
```
--------------------------------
### Install Firebase PHP JWT
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/jwt.md
Install the Firebase JWT library using Composer.
```bash
composer require firebase/php-jwt
```
--------------------------------
### Create New Project with FlightPHP Skeleton
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Recommended for new projects, this command sets up a complete project structure with autoloading, configuration, and additional tools.
```bash
composer create-project flightphp/skeleton my-project/
```
--------------------------------
### Running the Swoole Server
Source: https://github.com/flightphp/docs/blob/master/content/v3/zh/awesome-plugins/async.md
Command to start the Swoole server in production. For development, use PHP's built-in server or PHP-FPM.
```bash
php swoole_server.php
```
--------------------------------
### Manually Create UploadedFile Instance
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/uploaded_file.md
Demonstrates how to manually instantiate an UploadedFile object. This is typically not needed as Flight handles it automatically, but useful for testing or specific scenarios.
```php
use flight\net\UploadedFile;
$file = new UploadedFile(
$_FILES['myfile']['name'],
$_FILES['myfile']['type'],
$_FILES['myfile']['size'],
$_FILES['myfile']['tmp_name'],
$_FILES['myfile']['error']
);
```
--------------------------------
### Initialize APM Configuration File
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/apm.md
Run this command to generate the `.runway-config.json` file using an interactive wizard. This wizard helps configure the source and destination for APM metrics, defaulting to SQLite if not specified otherwise.
```bash
php vendor/bin/runway apm:init
```
--------------------------------
### Swoole Server Bootstrap and Flight App Initialization
Source: https://github.com/flightphp/docs/blob/master/content/v3/zh/awesome-plugins/async.md
This file bootstraps your Flight application and starts the Swoole driver if NOT_SWOOLE is not defined. It includes a basic route for '/'.
```php
// swoole_server.php
route('/', function() use ($app) {
$app->json(['hello' => 'world']);
});
if (!defined('NOT_SWOOLE')) {
// 在 Swoole 模式下运行时要求 SwooleServerDriver 类。
require_once __DIR__ . '/SwooleServerDriver.php';
Swoole\Runtime::enableCoroutine();
$Swoole_Server = new SwooleServerDriver('127.0.0.1', 9501, $app);
$Swoole_Server->start();
} else {
$app->start();
}
```
--------------------------------
### Inspect PHP Configuration
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/unit_testing_and_solid_principles.md
Use the command line to view current PHP configuration settings.
```bash
$ php -i
```
```bash
$ php -i | grep error_log
```
--------------------------------
### Install BladeOne Composer Package
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/templates.md
Install the BladeOne library using Composer to enable Blade templating in your project.
```bash
composer require eftec/bladeone
```
--------------------------------
### Install Swoole Extension
Source: https://github.com/flightphp/docs/blob/master/content/v3/zh/awesome-plugins/async.md
Install the Swoole extension for PHP. This is required if you plan to run your Flight application using Swoole.
```bash
# 使用 pecl
pecl install swoole
# 或 openswoole
pecl install openswoole
# 或使用包管理器(Debian/Ubuntu 示例)
sudo apt-get install php-swoole
```
--------------------------------
### Create Public Directory
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/guides/blog.md
Create the public directory which will serve as the web root for the application.
```bash
mkdir public
```
--------------------------------
### Install Specific PHP Version (Ubuntu)
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Installs a particular PHP version, such as 8.1, using the apt package manager.
```bash
sudo apt install php8.1
```
--------------------------------
### Simple Event Trigger Example - FlightPHP
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/events.md
This example triggers the 'user.login' event with a username argument, which will then execute the registered listener.
```php
$username = 'alice';
Flight::triggerEvent('user.login', $username);
```
--------------------------------
### Start Built-in PHP Development Server
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
A simple way to run your FlightPHP application locally. This command starts the server on localhost:8000.
```bash
php -S localhost:8000
```
--------------------------------
### Register Class with Constructor Parameters
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/extending.md
Register a class and provide constructor parameters by passing an array. This pre-initializes the object when it's first requested.
```php
// Register class with constructor parameters
Flight::register('db', PDO::class, ['mysql:host=localhost;dbname=test', 'user', 'pass']);
// Get an instance of your class
// This will create an object with the defined parameters
//
// new PDO('mysql:host=localhost;dbname=test','user','pass');
//
$db = Flight::db();
// and if you needed it later in your code, you just call the same method again
class SomeController {
public function __construct() {
$this->db = Flight::db();
}
}
```
--------------------------------
### Traditional Dependency Management in FlightPHP
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/learn/dependency_injection_container.md
This example shows the manual way of creating and passing dependencies like PDO to controllers before using a DIC. It's suitable for small applications but can become cumbersome as the application grows.
```php
require 'vendor/autoload.php';
// class to manage users from the database
class UserController {
protected PDO $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function view(int $id) {
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $id]);
print_r($stmt->fetch());
}
}
// in your routes.php file
$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$UserController = new UserController($db);
Flight::route('/user/@id', [ $UserController, 'view' ]);
// other UserController routes...
Flight::start();
```
--------------------------------
### Login Logic with Session Management
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/ghost_session.md
Example of handling a POST login request. Sets session variables upon successful login and commits the session data. Ensure session data is committed after writing.
```php
Flight::route('POST /login', function() {
$session = Flight::session();
// do your login logic here
// validate password, etc.
// if the login is successful
$session->set('is_logged_in', true);
$session->set('user', $user);
// any time you write to the session, you must commit it deliberately.
$session->commit();
});
```
--------------------------------
### Install Flight ActiveRecord via Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/active_record.md
Installs the Flight ActiveRecord library using Composer. This is the recommended method for adding the package to your project.
```bash
composer require flightphp/active-record
```
--------------------------------
### Get a Cache Value
Source: https://github.com/flightphp/docs/blob/master/content/v3/zh/awesome-plugins/php_file_cache.md
Retrieve a cached value using `get()` or `refreshIfExpired()`. `refreshIfExpired()` provides a convenience method to refresh the cache if it has expired.
```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()`.
```php
// 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
}
```
```
--------------------------------
### Install Specific PHP Version (Rocky Linux)
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/install/install.md
Installs a specific PHP version, such as 7.4, by enabling the corresponding module from Remi's repository.
```bash
sudo dnf module install php:remi-7.4
```
--------------------------------
### Install FlightPHP Session via Composer
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/session.md
Use Composer to install the FlightPHP Session plugin. This command adds the plugin to your project's dependencies.
```bash
composer require flightphp/session
```
--------------------------------
### UserRecord Model Example
Source: https://github.com/flightphp/docs/blob/master/content/v3/en/awesome-plugins/runway.md
Example of an Active Record model class for the 'users' table. This class defines properties, relationships, and a constructor that links to the 'users' table.
```php