Creating and Running a FuelPHP Project in the ServBay Local Development Environment
What is FuelPHP?
FuelPHP is a flexible and modular PHP framework designed for building modern web applications. It follows the Hierarchical Model-View-Controller (HMVC) design pattern, providing a rich set of features and tools aimed at helping developers rapidly and efficiently create high-quality web apps. Thanks to its outstanding flexibility, high performance, and scalability, FuelPHP has become a preferred framework for many PHP developers.
Key Features and Advantages of FuelPHP
- HMVC Architecture: Supports the hierarchical MVC pattern, helping organize code for better reuse and modularization. It's especially suited for large or complex projects.
- High Performance: Engineered with performance in mind, FuelPHP is known for its efficiency and optimized resource usage, making it capable of handling high concurrency.
- Easy Extensibility: The framework offers powerful extensibility mechanisms, allowing developers to easily integrate third-party libraries or add custom features to meet project needs.
- Security: Built-in features such as automatic input validation, output filtering (to prevent XSS), CSRF protection, and SQL injection prevention help you build safer applications.
- Strong Community Support: FuelPHP has an active developer community, offering prompt assistance and a wealth of third-party resources.
With these features, FuelPHP empowers developers to quickly build high-performance, secure, and maintainable web apps, suitable for projects ranging from small startups to large-scale enterprise applications.
Setting Up a FuelPHP Development Environment with ServBay
ServBay is a local web development environment designed for developers, prepackaged with essential services and tools such as PHP, Caddy/Nginx/Apache, MySQL/PostgreSQL/MongoDB, and Redis. With ServBay, you can easily set up the necessary environment for your FuelPHP project without having to manually install and configure dependencies.
This guide will walk you through how to leverage ServBay's PHP environment, web server (Caddy), and database and cache services to create and run a FuelPHP project. We'll use ServBay’s Websites feature to configure the web server, allowing quick access and testing of your project with just a few simple steps.
Prerequisites
Before you begin, make sure you have:
- Successfully installed and launched ServBay on your macOS system.
- Enabled the PHP environment in ServBay (ServBay enables PHP by default).
- Started and verified the database service (like MySQL) and cache services (like Redis, Memcached) you plan to use in ServBay.
- Composer is included with ServBay by default, so no extra installation is needed.
Creating a FuelPHP Project
Recommended Project Directory
ServBay recommends placing all website projects under /Applications/ServBay/www
for easier management and configuration. We'll use this directory as the example throughout this guide.
Navigate to the Website Root Directory
Open Terminal and switch to the recommended website root directory:
bashcd /Applications/ServBay/www
1Create a Project Directory
Make a new directory for your FuelPHP project and enter it:
bashmkdir servbay-fuelphp-app cd servbay-fuelphp-app
1
2Create a FuelPHP Project with Composer
Use Composer to download and set up the FuelPHP framework in your project directory. The
.
indicates to install in the current directory:bashcomposer create-project fuel/fuel .
1Composer will automatically download FuelPHP and its dependencies into your
servbay-fuelphp-app
directory.
Configuring the Web Server (Using ServBay's Websites Feature)
To access your FuelPHP project in a browser, you need to use ServBay's Websites feature to configure a virtual host.
- Open the ServBay main interface.
- Click on the Websites menu in the sidebar.
- Click the Add Website button at the top right.
- Fill out the configuration form with the following details:
- Name: A recognizable name for your website, e.g.,
My First FuelPHP Dev Site
. - Domain: Set a local development domain such as
servbay-fuelphp-test.local
. ServBay will automatically resolve this domain locally. - Website Type: Select
PHP
. - PHP Version: Choose the desired PHP version, like
8.3
. - Website Root Directory: Specify the public entry directory of your FuelPHP project. FuelPHP's public entry file is
public/index.php
, so set the root directory to the project'spublic
subfolder:/Applications/ServBay/www/servbay-fuelphp-app/public
.
- Name: A recognizable name for your website, e.g.,
- Click Add to save your configuration.
ServBay will automatically update the Caddy configuration and reload the service to activate the new domain.
For detailed steps, see the ServBay documentation: Adding Your First Website.
Configuring Service Connections for FuelPHP
FuelPHP projects typically require database and cache service connection settings.
Database Configuration
The database settings for FuelPHP are in the fuel/app/config/development/db.php
file. Edit this file to configure your database connection. Assuming you use ServBay’s default MySQL service:
<?php
/**
* The development database settings. These get merged with the global settings.
*/
return [
'default' => [
'connection' => [
'dsn' => 'mysql:host=localhost;dbname=fuel_dev', // Make sure the fuel_dev database exists
'username' => 'root', // ServBay MySQL default user
'password' => 'root', // ServBay MySQL default password (for local development only!)
],
'identifier' => '`', // MySQL requires backticks as the identifier
],
];
2
3
4
5
6
7
8
9
10
11
12
13
14
Note:
- You need to manually create a
fuel_dev
database using ServBay's database management tools (such as phpMyAdmin or Adminer). The default MySQL user (root
) and password (root
) are for local development only. 'identifier' => '
'` is required for MySQL to ensure table and field names are properly quoted.
Cache Configuration (Memcached and Redis)
FuelPHP supports multiple cache drivers. Configure cache drivers and connection details in fuel/app/config/cache.php
. Make sure Memcached and/or Redis services are running in ServBay.
Memcached Configuration (fuel/app/config/cache.php
):
If you want to use Memcached as the default cache:
<?php
return [
'driver' => 'memcached', // Set memcached as the default driver
'memcached' => [
'cache_id' => 'fuel', // Cache ID
'servers' => [
'default' => [
'host' => '127.0.0.1', // Default Memcached listen address
'port' => 11211, // Default Memcached port
'weight' => 100,
],
],
'compression' => false, // Enable or disable compression
],
// ... other cache driver configs
];
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
The PHP installations in ServBay typically have the Memcached extension pre-installed.
Redis Configuration (fuel/app/config/redis.php
):
For Redis, configure the connection in a separate redis.php
config file:
<?php
return [
'default' => [
'hostname' => '127.0.0.1', // Default Redis listen address
'port' => 6379, // Default Redis port
'database' => 0, // Redis database index
],
// You can define multiple Redis connections if needed
];
2
3
4
5
6
7
8
9
The PHP installations in ServBay also typically have the Redis extension pre-installed.
Database and Cache Service Examples
To demonstrate how FuelPHP interacts with database and cache services, let's add some sample code.
Preparing the Database Table (Using FuelPHP Migrations)
FuelPHP provides the Oil tool for managing database migrations, which let you version-control your database schema.
Create a Migration File
In your project root (
servbay-fuelphp-app
), use the Oil tool to generate a migration to define ausers
table:bashphp oil generate migration create_users_table
1This creates a new migration file in
fuel/app/migrations
, with a timestamp in the filename.Edit the Migration File
Open the newly created migration file (
fuel/app/migrations/xxxxxxxxxxxx_create_users_table.php
) and edit theup()
anddown()
methods:php<?php namespace Fuel\Migrations; use Fuel\Core\DBUtil; class Create_users_table { public function up() { // Create users table DBUtil::create_table('users', [ 'id' => ['type' => 'int', 'constraint' => 11, 'auto_increment' => true], 'name' => ['type' => 'varchar', 'constraint' => 100], 'email' => ['type' => 'varchar', 'constraint' => 100, 'unique' => true], ], ['id'], true, 'InnoDB', 'utf8mb4_unicode_ci'); // Set primary key, enable indexes, set engine and charset } public function down() { // Drop users table (rollback) DBUtil::drop_table('users'); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23Run the Migration
In your project root, run the migration to create the table:
bashphp oil refine migrate
1If successful, a
users
table will appear in thefuel_dev
database.
Adding Sample Controller Code
Edit fuel/app/classes/controller/welcome.php
to add methods for demonstrating database and cache operations:
<?php
use Fuel\Core\Controller;
use Fuel\Core\Response;
use Fuel\Core\Cache;
use Fuel\Core\DB; // Import DB facade
use Fuel\Core\Redis; // Import Redis facade
class Controller_Welcome extends Controller
{
// Default home action
public function action_index()
{
return Response::forge('Hello ServBay!');
}
// Memcached example action
public function action_memcached()
{
// Try to get data from cache
$value = Cache::get('servbay_memcached_key');
if ($value === false) {
// If not in cache, set data
$value = 'Hello Memcached from ServBay!';
Cache::set('servbay_memcached_key', $value, 60); // Cache for 60 seconds
$value .= ' (from cache)';
} else {
$value .= ' (cached)';
}
return Response::forge($value);
}
// Redis example action
public function action_redis()
{
// Get Redis instance (default connection)
$redis = \Redis_Db::instance(); // FuelPHP 1.x uses Redis_Db::instance()
// Or, if using multiple connections, \Redis_Db::instance('connection_name')
// Set data to Redis
$redis->set('servbay_redis_key', 'Hello Redis from ServBay!');
// Get data from Redis
$value = $redis->get('servbay_redis_key');
return Response::forge($value);
}
// MySQL insert example action
public function action_mysql_add()
{
try {
// Insert a record into users table
$result = DB::insert('users')->set([
'name' => 'ServBay Demo User ' . time(), // Use timestamp for uniqueness
'email' => 'demo_user_' . time() . '@servbay.test',
])->execute(); // execute() returns an array with the new inserted ID
return Response::forge('User added with ID: ' . $result[0]);
} catch (\Database_Exception $e) {
// Catch database exceptions, e.g., duplicate email
return Response::forge('Error adding user: ' . $e->getMessage(), 500);
}
}
// MySQL read example action
public function action_mysql()
{
// Query all records from users table
$users = DB::select('id', 'name', 'email')->from('users')->execute()->as_array();
// Return user list as JSON
return Response::forge(json_encode($users, JSON_PRETTY_PRINT));
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
Notes:
- DB and Redis facades are imported (
use Fuel\Core\DB;
,use Fuel\Core\Redis;
) for direct usage. - Cache keys for Memcached and Redis use the
servbay_
prefix to avoid conflicts. - The MySQL insert example adds timestamps for uniqueness and has simple error handling with more practical content.
- In FuelPHP 1.x, use
\Redis_Db::instance()
to get the Redis instance.
Configuring Routes
To access your new controller actions by URL, configure the routes in fuel/app/config/routes.php
. FuelPHP's default routing covers Controller_Welcome
, but you should explicitly add routes for the new actions.
Add or update the returned array in fuel/app/config/routes.php
:
<?php
return array(
'_root_' => 'welcome/index', // Default route to the welcome controller's index action
'_404_' => 'welcome/404', // 404 error page route
// Routes for the new example actions
'memcached' => 'welcome/memcached',
'redis' => 'welcome/redis',
'mysql_add' => 'welcome/mysql_add',
'mysql' => 'welcome/mysql',
// ... other route configurations
);
2
3
4
5
6
7
8
9
10
11
12
13
Website Access & Testing
You can now test your FuelPHP project and service connections in your browser by visiting the domain you set up in ServBay: https://servbay-fuelphp-test.local
.
- Visit Default Page:
https://servbay-fuelphp-test.local
- Expected output:
Hello ServBay!
- Expected output:
- Test Memcached:
https://servbay-fuelphp-test.local/memcached
- First visit:
Hello Memcached from ServBay! (from cache)
(if the cache is working) - Subsequent visits:
Hello Memcached from ServBay! (cached)
(if the cache is working and not expired)
- First visit:
- Test Redis:
https://servbay-fuelphp-test.local/redis
- Expected output:
Hello Redis from ServBay!
(if Redis is running)
- Expected output:
- Add User to MySQL:
https://servbay-fuelphp-test.local/mysql_add
- Expected output:
User added with ID: [the new ID]
(if MySQL is running and the database/table exists)
- Expected output:
- Read User List from MySQL:
https://servbay-fuelphp-test.local/mysql
- Expected output: A JSON array with all records from the
users
table (if MySQL is working and has data)
- Expected output: A JSON array with all records from the
About HTTPS: ServBay configures SSL certificates for local sites by default using either ServBay User CA or ServBay Public CA. If your browser warns about an untrusted certificate, make sure you’ve added ServBay’s CA certificate to your system’s trusted authorities.
Additional Notes
- Make sure in the ServBay main interface that your chosen PHP version, Caddy (or Nginx/Apache), MySQL (if needed), Redis (if needed), Memcached (if needed), and other services are running.
- Be sure to manually create the
fuel_dev
database with ServBay’s database management tools (or use another existing database as configured indb.php
). FuelPHP’s migration tooloil refine migrate
will create tables but not the database itself. - The public entry point for FuelPHP is
public/index.php
, so in ServBay’s Websites configuration, always set the Website Root Directory to the project’spublic
subfolder.
Summary
With ServBay, you can easily set up a complete local development environment for FuelPHP projects on macOS. This guide covered the process of creating a FuelPHP project, configuring ServBay’s Websites feature, connecting to database and cache services, and using sample code to verify functionality. ServBay’s pre-integrated services and streamlined configuration process can greatly enhance your development efficiency.
We hope this guide helps you start your FuelPHP development journey on ServBay with ease!