### Start Built-in PHP Development Server
Source: https://docs.flightphp.com/en/v3/single-page
Run this command to start the local development server on port 8000. This is the simplest way to get started, especially with SQLite.
```bash
php -S localhost:8000
```
--------------------------------
### LIMIT and OFFSET Example
Source: https://docs.flightphp.com/en/v3/single-page
Shows how to apply LIMIT and OFFSET to control the number of records returned and their starting point.
```php
$q = Builder::table('users')
->limit(10)
->build();
// LIMIT 10
$q = Builder::table('users')
->limit(10, 20) // limit, offset
->build();
// LIMIT 10 OFFSET 20
```
--------------------------------
### Initialize APM Configuration
Source: https://docs.flightphp.com/en/v3/single-page
Run this command to start the configuration wizard for your APM setup. It will guide you through setting up data sources and destinations.
```bash
php vendor/bin/runway apm:init
```
--------------------------------
### Example User and Contact Models with Relationships
Source: https://docs.flightphp.com/en/v3/single-page
Concrete examples of User and Contact ActiveRecord classes demonstrating the setup of HAS_MANY, HAS_ONE, and BELONGS_TO relationships.
```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');
}
}
```
--------------------------------
### Pagination Example with Count and Results
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates a common pagination pattern: first getting the total count of records, then fetching a specific page of results.
```php
$baseQuery = Builder::table('users')
->select(['id', 'name', 'email'])
->where(['status' => 'active'])
->orderBy('created_at DESC');
// Get total count
$countQuery = clone $baseQuery;
$countResult = $countQuery->clearSelect()->count()->build();
$total = Flight::db()->fetchField($countResult['sql'], $countResult['params']);
// Get paginated results
$page = 1;
$perPage = 20;
$listResult = $baseQuery->limit($perPage, ($page - 1) * $perPage)->build();
$users = Flight::db()->fetchAll($listResult['sql'], $listResult['params']);
```
--------------------------------
### Full FlightPHP Example with EasyQuery
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates listing, creating, updating, and deleting users using EasyQuery's fluent interface within FlightPHP routes. Requires EasyQuery and FlightPHP to be installed.
```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]);
});
```
--------------------------------
### Install Composer Locally
Source: https://docs.flightphp.com/en/v3/single-page
Download and install the Composer dependency manager for the current project. It's recommended to review the installer script before execution.
```bash
$ curl -sS https://getcomposer.org/installer | php
```
--------------------------------
### Install Simple Job Queue
Source: https://docs.flightphp.com/en/v3/single-page
Installs the simple_job_queue library using Composer. This is the first step to enable asynchronous job processing.
```bash
composer require n0nag0n/simple-job-queue
```
--------------------------------
### LLM Credentials Initialization Example
Source: https://docs.flightphp.com/en/v3/single-page
An example interaction for the `ai:init` command, showing prompts for provider selection, API key input, and model name.
```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
```
--------------------------------
### Latte Template Example
Source: https://docs.flightphp.com/en/v3/single-page
An example of a Latte template file (`home.latte`) demonstrating variable usage for dynamic content.
```html
{$title ? $title . ' - '}My App
Hello, {$name}!
```
--------------------------------
### Start Built-in PHP Development Server (Skeleton App)
Source: https://docs.flightphp.com/en/v3/single-page
If using the skeleton app, this command starts the development server. It is already configured to serve your application.
```bash
composer start
```
--------------------------------
### Install defuse/php-encryption
Source: https://docs.flightphp.com/en/v3/single-page
Install the defuse/php-encryption library using Composer.
```bash
composer require defuse/php-encryption
```
--------------------------------
### Database Connection Examples
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates how to establish database connections using PDO for SQLite and MySQL, and mysqli.
```php
// for sqlite
$database_connection = new PDO('sqlite:test.db'); // this is just for example, you'd probably use a real database connection
// for mysql
$database_connection = new PDO('mysql:host=localhost;dbname=test_db&charset=utf8bm4', 'username', 'password');
// or mysqli
$database_connection = new mysqli('localhost', 'username', 'password', 'test_db');
// or mysqli with non-object based creation
$database_connection = mysqli_connect('localhost', 'username', 'password', 'test_db');
```
--------------------------------
### Traditional Script-Based Routing Example
Source: https://docs.flightphp.com/en/v3/single-page
Illustrates a basic, unorganized approach to routing using individual PHP files 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...
```
--------------------------------
### Install overclokk/cookie
Source: https://docs.flightphp.com/en/v3/single-page
Install the overclokk/cookie library using Composer.
```bash
composer require overclokk/cookie
```
--------------------------------
### AI Instructions Generation Example
Source: https://docs.flightphp.com/en/v3/single-page
An example interaction for the `ai:generate-instructions` command, demonstrating prompts for project details like description, database, templating, and security.
```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 PHP Skeleton App
Source: https://docs.flightphp.com/en/v3
Use Composer to create a new project with the Flight PHP skeleton application. This provides a structured starting point with pre-configured settings.
```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
```
--------------------------------
### Composer Installation
Source: https://docs.flightphp.com/en/v3/single-page
Command to install the FlightPHP ActiveRecord library using Composer.
```bash
composer require flightphp/active-record
```
--------------------------------
### Install Homebrew
Source: https://docs.flightphp.com/en/v3/single-page
Run this command in the Terminal to install Homebrew on macOS if it's not already installed.
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
--------------------------------
### Install Ghostff/Session via Composer
Source: https://docs.flightphp.com/en/v3/single-page
Use this command to install the Ghostff/Session plugin using Composer.
```bash
composer require ghostff/session
```
--------------------------------
### Example APM Configuration
Source: https://docs.flightphp.com/en/v3/single-page
This is an example of the .runway-config.json file generated after running the initialization wizard. It specifies the source and storage types and their database connection strings.
```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 Database Operations Example
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates various PdoWrapper methods within a single Flight route, including fetching all users, a single user, a field, using IN() syntax, inserting, updating, deleting, and getting affected rows.
```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();
});
```
--------------------------------
### Swoole Server Bootstrap and Runtime
Source: https://docs.flightphp.com/en/v3/single-page
This file bootstraps the Flight app and starts the Swoole driver when NOT_SWOOLE is not defined. It enables coroutine support and starts the Swoole server.
```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();
}
```
--------------------------------
### Install byjg/migration PHP Library
Source: https://docs.flightphp.com/en/v3/single-page
Use this command to install the byjg/migration PHP library for managing database changes within your project.
```bash
composer require "byjg/migration"
```
--------------------------------
### Install Latest PHP (Ubuntu)
Source: https://docs.flightphp.com/en/v3/install
Installs the default, latest available version of PHP using the apt package manager.
```bash
sudo apt install php
```
--------------------------------
### Install byjg/migration-cli Command Line Interface
Source: https://docs.flightphp.com/en/v3/single-page
Install the standalone byjg/migration-cli globally to manage migrations from the command line. This allows creating a symbolic link for easy access.
```bash
composer require "byjg/migration-cli"
```
--------------------------------
### Clone MCP Server and Install Dependencies
Source: https://docs.flightphp.com/en/v3/single-page
Clone the MCP repository and install its dependencies using Composer. This is the initial step for self-hosting the MCP server.
```bash
git clone https://github.com/flightphp/mcp.git
cd mcp
composer install
php server.php
```
--------------------------------
### Full Filtering Example with Custom Method
Source: https://docs.flightphp.com/en/v3/single-page
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 Tracy Debugger
Source: https://docs.flightphp.com/en/v3/single-page
Install the Tracy Debugger via Composer to enable automatic logging of EasyQuery queries.
```bash
composer require tracy/tracy
```
--------------------------------
### Install Default PHP (Rocky Linux)
Source: https://docs.flightphp.com/en/v3/install
Installs the default PHP version available through the enabled repositories using dnf.
```bash
sudo dnf install php
```
--------------------------------
### Install FlightPHP Runway via Composer
Source: https://docs.flightphp.com/en/v3/single-page
Install the Runway CLI application for managing Flight applications using Composer.
```bash
composer require flightphp/runway
```
--------------------------------
### Install FlightPHP Cache
Source: https://docs.flightphp.com/en/v3/single-page
Install the FlightPHP Cache module using Composer.
```bash
composer require flightphp/cache
```
--------------------------------
### Install EasyQuery using Composer
Source: https://docs.flightphp.com/en/v3/single-page
Use this command to add the EasyQuery library to your project dependencies.
```bash
composer require knifelemon/easy-query
```
--------------------------------
### ORDER BY Clause Example
Source: https://docs.flightphp.com/en/v3/single-page
Illustrates how to specify an ORDER BY clause to sort the query results.
```php
$q = Builder::table('users')
->orderBy('created_at DESC')
->build();
// ORDER BY created_at DESC
```
--------------------------------
### Install Firebase PHP JWT
Source: https://docs.flightphp.com/en/v3/single-page
Install the Firebase PHP JWT library using Composer.
```bash
composer require firebase/php-jwt
```
--------------------------------
### Verify PHP Installation (Windows)
Source: https://docs.flightphp.com/en/v3/install
Run this command in the Command Prompt to check if PHP is installed and accessible via the system PATH.
```bash
php -v
```
--------------------------------
### Install Tracy Debugger
Source: https://docs.flightphp.com/en/v3/single-page
Installs the Tracy Debugger using Composer. This is a prerequisite for using the Tracy integration features.
```bash
composer require tracy/tracy
```
--------------------------------
### Install Supervisord on Different Operating Systems
Source: https://docs.flightphp.com/en/v3/single-page
Commands to install the Supervisord process control system on Ubuntu/Debian, CentOS/RHEL, and macOS using 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 PHP MySQL Module (Ubuntu)
Source: https://docs.flightphp.com/en/v3/install
Installs the necessary module for PHP to interact with MySQL databases.
```bash
sudo apt install php8.1-mysql
```
--------------------------------
### Install Flight PHP Core
Source: https://docs.flightphp.com/en/v3
Use Composer to install the Flight PHP core package. This is the recommended method for adding Flight to your project.
```bash
composer require flightphp/core
```
--------------------------------
### Install Latte Template Engine
Source: https://docs.flightphp.com/en/v3/single-page
Use Composer to install the Latte template engine. This is a prerequisite for using Latte with FlightPHP.
```bash
composer require latte/latte
```
--------------------------------
### Install Specific PHP Version (Ubuntu)
Source: https://docs.flightphp.com/en/v3/install
Installs a particular PHP version, such as 8.1, using the apt package manager.
```bash
sudo apt install php8.1
```
--------------------------------
### Installing and Configuring Tracy Extensions for FlightPHP
Source: https://docs.flightphp.com/en/v3/single-page
Install the Tracy extensions via Composer and enable the Tracy debugger. This snippet shows the bootstrap process, including registering a custom PDO wrapper for query analysis and initializing the Tracy extension loader.
```php
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']);
}
}
```
--------------------------------
### Controller With Namespaces
Source: https://docs.flightphp.com/en/v3/single-page
Example of a controller class using namespaces. Namespaces must match the directory structure and case.
```php
/**
* app/controllers/MyController.php
*/
// namespaces are required
// namespaces are the same as the directory structure
// namespaces must follow the same case as the directory structure
// namespaces and directories cannot have any underscores (unless Loader::setV2ClassLoading(false) is set)
namespace app\controllers;
// All autoloaded classes are recommended to be Pascal Case (each word capitalized, no spaces)
// As of 3.7.2, you can use Pascal_Snake_Case for your class names by running Loader::setV2ClassLoading(false);
class MyController {
public function index() {
// do something
}
}
```
--------------------------------
### Install FlightPHP Async Package
Source: https://docs.flightphp.com/en/v3/single-page
Install the FlightPHP Async package using Composer. This package enables running Flight applications with asynchronous servers.
```bash
composer require flightphp/async
```
--------------------------------
### Install EPEL Repository (Rocky Linux)
Source: https://docs.flightphp.com/en/v3/install
Installs the Extra Packages for Enterprise Linux (EPEL) repository, which is often required for additional software on Rocky Linux.
```bash
sudo dnf install epel-release
```
--------------------------------
### Quick Start: Build and Execute a SELECT Query
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates building a basic SELECT query with WHERE, ORDER BY, and LIMIT clauses, then executing 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']);
```
--------------------------------
### Dump All Flight Configuration
Source: https://docs.flightphp.com/en/v3/single-page
A troubleshooting utility to display all current Flight configuration settings, useful for verifying setup.
```php
var_dump(Flight::get());
```
--------------------------------
### Install Remi's Repository (Rocky Linux)
Source: https://docs.flightphp.com/en/v3/install
Installs Remi's repository, a popular source for up-to-date PHP packages on Enterprise Linux distributions.
```bash
sudo dnf install https://rpms.remirepo.net/enterprise/remi-release-8.rpm
sudo dnf module reset php
```
--------------------------------
### Basic index.php for FlightPHP Application
Source: https://docs.flightphp.com/en/v3/install
A minimal index.php file to get started with FlightPHP. It includes the Composer autoloader, defines a simple route, and starts the framework.
```php
alias('u')
->select(['u.name', 'o.total'])
->leftJoin('orders', 'u.id = o.user_id', 'o')
->build();
// ... LEFT JOIN orders AS o ON u.id = o.user_id
```
--------------------------------
### Install Swoole Extension
Source: https://docs.flightphp.com/en/v3/single-page
Install the Swoole extension for PHP, which is required for running Flight applications with the Swoole asynchronous server. This can be done using PECL or a package manager.
```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
```
--------------------------------
### GROUP BY Clause Example
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates how to use the GROUP BY clause to aggregate rows that have the same values in specified columns.
```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
```
--------------------------------
### Built-in View Template Example
Source: https://docs.flightphp.com/en/v3/single-page
A simple PHP template file (`hello.php`) that displays a variable passed from the `render` method.
```php
Hello, = $name ?>!
```
--------------------------------
### Basic Flight PHP Route
Source: https://docs.flightphp.com/en/v3/single-page
A simple GET route example for Flight PHP that returns a JSON response. This can be used for basic API endpoints.
```php
Flight::route('GET /api/hello', function() {
Flight::json(['message' => 'Hello World!']);
});
```
--------------------------------
### Install Composer Globally
Source: https://docs.flightphp.com/en/v3/single-page
Move the Composer executable to a system-wide location for convenient access. You may need `sudo` permissions for this operation.
```bash
$ mv composer.phar /usr/local/bin/composer
$ chmod +x composer
```
--------------------------------
### Simple Controller Without Namespaces
Source: https://docs.flightphp.com/en/v3/single-page
Example of a controller class without namespaces. Class names should be Pascal Case.
```php
/**
* app/controllers/MyController.php
*/
// no namespacing required
// All autoloaded classes are recommended to be Pascal Case (each word capitalized, no spaces)
class MyController {
public function index() {
// do something
}
}
```
--------------------------------
### Basic Flight PHP Application
Source: https://docs.flightphp.com/en/v3
A minimal Flight PHP application demonstrating route definition and starting the server. This example shows how to define a simple route and handle a JSON response.
```php
'world'
]);
});
Flight::start();
```
--------------------------------
### Initialize LLM Credentials
Source: https://docs.flightphp.com/en/v3/single-page
Use the `ai:init` command to connect your project to an LLM provider by selecting a provider, entering your API key, and specifying the base URL and model name. This creates a `.runway-creds.json` file.
```bash
php runway ai:init
```
--------------------------------
### Register Custom Router Class
Source: https://docs.flightphp.com/en/v3/single-page
Replace the default Router class with a custom implementation to modify routing behavior. This example shows how to create 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');
```
--------------------------------
### Run APM Worker with Custom Options
Source: https://docs.flightphp.com/en/v3/single-page
Start the APM worker with specific configurations for timeout, message capping, batch size, and daemon mode. This example runs the worker for an hour, processing 100 metrics at a time.
```shell
php vendor/bin/runway apm:worker --daemon --batch_size 100 --timeout 3600
```
--------------------------------
### Start Databases for Integration Tests
Source: https://docs.flightphp.com/en/v3/single-page
Use Docker Compose to bring up PostgreSQL, MySQL, and SQL Server instances for running integration tests.
```shell
docker-compose up -d postgres mysql mssql
```
--------------------------------
### Register Class with Post-Construction Callback
Source: https://docs.flightphp.com/en/v3/single-page
Register a class and execute a callback function immediately after construction to perform setup procedures on the new object.
```php
// The callback will be passed the object that was constructed
Flight::register(
'db',
PDO::class,
['mysql:host=localhost;dbname=test', 'user', 'pass'],
function (PDO $db) {
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
);
```
--------------------------------
### Install Specific PHP Version with Homebrew
Source: https://docs.flightphp.com/en/v3/single-page
Install a specific PHP version, like 8.1, on macOS by tapping a third-party repository and installing the versioned package.
```bash
brew tap shivammathur/php
brew install shivammathur/php/php@8.1
```
--------------------------------
### Installing PHP on macOS using Homebrew
Source: https://docs.flightphp.com/en/v3/install
Commands to install Homebrew and then install the latest version of PHP or a specific version like PHP 8.1 on macOS.
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
```bash
brew install php
```
```bash
brew tap shivammathur/php
brew install shivammathur/php/php@8.1
```
--------------------------------
### Create Project Directory
Source: https://docs.flightphp.com/en/v3/single-page
Creates a new directory for the Flight PHP blog project.
```bash
mkdir flight-blog
cd flight-blog
```
--------------------------------
### Creating and Inserting a New User
Source: https://docs.flightphp.com/en/v3/single-page
Shows how to instantiate a User object, set its properties, and insert it into the database.
```php
$user = new User($database_connection);
$user->name = 'Bobby Tables';
$user->password = password_hash('some cool password');
$user->insert();
// or $user->save();
echo $user->id; // 1
$user->name = 'Joseph Mamma';
$user->password = password_hash('some cool password again!!!');
$user->insert();
// can't use $user->save() here or it will think it's an update!
echo $user->id; // 2
```
--------------------------------
### Create a Custom Command
Source: https://docs.flightphp.com/en/v3/single-page
Example of creating a custom command by extending `AbstractBaseCommand`. Implement `__construct` and `execute` methods for custom logic.
```php
$config Config from app/config/config.php
*/
public function __construct(array $config)
{
parent::__construct('make:example', 'Create an example for the documentation', $config);
$this->argument('', 'The name of the funny gif');
}
/**
* Executes the function
*
* @return void
*/
public function execute()
{
$io = $this->app()->io();
$io->info('Creating example...');
// Do something here
$io->ok('Example created!');
}
}
```
--------------------------------
### Install Latest PHP with Homebrew
Source: https://docs.flightphp.com/en/v3/single-page
Use this command to install the latest version of PHP on macOS using Homebrew.
```bash
brew install php
```
--------------------------------
### Notify New Users Event
Source: https://docs.flightphp.com/en/v3/single-page
Set up a listener for the 'user.registered' event to simulate sending a welcome email. Trigger this event during the user signup process.
```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!";
});
```
--------------------------------
### Install FlightPHP Session Plugin
Source: https://docs.flightphp.com/en/v3/single-page
Install the FlightPHP Session plugin using Composer for file-based session management.
```bash
composer require flightphp/session
```
--------------------------------
### Asset Copying Example
Source: https://docs.flightphp.com/en/v3/single-page
Shows how to copy static assets like images and documents to the public directory for web access. '
Download Brochure
```
--------------------------------
### Raw SQL with Bound Parameters
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates using `raw()` with bound parameters for dynamic SQL expressions.
```php
$q = Builder::table('orders')
->update([
'total' => Builder::raw('COALESCE(subtotal, ?) + ?', [0, 10])
])
->where(['id' => 1])
->build();
// SET total = COALESCE(subtotal, ?) + ?
// params: [0, 10, 1]
```
--------------------------------
### Controller with Dependency Injection
Source: https://docs.flightphp.com/en/v3/single-page
Demonstrates a controller using dependency injection for database and mailer services, making it easier to mock and test.
```php
use flight\database\PdoWrapper;
class UserController {
protected $app;
protected $db;
protected $mailer;
public function __construct(Engine $app, PdoWrapper $db, MailerInterface $mailer) {
$this->app = $app;
$this->db = $db;
$this->mailer = $mailer;
}
public function register() {
$email = $this->app->request()->data->email;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// adding the return here helps unit testing to stop execution
return $this->app->jsonHalt(['status' => 'error', 'message' => 'Invalid email']);
}
$this->db->runQuery('INSERT INTO users (email) VALUES (?)', [$email]);
$this->mailer->sendWelcome($email);
return $this->app->json(['status' => 'success', 'message' => 'User registered']);
}
}
```
--------------------------------
### Display PHP Configuration
Source: https://docs.flightphp.com/en/v3/single-page
Use the CLI command to display all PHP configuration settings. This is useful for inspecting enabled extensions and other runtime configurations.
```bash
$ php -i
```
--------------------------------
### UserRecord Model Example
Source: https://docs.flightphp.com/en/v3/single-page
An example of an Active Record model generated for the 'users' table, including property definitions and a constructor.
```php
before() executes
before() checks for valid logged in session
if yes do nothing and continue execution
if no redirect the user to /login
Callable/method attached to /api executed and response generated
LoggedInMiddleware->after() has nothing defined so it lets execution continue
User receives dashboard HTML from server
```
--------------------------------
### Create Public Directory
Source: https://docs.flightphp.com/en/v3/single-page
Creates the public directory, which will serve as the web root for the application.
```bash
mkdir public
```
--------------------------------
### Configure FlightPHP MCP Server in Continue.dev config.json
Source: https://docs.flightphp.com/en/v3/single-page
Add the FlightPHP documentation server to your `~/.continue/config.json` file for the Continue.dev extension. This allows AI assistants to fetch FlightPHP documentation.
```json
{
"mcpServers": [
{
"name": "flightphp-docs",
"transport": {
"type": "http",
"url": "https://mcp.flightphp.com/mcp"
}
}
]
}
```
--------------------------------
### Install Specific PHP Version (Rocky Linux)
Source: https://docs.flightphp.com/en/v3/install
Installs a specific PHP version, such as 7.4, by enabling the corresponding module stream in dnf.
```bash
sudo dnf module install php:remi-7.4
```
--------------------------------
### Register Class with Constructor Parameters
Source: https://docs.flightphp.com/en/v3/single-page
Register a class and provide constructor parameters to pre-initialize the instance. This is useful for setting up dependencies like database connections.
```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();
}
}
```
--------------------------------
### Get Help for a Specific Runway Command
Source: https://docs.flightphp.com/en/v3/single-page
Use the --help flag with any Runway command to get detailed information on its usage and options.
```bash
php runway routes --help
```
--------------------------------
### Install FlightPHP APM using Composer
Source: https://docs.flightphp.com/en/v3/single-page
Install the FlightPHP APM package using Composer. Ensure you have PHP 7.4+ and FlightPHP Core v3.15+.
```bash
composer require flightphp/apm
```
--------------------------------
### Running Built-in PHP Server with Custom Document Root
Source: https://docs.flightphp.com/en/v3/install
Start the PHP built-in development server, specifying a custom document root (e.g., 'public/'). This is useful when your project's web root is not the top-level directory.
```bash
php -S localhost:8000 -t public/
```
--------------------------------
### Implement Basic APM with Before and After Hooks
Source: https://docs.flightphp.com/en/v3/single-page
Use `Flight::before()` and `Flight::after()` hooks to measure request duration and log performance metrics. This example logs the time taken for each request and includes request/response headers.
```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));
});
```
--------------------------------
### Instantiate Controller and Route
Source: https://docs.flightphp.com/en/v3/single-page
Instantiate a controller class before defining the route to pass dependencies like the `flight\Engine` instance.
```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' ]);
```
--------------------------------
### Manage Multiple Worker Pipelines with Supervisord
Source: https://docs.flightphp.com/en/v3/single-page
Example Supervisord configuration showing how to define separate processes for different worker pipelines, such as email and notification workers.
```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 ...
```
--------------------------------
### PHPUnit Configuration File
Source: https://docs.flightphp.com/en/v3/single-page
Create a phpunit.xml file to configure the test runner, specifying the bootstrap file and test directories.
```xml
tests
```