Creating and Running a Phalcon Project
What Is Phalcon?
Phalcon is an open-source, high-performance PHP web framework implemented as a C extension. This unique approach gives Phalcon exceptionally low resource usage and extraordinary execution speed, significantly outperforming most traditional PHP frameworks. Phalcon follows the MVC (Model-View-Controller) architecture and offers developers a wide array of powerful components, including ORM, template engine, routing, caching, and an event manager, enabling rapid development of robust, high-speed web applications and APIs.
Key Features and Advantages of Phalcon
- Exceptional Performance: As a C extension, Phalcon sidesteps the overhead of PHP script parsing and loading, delivering native-level performance.
- Resource Efficiency: Extremely low memory footprint, ideal for applications with demanding scalability and performance requirements.
- Comprehensive Functionality: Built-in core components for web development reduce reliance on third-party libraries.
- Ease of Use: Clear and consistent APIs, along with thorough documentation, make Phalcon accessible even for newcomers.
- Highly Decoupled: Components are designed independently, allowing developers to use or swap out parts as needed.
- Security: Offers a suite of security features, including input filtering and CSRF protection.
Phalcon is an excellent choice for building high-performance, scalable web applications and APIs, especially when speed and resource efficiency are critical.
Creating and Running a Phalcon Project Using ServBay
ServBay is a local web development environment specially designed for macOS. It comes bundled with multiple versions of PHP, databases (such as MySQL, PostgreSQL, MongoDB, Redis), web servers (Caddy, Nginx, Apache), and other developer tools. With ServBay, you can easily set up and manage the ideal runtime for your Phalcon projects.
This guide walks you through creating a basic Phalcon project using ServBay’s PHP environment, configuring the web server for access, and integrating both relational (MySQL) and NoSQL (Redis) databases.
Prerequisites
Before getting started, make sure you meet the following requirements:
- ServBay is installed and running: Ensure ServBay is successfully installed and launched on your macOS system.
- Required PHP version enabled: In ServBay, make sure the PHP version you intend to use is enabled.
- Phalcon module enabled: ServBay includes the Phalcon module, but it may not be enabled by default. Follow the instructions in How to Enable ServBay’s Built-in Phalcon Module to enable the Phalcon extension for your chosen PHP version and restart the PHP service.
- Composer available: ServBay comes with Composer pre-installed, so you don’t need to install it yourself. Make sure you can use the
composer
command directly in the terminal.
Phalcon Versions and DevTools Compatibility
The Phalcon framework and its official development tools (Phalcon DevTools) must be compatible with your PHP version. The table below shows commonly used PHP versions and recommended corresponding Phalcon framework and DevTools versions:
PHP Version | Recommended Phalcon Version | Recommended Phalcon DevTools Version | Notes |
---|---|---|---|
PHP 5.6, 7.0, 7.1 | Phalcon 3.4.5 | 3.4.x | |
PHP 7.2, 7.3, 7.4 | Phalcon 4.1.2 | ~4.1 (or 4.3.x ) | |
PHP 8.0, 8.1, 8.2 | Phalcon 5.x | 5.0.x (official) | Official DevTools may have compatibility issues on PHP 8.x. |
PHP 8.3, 8.4 | Phalcon 5.x | dev-master (use fixed community repo) | It’s recommended to use a community-maintained fixed version. |
Important: For PHP 8.x and above, the official Phalcon DevTools may not be fully compatible. It’s recommended to use the fixed version maintained by the community. The following project creation steps include instructions on how to install the fixed DevTools via Composer.
Creating a Phalcon Project
Recommended project directory
For easier management, ServBay suggests placing all web projects in the default site root directory: /Applications/ServBay/www
. This example will use this directory to create the project.
Navigate to the site root and create a project folder
Open your terminal, go to ServBay’s site root, and create a new folder for your Phalcon project (for example,
servbay-phalcon-app
):bashcd /Applications/ServBay/www mkdir servbay-phalcon-app cd servbay-phalcon-app
1
2
3Install Phalcon DevTools
Phalcon DevTools is a CLI toolkit for rapid code generation, project scaffolding, and database migrations. It’s installed via Composer. Installation varies a bit depending on your PHP version:
For PHP 5.6, 7.0, 7.1 (Phalcon DevTools
^3.4
):bashcomposer require phalcon/devtools:"^3.4"
1For PHP 7.2, 7.3, 7.4 (Phalcon DevTools
~4.1
):bashcomposer require phalcon/devtools:"~4.1"
1For PHP 8.0, 8.1, 8.2, 8.3, 8.4 (Phalcon DevTools
dev-master
, fixed version): As the official DevTools may not fully support PHP 8.x, use Composer to install the community-maintained fixed version. In your project root (/Applications/ServBay/www/servbay-phalcon-app
), create or editcomposer.json
with the following configuration:json{ "repositories": [ { "url": "https://github.com/daleffe/phalcon-devtools-5.x-fixed.git", "type": "git" } ], "require": { "phalcon/devtools": "dev-master" }, "minimum-stability": "dev", "prefer-stable": true }
1
2
3
4
5
6
7
8
9
10
11
12
13Then, run Composer update to install DevTools:
bashcomposer update
1
Composer will create a
vendor
directory in your project root (servbay-phalcon-app
) with the DevTools executable atvendor/bin/phalcon
.Create the project skeleton with DevTools
Now, use the DevTools CLI to generate the basic structure. By default, project code is placed in a subdirectory (named the same as your project):
bashvendor/bin/phalcon project servbay-phalcon-app
1This will create a new subdirectory:
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app
, containing a fully scaffolded Phalcon project.Navigate to the project code directory
Change to your new code directory for further setup:
bashcd servbay-phalcon-app
1You should now be in
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app
.
Configuring the Project Environment
Phalcon project configuration is typically handled in the app/config/config.php
file, including database connection info and app paths.
Edit the config file
Open
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/app/config/config.php
in your favorite editor. Find or add the database configuration block. ServBay’s MariaDB/MySQL default user isroot
with no password, but for security, you should set a strong password. Here,password
is a placeholder—change it to your real credentials. The database nameservbay_phalcon_app
is used for this example (make sure to create it).phpreturn new \Phalcon\Config([ // ... other config ... 'database' => [ 'adapter' => 'Mysql', // Or 'Postgres', etc. 'host' => '127.0.0.1', 'username' => 'root', // ServBay default 'password' => 'password', // <-- Change to your actual database password 'dbname' => 'servbay_phalcon_app', // <-- Change to your actual database name ], // ... other config ... ]);
1
2
3
4
5
6
7
8
9
10
11Important: Make sure the relevant database service (MySQL or MariaDB) is running in ServBay and credentials match this configuration. You need to manually create the
servbay_phalcon_app
database, which you can do using ServBay’s database management tools (phpMyAdmin or Adminer).
Setting Up the Web Server (Via ServBay Websites)
To access your Phalcon project in the browser, use ServBay’s Websites feature to configure a virtual host pointing to your project's web-accessible directory.
- Open the ServBay application
- Go to the "Websites" settings: On ServBay’s main interface, click on the "Websites" section.
- Add a new website:
- Name: Enter something descriptive, e.g.,
My First Phalcon Dev Site
. - Domain: Specify the domain you want to use in the browser, e.g.,
servbay-phalcon-test.local
. ServBay automatically maps.local
domains to your computer. - Website type: Select
PHP
. - PHP Version: Choose the version with the enabled Phalcon module.
- Site root directory: Crucial step—Phalcon’s entry file (
index.php
) is in thepublic
folder, so set your root to:/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/public
.
- Name: Enter something descriptive, e.g.,
- Save settings: Save your new site config. ServBay applies the changes automatically; you may need to restart your web server (Caddy or Nginx).
For step-by-step instructions, see Adding Your First Website. ServBay handles domain resolution and web server configuration behind the scenes.
Adding Example Code
Let’s add some simple code to verify your project setup is working.
Configure routing
Edit
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/app/config/routes.php
to add a basic route for the root path/
:php<?php use Phalcon\Mvc\Router; $router = new Router(false); // Define default route: map '/' to IndexController's indexAction $router->add( '/', [ 'controller' => 'index', 'action' => 'index', ] ); // ... Add more route rules as needed ... $router->handle($_SERVER['REQUEST_URI']); return $router;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19Create a controller
Edit
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/app/controllers/IndexController.php
(create it if it doesn’t exist) with a simpleindexAction
method:php<?php namespace App\Controllers; // Ensure correct namespace use Phalcon\Mvc\Controller; class IndexController extends Controller { // Handle requests to '/' public function indexAction() { // Return a simple string as a response return 'Hello ServBay!'; } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Accessing Your Website
Once you’ve saved all files and confirmed ServBay is running, open your browser and visit the domain you set up in ServBay:
https://servbay-phalcon-test.local
If everything is configured correctly, you should see the output Hello ServBay!
.
Integrating Databases
Phalcon provides a powerful database abstraction layer and ORM. ServBay integrates various databases, allowing for easy connection with your Phalcon project. The examples below use MySQL and Redis.
Relational Database Example: MySQL
Here’s how to connect Phalcon to ServBay’s MySQL and perform simple insert and query operations.
Creating the Database Structure (with Migrations)
Phalcon DevTools supports database migrations, a standard method for schema versioning.
Generate migration file: Run the DevTools command in your project directory to generate a blank migration:
bashvendor/bin/phalcon migration generate
1This creates a new migration in the
migrations
folder, named likeYYYYMMDDHHMMSS_MigrationName.php
.Edit the migration file: Open the new migration and edit its
morph
method to define a simpleusers
table:php<?php use Phalcon\Db\Column; use Phalcon\Db\Index; use Phalcon\Migrations\Mvc\Model\Migration; /** * Class UsersMigration_100 */ class UsersMigration_100 extends Migration // Class name must match filename { /** * Run the migrations * * @return void */ public function morph() { $this->morphTable('users', [ 'columns' => [ new Column( 'id', [ 'type' => Column::TYPE_INTEGER, 'autoIncrement' => true, 'notNull' => true, 'primary' => true, ] ), new Column( 'name', [ 'type' => Column::TYPE_VARCHAR, 'size' => 255, 'notNull' => true, ] ), new Column( 'email', [ 'type' => Column::TYPE_VARCHAR, 'size' => 255, 'notNull' => true, 'unique' => true, ] ), ], 'indexes' => [ new Index('PRIMARY', ['id'], 'PRIMARY'), new Index('email_UNIQUE', ['email'], 'UNIQUE'), ], 'options' => [ 'TABLE_ENGINE' => 'InnoDB', 'CHARACTER SET' => 'utf8mb4', 'COLLATE' => 'utf8mb4_unicode_ci', ], ]); } /** * Reverse the migrations * * @return void */ public function down() { // Optional: implement rollback logic, e.g., drop the table // $this->getConnection()->dropTable('users'); } }
1
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
70Note: The class name (e.g.,
UsersMigration_100
) must match the migration file’s class and filename.Run the migration: In the project directory, execute DevTools to apply the migration and create the
users
table:bashvendor/bin/phalcon migration run
1If you encounter connection errors, double-check your database settings in
app/config/config.php
and ensure MySQL/MariaDB is running in ServBay.
Setup database connection (already done above)
Confirm the
'database'
block inapp/config/config.php
points to the correct ServBay MySQL/MariaDB instance (usually host127.0.0.1
, port3306
, userroot
, and your chosen password).Add example routes
Edit
app/config/routes.php
to add routes for inserting and selecting user data:php<?php use Phalcon\Mvc\Router; $router = new Router(false); $router->add('/', [ 'controller' => 'index', 'action' => 'index', ]); // Route to insert user data $router->add( '/mysql-add', [ 'controller' => 'index', 'action' => 'mysqlAdd', ] ); // Route to query user data $router->add( '/mysql', [ 'controller' => 'index', 'action' => 'mysql', ] ); $router->handle($_SERVER['REQUEST_URI']); return $router;
1
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
31Implement database operations in the controller
Edit
app/controllers/IndexController.php
, addingmysqlAddAction
andmysqlAction
for DB operations. Here we use Phalcon’s database adapter directly.php<?php namespace App\Controllers; use Phalcon\Mvc\Controller; use Phalcon\Db\Adapter\Pdo\Mysql; // MySQL adapter use Phalcon\Db\Enum; // For fetchAll mode constants class IndexController extends Controller { public function indexAction() { return 'Hello ServBay!'; } // Insert user example public function mysqlAddAction() { // Get a DB connection directly (normally set up as a service) $connection = new Mysql([ 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'password', // <-- Change to your DB password 'dbname' => 'servbay_phalcon_app', 'charset' => 'utf8mb4', ]); // Insert a demo user record $success = $connection->insert( 'users', // Table name ['ServBay Demo User', 'demo@servbay.test'], // Values ['name', 'email'] // Columns ); // Output result echo $success ? 'User added successfully.' : 'Failed to add user.'; } // Query and display user data public function mysqlAction() { // Get DB connection $connection = new Mysql([ 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'password', // <-- Change to your DB password 'dbname' => 'servbay_phalcon_app', 'charset' => 'utf8mb4', ]); // Query all users $users = $connection->fetchAll('SELECT * FROM users', Enum::FETCH_ASSOC); // Output as JSON header('Content-Type: application/json'); echo json_encode($users); } }
1
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
57Note: In production, set up DB connection in the service container and use dependency injection, rather than creating connections in each action.
Testing the example
- Visit
https://servbay-phalcon-test.local/mysql-add
in your browser. On success, you’ll see "User added successfully." - Visit
https://servbay-phalcon-test.local/mysql
. You should see JSON output of yourusers
table, including the demo record.
- Visit
NoSQL Database Example: Redis
Here's how to use ServBay's Redis service as a cache in your Phalcon project.
Install Redis extension
ServBay’s PHP packages generally include popular extensions like Redis. You don’t need to install manually—just enable the Redis extension for your chosen PHP version.
Configure Redis connection
In
app/config/config.php
, add Redis connection info. ServBay Redis runs at127.0.0.1:6379
.phpreturn new \Phalcon\Config([ // ... other config ... 'cache' => [ 'adapter' => 'Redis', 'host' => '127.0.0.1', 'port' => 6379, 'index' => 0, // Redis DB index (default 0) 'persistent' => false, // Persistent connection 'auth' => null, // Add your password if Redis is gated ], // ... other config ... ]);
1
2
3
4
5
6
7
8
9
10
11
12Add example route
Edit
app/config/routes.php
to add a new route for Redis cache demo:php<?php use Phalcon\Mvc\Router; $router = new Router(false); $router->add('/', [ 'controller' => 'index', 'action' => 'index', ]); $router->add('/mysql-add', [ 'controller' => 'index', 'action' => 'mysqlAdd', ]); $router->add('/mysql', [ 'controller' => 'index', 'action' => 'mysql', ]); // Route for Redis cache demo $router->add( '/redis', [ 'controller' => 'index', 'action' => 'redis', ] ); $router->handle($_SERVER['REQUEST_URI']); return $router;
1
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
32Use Redis cache in the controller
Edit
app/controllers/IndexController.php
to add aredisAction
showing Redis cache usage:php<?php namespace App\Controllers; use Phalcon\Mvc\Controller; use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Db\Enum; use Phalcon\Cache\Adapter\Redis; // Redis cache adapter use Phalcon\Storage\SerializerFactory; // Serializer factory class IndexController extends Controller { public function indexAction() { return 'Hello ServBay!'; } public function mysqlAddAction() { $connection = new Mysql([/* ... */]); $success = $connection->insert(/* ... */); echo $success ? 'User added successfully.' : 'Failed to add user.'; } public function mysqlAction() { $connection = new Mysql([/* ... */]); $users = $connection->fetchAll('SELECT * FROM users', Enum::FETCH_ASSOC); header('Content-Type: application/json'); echo json_encode($users); } // Redis cache demo public function redisAction() { // Create a serializer factory instance $serializerFactory = new SerializerFactory(); // Configure Redis cache options // Note: Keep this in sync with the 'cache' section in app/config/config.php $options = [ 'defaultSerializer' => 'Json', 'lifetime' => 3600, // Cache time in seconds (e.g., 1 hour) 'host' => '127.0.0.1', 'port' => 6379, 'index' => 0, // 'auth' => 'your_redis_password', // Add if needed ]; // Create Redis cache adapter instance $cache = new Redis($serializerFactory, $options); $cacheKey = 'my_servbay_redis_cache_key'; $cachedData = $cache->get($cacheKey); // Try getting cached data if ($cachedData === null) { // No data in cache echo "Data not found in cache, fetching from source..."; $cachedData = 'Data fetched from source: Hello Redis from ServBay!'; $cache->set($cacheKey, $cachedData); // Write to cache echo "Data stored in cache."; } else { // Data found in cache echo "Data found in cache: "; } // Return cached data (or just written) return $cachedData; } }
1
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
69Note: In production, configure caching in the service container for easier app-wide access.
Test the example
Visit
https://servbay-phalcon-test.local/redis
in your browser.- On first visit, you’ll see "Data not found in cache, fetching from source...Data stored in cache." and "Data fetched from source: Hello Redis from ServBay!"
- On subsequent visits (within cache lifetime), you’ll see "Data found in cache:" and "Data fetched from source: Hello Redis from ServBay!", confirming data is retrieved from Redis.
Frequently Asked Questions (FAQ)
- Q: What if I get a 404 Not Found error accessing the site?
- A: Confirm your ServBay website settings point the "Site root directory" to your Phalcon project’s
public
folder (/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/public
). Also, check that ServBay’s web server (Caddy or Nginx) is running and local domain resolution works.
- A: Confirm your ServBay website settings point the "Site root directory" to your Phalcon project’s
- Q: Get an error about missing Phalcon module (e.g., Class 'Phalcon\Mvc\Application' not found)?
- A: Usually, the Phalcon extension isn’t enabled in your PHP version. Go back to the ServBay UI, enable the Phalcon extension for your selected PHP version, and restart PHP. See How to Enable ServBay’s Built-in Phalcon Module.
- Q: Database connection failed?
- A: Double-check the database settings (
host
, username, password, database name) inapp/config/config.php
, ensure the relevant DB service is running in ServBay, and the user has access to the database, which must exist.
- A: Double-check the database settings (
Conclusion
ServBay lets you quickly set up a high-performance local environment for the Phalcon framework. This guide covers building your project skeleton, configuring your web server, and integrating MySQL and Redis databases. With ServBay’s bundled software and simple management interface, local environment setup and maintenance are streamlined, so you can focus on developing your Phalcon application. We hope this guide helps you get started with fast, efficient web development using ServBay and Phalcon!