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 allows Phalcon to deliver extremely low resource consumption and blazing execution speed, outperforming most traditional PHP frameworks. Following the MVC (Model-View-Controller) architecture pattern, Phalcon provides a comprehensive set of feature-rich components—including ORM (Object-Relational Mapping), template engine, routing, caching, events manager, and others—enabling developers to rapidly build robust and high-performance web applications and APIs.
Key Features and Advantages of Phalcon
- Exceptional Performance: Runs as a C extension, eliminating the overhead of parsing and loading PHP scripts, thus delivering native-level performance.
- Resource Efficiency: Minimal memory usage, making it ideal for applications with demanding performance and scalability needs.
- Comprehensive Features: Most core components required for web application development are built-in, reducing dependency on third-party libraries.
- Easy to Use: Provides a clear and consistent API with thorough documentation, enabling even newcomers to quickly get started.
- Highly Decoupled: Components are designed independently, allowing developers the flexibility to use or replace specific parts as needed.
- Security: Includes various security-oriented components, such as input filtering and CSRF protection.
Phalcon is an ideal choice for building high-performance, scalable web applications and APIs, particularly suitable for projects requiring strict speed and resource efficiency.
Creating and Running a Phalcon Project with ServBay
ServBay is a local web development environment designed for macOS, integrating multiple versions of PHP, databases (MySQL, PostgreSQL, MongoDB, Redis), web servers (Caddy, Nginx, Apache), and other developer tools. With ServBay, you can effortlessly set up and manage the runtime environment your Phalcon project needs.
This guide will walk you through using ServBay’s PHP environment to create a basic Phalcon project, configure the web server for accessibility, and show how to integrate both relational (MySQL) and NoSQL (Redis) databases.
Prerequisites
Before you begin, please ensure the following:
- ServBay is installed and running: Make sure ServBay is successfully installed and started on your macOS system.
- Required PHP version is enabled: In ServBay, ensure the PHP version you plan to use is enabled.
- Phalcon module is enabled: ServBay comes with the Phalcon module pre-installed, but it may not be enabled by default. Be sure to enable the Phalcon extension for the relevant PHP version and restart the PHP service as described in How to enable the built-in Phalcon module in ServBay.
- Composer is available: ServBay includes Composer by default, so separate installation is not required. Ensure you can run the
composer
command directly in your terminal.
Different Versions of Phalcon and DevTools
The versions of the Phalcon framework and its corresponding DevTools (Phalcon DevTools) need to be compatible with the PHP version you are using. The table below shows the typical PHP versions and the recommended Phalcon framework and DevTools pairings:
PHP Version | Recommended Phalcon Framework | Recommended Phalcon DevTools | 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 (patched repo) | It’s recommended to use a community-maintained patched version for better compatibility. |
Important: For PHP 8.x and above, the official Phalcon DevTools may not be fully compatible. It is recommended to use a patched version maintained by the community. The following project creation steps will include instructions on using Composer to install the patched DevTools.
Creating a Phalcon Project
Recommended Project Location
For easier management, ServBay recommends placing all your website projects under the default web root directory /Applications/ServBay/www
. This example will create the project in that directory.
Navigate to the Web Root and Create a Project Folder
Open the terminal, navigate to ServBay’s web root, and create a new folder for your Phalcon project (e.g.,
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 toolset to help developers generate code, create project skeletons, manage database migrations, and more. We’ll use Composer to install it. The command varies slightly 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
patched version): Official DevTools may not support PHP 8.x properly, so use the community-maintained patched version via Composer. In your project root (/Applications/ServBay/www/servbay-phalcon-app
), create or updatecomposer.json
with the patched repo 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 under the project root (servbay-phalcon-app
), and DevTools’ executable will be atvendor/bin/phalcon
.Create Project Skeleton Using Phalcon DevTools
With DevTools installed, use the CLI command to generate the basic structure for your Phalcon project. The actual code will be placed in a subdirectory (also named
servbay-phalcon-app
, as this is DevTools’ default behavior):bashvendor/bin/phalcon project servbay-phalcon-app
1This will create a new subdirectory
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app
and generate a complete Phalcon project skeleton within it.Enter the Project Code Directory
Move into the newly created project code directory—all subsequent operations happen here:
bashcd servbay-phalcon-app
1You should now be at
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app
.
Configuring the Project Environment
Phalcon project configuration is typically centralized in the app/config/config.php
file. Here, you need to set up database connection info, application paths, and other crucial settings.
Edit the Configuration File
Open
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/app/config/config.php
in your favorite code editor. Locate or add the database section. ServBay’s default MySQL/MariaDB user isroot
, and the default password is empty; however, for security, we strongly recommend setting a strong password.password
here is a placeholder—please update it to your actual config. The database nameservbay_phalcon_app
is a sample name for this demo (you may need to create this database manually).phpreturn new \Phalcon\Config([ // ... other settings ... 'database' => [ 'adapter' => 'Mysql', // or 'Postgres', etc. 'host' => '127.0.0.1', 'username' => 'root', // Default ServBay root user 'password' => 'password', // <-- Update to your database password 'dbname' => 'servbay_phalcon_app', // <-- Update to your database name ], // ... other settings ... ]);
1
2
3
4
5
6
7
8
9
10
11Important: Ensure that the relevant database service (MySQL or MariaDB) is running in ServBay, that the user and password match this config, and that you have created the
servbay_phalcon_app
database. You can manage databases and users using ServBay’s tools such as phpMyAdmin or Adminer.
Configuring the Web Server (Using ServBay’s Website Feature)
To access your Phalcon project via browser, configure a virtual host through ServBay’s Websites feature, pointing it to the public directory of your project.
- Open the ServBay application
- Go to the “Websites” setting: In the main interface, click the “Websites” option.
- Add a new website: Click the add website button.
- Name: Enter a recognizable name, e.g.,
My First Phalcon Dev Site
. - Domain: Enter a domain you’ll use in the browser, e.g.,
servbay-phalcon-test.local
. ServBay will resolve.local
domains to localhost. - Website Type: Select
PHP
. - PHP Version: Choose the PHP version with the Phalcon module enabled.
- Website Root Directory: This is key—Phalcon’s entry file
index.php
is typically in thepublic
folder. Set the website root to/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/public
.
- Name: Enter a recognizable name, e.g.,
- Save settings: Save the new site configuration. ServBay will auto-apply changes, which may require a web server (Caddy or Nginx) restart.
For detailed steps, see Adding Your First Website. Once configuration is complete, ServBay will handle local DNS and web server setup automatically.
Adding Sample Code
Let’s add some simple code to verify your project is running correctly.
Configure Routing
Edit
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/app/config/routes.php
and add a rule to handle requests to/
:php<?php use Phalcon\Mvc\Router; $router = new Router(false); // Define default route, mapping '/' to IndexController’s indexAction $router->add( '/', [ 'controller' => 'index', 'action' => 'index', ] ); // ... Add other routes 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 the Controller
Edit (or create, if missing)
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/app/controllers/IndexController.php
, and add a simpleindexAction
:php<?php namespace App\Controllers; // Ensure the namespace matches use Phalcon\Mvc\Controller; class IndexController extends Controller { // Handles requests to '/' public function indexAction() { // Return a simple string response return 'Hello ServBay!'; } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Accessing the Website
After saving all files and ensuring ServBay is running, open your web browser and go to the configured domain:
https://servbay-phalcon-test.local
If everything is set up correctly, you should see Hello ServBay!
displayed in your browser.
Integrating Databases
Phalcon offers a powerful database abstraction layer and ORM. ServBay comes with various databases pre-integrated, making it easy to connect them to your Phalcon projects. Below, we’ll use MySQL and Redis as examples.
Relational Database Example: MySQL
Here’s how to connect to ServBay’s MySQL service using Phalcon’s database adapter and perform simple insert/query operations:
Create the Database Structure (Using Migrations)
Phalcon DevTools support database migrations—version control for your database schema.
Generate migration file: In your project code directory (
/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app
), generate an empty migration file:bashvendor/bin/phalcon migration generate
1This creates a new migration file in the
migrations
directory—filename likeYYYYMMDDHHMMSS_MigrationName.php
.Edit the migration file: Edit the generated file’s
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 should 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, such as dropping 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: Be sure the class name (e.g.,
UsersMigration_100
) matches the filename, which usually includes a timestamp and class name.Run the migration: In your project code directory, run DevTools to execute the migration and create the
users
table:bashvendor/bin/phalcon migration run
1If you get connection errors, check your
app/config/config.php
database settings and whether the MySQL/MariaDB service is running in ServBay.
Configure Database Connection (done earlier)
Make sure your
'database'
config inapp/config/config.php
targets the ServBay MySQL/MariaDB service (defaulthost
is127.0.0.1
, port3306
, userroot
, and password as set).Add Sample Routes
Edit
app/config/routes.php
to add routes for inserting and querying user data:php<?php use Phalcon\Mvc\Router; $router = new Router(false); $router->add('/', [ 'controller' => 'index', 'action' => 'index', ]); // Route for inserting user data $router->add( '/mysql-add', [ 'controller' => 'index', 'action' => 'mysqlAdd', ] ); // Route for querying 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 Controller
Edit
app/controllers/IndexController.php
, addingmysqlAddAction
andmysqlAction
methods for database operations. We’ll use Phalcon’s database connection service directly:php<?php namespace App\Controllers; use Phalcon\Mvc\Controller; use Phalcon\Db\Adapter\Pdo\Mysql; // Import MySQL adapter use Phalcon\Db\Enum; // For fetchAll mode constants class IndexController extends Controller { public function indexAction() { return 'Hello ServBay!'; } // Example: Insert user data public function mysqlAddAction() { // Get the database connection from the DI container (preferred), or create a new one (shown here for demo) $connection = new Mysql([ 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'password', // <-- Update to your db password 'dbname' => 'servbay_phalcon_app', 'charset' => 'utf8mb4', // Recommended charset ]); // Insert a sample user $success = $connection->insert( 'users', // Table ['ServBay Demo User', '[email protected]'], // Values ['name', 'email'] // Columns ); // Output result echo $success ? 'User added successfully.' : 'Failed to add user.'; } // Example: Query and output user data public function mysqlAction() { // Get database connection $connection = new Mysql([ 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'password', // <-- Update to your db password 'dbname' => 'servbay_phalcon_app', 'charset' => 'utf8mb4', // Recommended charset ]); // Fetch all users $users = $connection->fetchAll('SELECT * FROM users', Enum::FETCH_ASSOC); // Return result 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 real-world applications, it’s best to register the database connection in the DI container and inject it into controllers, rather than creating connections on every action.
Test the Sample
- Open your browser and go to
https://servbay-phalcon-test.local/mysql-add
. On success, you’ll see "User added successfully." - Then visit
https://servbay-phalcon-test.local/mysql
to see theusers
table data (including the new entry) in JSON.
- Open your browser and go to
NoSQL Database Example: Redis
Let's use the Redis service provided by ServBay as a cache in your Phalcon project.
Install Redis Extension
ServBay’s PHP packages usually include commonly used extensions such as Redis. No need for separate PECL/manual installation; just make sure the Redis extension is checked/enabled for your chosen PHP version via ServBay.
Configure Redis Connection
Add Redis connection settings to
app/config/config.php
. ServBay’s Redis runs at127.0.0.1:6379
by default.phpreturn new \Phalcon\Config([ // ... other settings ... 'cache' => [ 'adapter' => 'Redis', 'host' => '127.0.0.1', 'port' => 6379, 'index' => 0, // Redis database index (default 0) 'persistent' => false, // Use persistent connection? 'auth' => null, // Set password if your Redis uses one ], // ... other settings ... ]);
1
2
3
4
5
6
7
8
9
10
11
12Add Sample Route
Edit
app/config/routes.php
and add a route to demonstrate Redis caching: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 Controller
Edit
app/controllers/IndexController.php
, and add aredisAction
method to demonstrate Redis caching:php<?php namespace App\Controllers; use Phalcon\Mvc\Controller; use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Db\Enum; use Phalcon\Cache\Adapter\Redis; // Import Redis adapter use Phalcon\Storage\SerializerFactory; 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 serializer factory $serializerFactory = new SerializerFactory(); // Redis cache settings—should match the 'cache' config in config.php $options = [ 'defaultSerializer' => 'Json', // Use JSON for storing data 'lifetime' => 3600, // Cache TTL in seconds (e.g., 1 hour) 'host' => '127.0.0.1', 'port' => 6379, 'index' => 0, // Redis DB index // 'auth' => 'your_redis_password', // Set if password is used ]; // Create Redis cache adapter instance $cache = new Redis($serializerFactory, $options); $cacheKey = 'my_servbay_redis_cache_key'; $cachedData = $cache->get($cacheKey); // Attempt to get data from cache if ($cachedData === null) { // Not found: fetch and store echo "Data not found in cache, fetching from source..."; $cachedData = 'Data fetched from source: Hello Redis from ServBay!'; $cache->set($cacheKey, $cachedData); // Save to cache echo "Data stored in cache."; } else { // Data found in cache echo "Data found in cache: "; } // Return (cached or just set) data 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
68Note: In real applications, it’s best to register cache settings as services in the DI container for easy global access.
Test Redis Cache
Open your browser and go to
https://servbay-phalcon-test.local/redis
:- On first visit, you’ll see "Data not found in cache, fetching from source...Data stored in cache." along with "Data fetched from source: Hello Redis from ServBay!"
- On subsequent visits within the cache validity period, you’ll see "Data found in cache: " plus "Data fetched from source: Hello Redis from ServBay!", confirming retrieval from Redis cache.
FAQ
- Q: What if I get a 404 Not Found error?
- A: Make sure your “Website Root Directory” is correctly set to the
public
folder of your Phalcon project (/Applications/ServBay/www/servbay-phalcon-app/servbay-phalcon-app/public
). Check that the corresponding web server (Caddy or Nginx) is running in ServBay and your local DNS resolves the domain.
- A: Make sure your “Website Root Directory” is correctly set to the
- Q: “Class 'Phalcon\Mvc\Application' not found” or missing Phalcon module error?
- A: This means the Phalcon extension isn’t enabled for your chosen PHP version. Go back to the ServBay UI, ensure the right PHP version has Phalcon enabled, and restart PHP. See How to enable the built-in Phalcon module in ServBay.
- Q: Database connection fails?
- A: Double-check your
app/config/config.php
database settings (host, username, password, database name). Ensure MySQL/MariaDB is running in ServBay, your database user can connect and has permissions, and the database exists.
- A: Double-check your
Conclusion
With ServBay, you can easily set up a high-performance local development environment for the Phalcon framework. This guide walks you through project bootstrapping, web server setup, and integrating MySQL and Redis databases. ServBay’s integrated packages and user-friendly interface greatly streamline the configuration and maintenance of your local development stack, letting you focus on developing your Phalcon applications. We hope this guide helps you start fast and efficiently with ServBay and Phalcon for powerful web development!