Creating and Running a CakePHP Project with ServBay
ServBay is a local web development environment supporting macOS and Windows, integrated with multiple language environments such as PHP, Node.js, Python, Go, and Java, as well as database services like MySQL, PostgreSQL, MongoDB, Redis, and more. It works seamlessly with Caddy or Nginx web servers. ServBay offers a convenient and efficient platform for developers to easily set up and manage local projects.
This article will guide you through creating, configuring, and running a CakePHP project in a ServBay environment. CakePHP is a popular PHP web development framework that follows the MVC (Model-View-Controller) pattern, known for rapid development, powerful ORM, and built-in security features. Paired with ServBay’s user-friendliness, you can kickstart CakePHP development quickly.
What Is CakePHP?
CakePHP is an open-source PHP web application development framework that offers a foundational structure for rapid, organized web app development without compromising flexibility. It follows the “Convention over Configuration” principle to simplify many common development tasks.
Key Features & Advantages of CakePHP
- MVC-based Architecture: Clear code organization, easy to maintain and scale.
- Rapid Development: Includes command-line tool (Bake) to generate code and accelerate development.
- Powerful ORM (Object Relational Mapping): Simplifies database interactions and supports multiple databases.
- Built-in Security: Features CSRF protection, SQL injection prevention, input validation, and more.
- Flexible Templating Engine: Supports various view-layer technologies.
- Active Community & Rich Plugin Ecosystem: Easy to find support and add new features.
- Thorough Documentation: Comprehensive guides and API references are available.
CakePHP is suitable for projects ranging from simple APIs to complex enterprise-level applications.
Setting up the CakePHP Development Environment with ServBay
ServBay provides a streamlined, integrated environment for CakePHP development, including:
- Pre-installed PHP interpreter and common extensions.
- Pre-installed Composer package manager.
- Easily configurable web servers (Caddy/Nginx).
- Integrated database services (MySQL, PostgreSQL, Redis, etc.).
With ServBay, you can skip the hassle of manually installing and configuring these components.
Prerequisites
Before you begin, make sure you have completed the following:
- Install ServBay: Ensure ServBay has been downloaded and successfully installed on macOS.
- Start ServBay Services: Launch the ServBay application and make sure required packages (like PHP, the database you plan to use such as MySQL or PostgreSQL, and cache services like Redis or Memcached) are running. You can manage these from the “Packages” tab in ServBay’s control panel.
- Familiarize Yourself with ServBay Basics: Know how to add and configure websites in ServBay. If you’re new, review the ServBay Basic Usage Guide first.
Creating a CakePHP Project
ServBay recommends keeping your web project files under the /Applications/ServBay/www
directory, making it easier for ServBay to automatically detect and manage your sites.
Open Terminal
Launch the Terminal app in macOS.
Navigate to ServBay Website Root Directory
Change to ServBay’s recommended directory for websites:
bashcd /Applications/ServBay/www
1Create a Project Directory
Create a new subdirectory for your CakePHP project. In this guide, the sample project name is
servbay-cakephp-app
:bashmkdir servbay-cakephp-app cd servbay-cakephp-app
1
2Create CakePHP Project with Composer
ServBay comes with Composer pre-installed. Within the project directory, use Composer to create the CakePHP project skeleton:
bashcomposer create-project --prefer-dist cakephp/app .
1This command downloads and installs the latest stable version of CakePHP and its dependencies into the current directory (
.
).Install ORM Driver (For PostgreSQL)
If you plan to use PostgreSQL, install the PostgreSQL ORM driver:
bashcomposer require cakephp/orm-pgsql
1For MySQL, no extra driver installation is needed; it’s already included with CakePHP core dependencies.
Initial Configuration
After creating your project, you’ll need some basic configuration, especially for database connections.
Configure Environment Variables and Database Connection
CakePHP’s local environment settings are mainly in the
config/app_local.php
file. Edit this file, find theDatasources
section, and set your database connection info. ServBay’s default database username is usuallyroot
, and the default password ispassword
.For example, configure MySQL connection:
php// config/app_local.php 'Datasources' => [ 'default' => [ 'className' => \Cake\Database\Connection::class, 'driver' => \Cake\Database\Driver\Mysql::class, // Or \Cake\Database\Driver\Postgres::class for PostgreSQL 'persistent' => false, 'host' => '127.0.0.1', // Database server address, ServBay defaults to localhost //'port' => '3306', // MySQL default port is 3306, PostgreSQL default is 5432 'username' => 'root', // ServBay default username 'password' => 'password', // ServBay default password 'database' => 'servbay_cakephp_app', // Database name you’ll create 'encoding' => 'utf8mb4', 'timezone' => 'UTC', 'flags' => [], 'cacheMetadata' => true, 'log' => false, /** * Set identifier quoting to true if you are using words like "user" as your table name. * But if you are using words like "cake" you can set it to false. * If you don't know use true. */ 'quoteIdentifiers' => false, /** * Current limitations include the following: * - Most drivers do not support setting isolation levels via PDO options. * Using them will result in an error. * - Not all drivers support setting the charset via PDO options. * Using them will result in an error. * - PDO options are not supported for packaged drivers like Postgres from CakePHP. * For Postgres, you only need to set the encoding. */ 'options' => [], //'url' => env('DATABASE_URL', null), // Uncomment if using DATABASE_URL environment variable ], ],
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
38Adjust the
driver
andport
settings based on your database type (MySQL or PostgreSQL). Make sure thedatabase
name matches the one you’ll create.
Configuring the Web Server (Creating a Site in ServBay)
To access your CakePHP project via a browser, set up a site in ServBay that points to your project directory.
Open ServBay Control Panel
Click the ServBay icon to open the control panel.
Navigate to the “Websites” Tab
In ServBay’s control panel, select “Websites” on the left sidebar (previously called “Hosts”).
Add a New Website
Click the
+
button at the bottom to add a new website. Fill in the following info:- Name: Give your site an easy-to-identify name, e.g.,
My CakePHP Dev Site
. - Domain: Set a local development domain, such as
servbay-cakephp-test.local
. ServBay will automatically point this to localhost. - Site Type: Choose
PHP
. - PHP Version: Select a version compatible with your CakePHP release (e.g., CakePHP 4+ needs PHP 7.4+, CakePHP 5+ needs PHP 8.1+). Example:
8.3
. - Document Root: Important! The web server root for your CakePHP project is not the main project directory, but its internal
webroot
directory. Set it to/Applications/ServBay/www/servbay-cakephp-app/webroot
(replaceservbay-cakephp-app
with your actual project directory name).
- Name: Give your site an easy-to-identify name, e.g.,
Save and Apply Changes
Click “Save” at the bottom right after filling out the fields. ServBay will prompt you to apply changes—confirm it. ServBay automatically configures your web server (Caddy or Nginx) to respond to the domain
servbay-cakephp-test.local
and route requests to your project’swebroot
directory.
For detailed steps, see ServBay documentation: Adding Your First Website.
Verifying Your Setup
You should now be able to access your site through your browser.
Open a browser and hit your configured domain in ServBay, for example https://servbay-cakephp-test.local
.
If everything is set up correctly, you’ll see CakePHP’s default welcome page, confirming that the PHP environment, web server, and site configuration on ServBay are working.
Integrating Database and Cache Services
CakePHP provides a powerful ORM and cache abstraction layer, making it easy to use ServBay’s database and cache services.
Relational Database Example (MySQL / PostgreSQL)
Here’s an example of using CakePHP’s ORM to connect to MySQL or PostgreSQL in ServBay, create a simple users
table, and perform basic CRUD operations.
Create a Database in ServBay
Before running migrations, create a new database in ServBay’s database server. Use ServBay’s database management tool—for example, phpMyAdmin for MySQL/MariaDB, pgAdmin for PostgreSQL, or third-party tools like Navicat or DBeaver—to connect to the service (address usually
127.0.0.1
, username:root
, password:password
), and create a database namedservbay_cakephp_app
.Create ORM Model File
CakePHP’s ORM needs a model file representing the database table. Create a
UsersTable.php
file for yourusers
table.Save the following in
src/Model/Table/UsersTable.php
:php<?php namespace App\Model\Table; use Cake\ORM\Table; use Cake\Validation\Validator; // For validation rules class UsersTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config): void { parent::initialize($config); $this->setTable('users'); // Explicitly specify table name $this->setDisplayField('name'); // Set default display field $this->setPrimaryKey('id'); // Set the primary key // If using timestamp behavior // $this->addBehavior('Timestamp'); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator): Validator { $validator ->scalar('name') ->maxLength('name', 255) ->requirePresence('name', 'create') ->notEmptyString('name'); $validator ->email('email') ->requirePresence('email', 'create') ->notEmptyString('email') ->add('email', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']); // Ensure email uniqueness return $validator; } }
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
49Use Bake Tool to Create Migration File
CakePHP recommends managing the database schema via migrations. In the project root (
/Applications/ServBay/www/servbay-cakephp-app
), use CakePHP’s Bake tool to create a migration for theusers
table:bashbin/cake bake migration CreateUsers name:string email:string:unique
1This generates a migration file containing instructions to create the
users
table withname
(string) and uniqueemail
fields.Run the Database Migration
Execute the migration to create the actual table in the database made earlier:
bashbin/cake migrations migrate
1On success, you’ll see the new
users
table in your database.Configure Database Connection (if not already done)
Ensure the
config/app_local.php
Datasources.default
section matches your database type and credentials.MySQL Example:
php'Datasources' => [ 'default' => [ 'className' => \Cake\Database\Connection::class, 'driver' => \Cake\Database\Driver\Mysql::class, 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'password', 'database' => 'servbay_cakephp_app', // ... other settings ], ],
1
2
3
4
5
6
7
8
9
10
11PostgreSQL Example:
php'Datasources' => [ 'default' => [ 'className' => \Cake\Database\Connection::class, 'driver' => \Cake\Database\Driver\Postgres::class, 'host' => '127.0.0.1', // 'port' => '5432', // default port 'username' => 'root', // ServBay default 'password' => 'password', // ServBay default 'database' => 'servbay_cakephp_app', // ... other settings ], ],
1
2
3
4
5
6
7
8
9
10
11
12
Add Example Routes and Controller Methods
Edit the
config/routes.php
to add routes for adding and listing users:php// config/routes.php use Cake\Routing\RouteBuilder; use Cake\Routing\Router; use Cake\Routing\Route\DashedRoute; Router::defaultRouteClass(DashedRoute::class); Router::scope('/', function (RouteBuilder $routes) { // ... other routes $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']); // Add database example routes $routes->connect('/db-add-user', ['controller' => 'Pages', 'action' => 'dbAddUser']); $routes->connect('/db-list-users', ['controller' => 'Pages', 'action' => 'dbListUsers']); // ... other routes $routes->fallbacks(DashedRoute::class); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18Then, edit
src/Controller/PagesController.php
and add methods for database operations:php<?php namespace App\Controller; use Cake\Http\Response; use Cake\ORM\TableRegistry; use Cake\Datasource\Exception\RecordNotFoundException; // For find exceptions class PagesController extends AppController { /** * Displays a view * * @param array ...$path Path segments. * @return \Cake\Http\Response|null */ public function display(...$path): ?Response { // ... default display method return new Response(['body' => 'Hello ServBay! This is the default page.']); } /** * Database Example: Add User */ public function dbAddUser(): Response { $usersTable = TableRegistry::getTableLocator()->get('Users'); // Get Users table instance // Create new user entity $user = $usersTable->newEntity([ 'name' => 'ServBay Demo User', 'email' => 'servbay-demo@servbay.test' // Example ServBay brand email ]); // Try saving to DB if ($usersTable->save($user)) { return new Response(['body' => 'User added successfully! User ID: ' . $user->id]); } else { // If saving fails (validation errors or other) $errors = $user->getErrors(); // Get validation errors return new Response(['body' => 'Failed to add user. Errors: ' . json_encode($errors)]); } } /** * Database Example: List All Users */ public function dbListUsers(): Response { $usersTable = TableRegistry::getTableLocator()->get('Users'); // Get Users table // Find all users $users = $usersTable->find()->all(); // Output results as JSON return new Response(['body' => json_encode($users->toArray())]); // toArray() converts Collection to array } }
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
58Access the Database Example
In your browser:
- Visit
https://servbay-cakephp-test.local/db-add-user
to add a user. You should see a success message. - Visit
https://servbay-cakephp-test.local/db-list-users
to view all users (now including the one you just added).
- Visit
These steps successfully connect your CakePHP project to a relational database in ServBay and demonstrate basic ORM usage.
Cache Service Example (Memcached / Redis)
CakePHP offers a unified cache API, allowing you to easily switch between cache engines like Memcached or Redis. ServBay comes with the PHP extensions for Memcached and Redis pre-installed, plus runnable services.
First, make sure Memcached or Redis is started from the “Packages” tab in ServBay’s control panel.
Configure Cache Connection
Edit the
config/app_local.php
file, and configure theCache
section.Memcached example:
php// config/app_local.php 'Cache' => [ 'default' => [ 'className' => \Cake\Cache\Engine\MemcachedEngine::class, 'servers' => ['127.0.0.1:11211'], // ServBay default Memcached address and port 'prefix' => 'servbay_cakephp_', // Cache key prefix ], // ... other cache config ],
1
2
3
4
5
6
7
8
9Redis example:
php// config/app_local.php 'Cache' => [ 'default' => [ 'className' => \Cake\Cache\Engine\RedisEngine::class, 'host' => '127.0.0.1', // ServBay default Redis address 'port' => 6379, // ServBay default Redis port 'password' => null, // Add password if Redis requires one 'database' => 0, // Redis DB index 'prefix' => 'servbay_cakephp_', // Cache key prefix ], // ... other cache config ],
1
2
3
4
5
6
7
8
9
10
11
12
Configure whichever cache service you’re using.
Add Example Routes and Controller Methods
Edit
config/routes.php
to add cache example routes:php// config/routes.php // ... other routes $routes->connect('/cache-memcached', ['controller' => 'Pages', 'action' => 'cacheMemcached']); $routes->connect('/cache-redis', ['controller' => 'Pages', 'action' => 'cacheRedis']); // ... other routes
1
2
3
4
5Then, in
src/Controller/PagesController.php
, add methods that read/write cache:php<?php namespace App\Controller; use Cake\Http\Response; use Cake\Cache\Cache; // Import Cache class // ... other use statements class PagesController extends AppController { // ... other methods (display, dbAddUser, dbListUsers) /** * Cache Example: Memcached */ public function cacheMemcached(): Response { // Ensure app_local.php configures 'default' cache as MemcachedEngine $cacheKey = 'servbay_memcached_test_key'; $cachedData = Cache::read($cacheKey); // Try reading from cache $responseBody = ''; if ($cachedData === false) { // Cache miss $responseBody = 'Cache miss! Writing "Hello Memcached!" to cache.'; $dataToCache = 'Hello Memcached!'; Cache::write($cacheKey, $dataToCache, 'default'); // Write to 'default' cache (Memcached) } else { // Cache hit $responseBody = 'Cache hit! Data from cache: ' . $cachedData; } return new Response(['body' => $responseBody]); } /** * Cache Example: Redis */ public function cacheRedis(): Response { // Ensure app_local.php configures 'default' cache as RedisEngine $cacheKey = 'servbay_redis_test_key'; $cachedData = Cache::read($cacheKey); // Try reading from cache $responseBody = ''; if ($cachedData === false) { // Cache miss $responseBody = 'Cache miss! Writing "Hello Redis!" to cache.'; $dataToCache = 'Hello Redis!'; Cache::write($cacheKey, $dataToCache, 'default'); // Write to 'default' cache (Redis) } else { // Cache hit $responseBody = 'Cache hit! Data from cache: ' . $cachedData; } return new Response(['body' => $responseBody]); } }
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
61Access the Cache Example
In your browser:
- If using Memcached, visit
https://servbay-cakephp-test.local/cache-memcached
. The first time you’ll see “Cache miss,” refresh to see “Cache hit.” - If using Redis, visit
https://servbay-cakephp-test.local/cache-redis
. First visit shows “Cache miss,” refresh to see “Cache hit.”
- If using Memcached, visit
This confirms your CakePHP project is connected and using ServBay’s cache services.
Notes
- Database Credentials: ServBay’s default database username and password (
root
/password
) are for local development only. Always use secure credentials in production. - Document Root: Always set the “Document Root” for your ServBay website to the CakePHP project’s
webroot
folder—not the main project folder, in accordance with best practices. - PHP Version Compatibility: Make sure the PHP version in ServBay matches requirements for your CakePHP release. Check official CakePHP documentation for version requirements.
- ServBay Ports: If ServBay’s default ports (such as 80 and 443) are in use by other apps, adjust ServBay preferences to change the ports, and update your hosts file or access using the correct port.
FAQ (Frequently Asked Questions)
- Q: Seeing “Page not found” for
servbay-cakephp-test.local
?- A: Check your ServBay site’s “Document Root”—it must point to
/Applications/ServBay/www/servbay-cakephp-app/webroot
. - Check that ServBay's web server (Caddy/Nginx) is running.
- Make sure your OS hosts file maps
servbay-cakephp-test.local
to127.0.0.1
(ServBay handles this automatically, but verify if needed). - Make sure your CakePHP project's
.htaccess
or web server config is correct (the default inwebroot/.htaccess
is usually fine).
- A: Check your ServBay site’s “Document Root”—it must point to
- Q: Database connection failed?
- A: Make sure the corresponding database service (MySQL/PostgreSQL) is running in ServBay.
- Check the connection info in
config/app_local.php
(host
,port
,username
,password
,database
) matches your ServBay database service. - Confirm you’ve created the
servbay_cakephp_app
database in the server.
- Q: Composer command (
bin/cake
) won’t run?- A: Ensure your current working directory in terminal is the CakePHP project root (
/Applications/ServBay/www/servbay-cakephp-app
). - Confirm that PHP and Composer packages are running in ServBay.
- Check if your terminal can find the
php
command (ServBay adds PHP to your PATH in most cases; try using ServBay’s integrated terminal or set your PATH manually).
- A: Ensure your current working directory in terminal is the CakePHP project root (
Conclusion
ServBay enables a highly efficient local development environment for CakePHP projects. With pre-integrated PHP, Composer, web servers, and database services, ServBay greatly simplifies setup. This guide walks you step-by-step from project creation, basic config, site setup, to integrating relational databases and cache services, helping you get started with CakePHP rapidly. Thanks to ServBay’s convenience, you can focus on writing code—without worrying about the complexities of environment setup.