Creating and Running a CakePHP Project with ServBay
ServBay is a local web development environment designed specifically for macOS. It integrates environments for PHP, Node.js, Python, Go, Java, and more, along with database services such as MySQL, PostgreSQL, MongoDB, and Redis. ServBay pairs with Caddy or Nginx web servers to provide a streamlined and efficient development platform, making it easy for developers to set up and manage projects locally.
This article will guide you through creating, configuring, and running a CakePHP project within the ServBay environment. CakePHP is a popular PHP web development framework that adheres to the MVC (Model-View-Controller) model, known for its rapid development, powerful ORM, and robust built-in security features. With ServBay’s convenience, you can jumpstart your CakePHP development in no time.
What is CakePHP?
CakePHP is an open-source PHP web application framework providing a foundation for rapid and structured web app development without sacrificing flexibility. It follows the "convention over configuration" principle to simplify many common development tasks.
Key Features and Benefits of CakePHP
- MVC Architecture: Clear code structure, easy to maintain and extend.
- Rapid Development: Command line tool (Bake) for code generation speeds up the development process.
- Powerful ORM: Simplifies database interactions and supports multiple database systems.
- Comprehensive Security: Features like CSRF protection, SQL injection prevention, and input validation are built-in.
- Flexible Templating Engine: Supports various view layer technologies.
- Vibrant Community and Plugins: Plenty of support and extension capabilities.
- Thorough Documentation: Comprehensive guides and API references are available.
CakePHP is suitable for building web applications of any size, from simple APIs to complex enterprise systems.
Setting Up a CakePHP Development Environment with ServBay
ServBay offers a convenient integrated environment for CakePHP development, including:
- Pre-installed PHP interpreter with 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 tedious process of installing and configuring these components manually.
Prerequisites
Before you begin, make sure you've completed the following:
- Install ServBay: Download and successfully install ServBay on your macOS system.
- Start ServBay Services: Launch ServBay and ensure required packages (such as PHP, your database of choice like MySQL or PostgreSQL, and cache services like Redis or Memcached) are up and running. You can manage these from the "Packages" tab in the ServBay control panel.
- Familiarity with ServBay Basics: Learn how to add and configure websites in ServBay. If you’re new, read the ServBay Basic Usage Guide first.
Creating a CakePHP Project
ServBay recommends storing all your web projects under the /Applications/ServBay/www
directory. This helps ServBay automatically detect and manage your sites.
Open Terminal
Launch the Terminal app on macOS.
Navigate to the ServBay Web Root
Change to the ServBay recommended project directory:
bashcd /Applications/ServBay/www
1Create a Project Directory
Create a new subdirectory for your CakePHP project, e.g.,
servbay-cakephp-app
:bashmkdir servbay-cakephp-app cd servbay-cakephp-app
1
2Create a CakePHP Project Using Composer
ServBay has Composer pre-installed. In the project directory, scaffold a CakePHP project:
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 users)
If you plan to use PostgreSQL, you’ll need its ORM driver:
bashcomposer require cakephp/orm-pgsql
1For MySQL, no additional driver is needed—it's already included in CakePHP’s core dependencies.
Initial Configuration
After creating your project, you’ll need some basic setup, especially for database connections.
Configure Environment Variables and Database Connection
Local environment configuration for CakePHP is mainly handled in
config/app_local.php
. Edit this file, locate theDatasources
section, and set your database connection. ServBay’s default database user is usuallyroot
, and the password ispassword
.For example, to connect to MySQL:
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 runs this locally by default //'port' => '3306', // MySQL default is 3306, PostgreSQL is 5432 'username' => 'root', // ServBay default 'password' => 'password', // ServBay default 'database' => 'servbay_cakephp_app', // Name of your database to be created '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), // Enable this if you use a 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
and potentiallyport
settings according to your database type (MySQL or PostgreSQL). Ensure thedatabase
value matches your intended database name.
Configuring the Web Server (Creating a Site in ServBay)
To access your CakePHP project in a browser, you’ll need to set up a site in ServBay that points to your project directory.
Open the ServBay Control Panel
Click the ServBay icon to open the control panel.
Go to the “Sites” Tab
In the left sidebar, select “Sites” (previously “Hosts”).
Add a New Site
Click the
+
button at the bottom to add a new site. Fill in the following details:- Name: Give your site a recognizable name, e.g.,
My CakePHP Dev Site
. - Domain: Set a local development domain, such as
servbay-cakephp-test.local
. ServBay automatically points this to your machine. - Site Type: Choose
PHP
. - PHP Version: Select a PHP version compatible with your CakePHP release (e.g., CakePHP 4+ typically requires PHP 7.4+, CakePHP 5+ usually needs PHP 8.1+). Try
8.3
. - Document Root: Important! The web server root is not the project main folder, but its internal
webroot
folder. Set this to/Applications/ServBay/www/servbay-cakephp-app/webroot
(replaceservbay-cakephp-app
with your actual project folder).
- Name: Give your site a recognizable name, e.g.,
Save and Apply Changes
Once done, click the "Save" button in the bottom right. ServBay may prompt you to apply changes—confirm this. ServBay will automatically configure the web server (Caddy or Nginx) to respond to
servbay-cakephp-test.local
and point to your project'swebroot
.
For detailed steps on adding a site, refer to Adding Your First Site in the ServBay docs.
Verifying the Basic Setup
Now you should be able to visit your new site in a browser.
Open your browser and go to the domain you set up in ServBay, e.g., https://servbay-cakephp-test.local
.
If all is configured correctly, you’ll see CakePHP’s default welcome page, indicating that PHP, the web server, and ServBay’s site configuration are working as expected.
Integrating Database and Cache Services
CakePHP offers a powerful ORM and cache abstraction, making it easy to integrate ServBay’s database and caching services.
Example: Relational Database (MySQL / PostgreSQL)
This example demonstrates how to connect a CakePHP project running in ServBay to a MySQL or PostgreSQL database, create a simple users
table, and perform CRUD operations.
Create a Database in ServBay
Before running migrations, create a new database in your chosen database server via ServBay. Use tools such as phpMyAdmin (for MySQL/MariaDB), pgAdmin (for PostgreSQL), or third-party tools like Navicat/DBeaver. Connect with host
127.0.0.1
, userroot
, passwordpassword
, and create a database namedservbay_cakephp_app
.Create an ORM Model File
CakePHP’s ORM requires a model to represent your database table. Create a
UsersTable.php
to represent theusers
table.Save the following to
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'); // Specify the table name explicitly $this->setDisplayField('name'); // Default display field for associations $this->setPrimaryKey('id'); // MySQL primary key // Enable timestamp behavior if needed // $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 unique email 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
49Create a Migration File Using the Bake Tool
CakePHP recommends using migrations for database structure management. In your project root (
/Applications/ServBay/www/servbay-cakephp-app
), generate a migration for theusers
table:bashbin/cake bake migration CreateUsers name:string email:string:unique
1This command generates a migration to create a
users
table with string fields:name
and a uniqueemail
.Run the Migration
Execute migrations to actually create the
users
table in the database you made in step 1:bashbin/cake migrations migrate
1If successful, the
users
table appears in your database.Configure the Database Connection (if not yet set)
Make sure your
config/app_local.php
'sDatasources.default
section is correct for your database.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', // ... more 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 'username' => 'root', // ServBay default 'password' => 'password', // ServBay default 'database' => 'servbay_cakephp_app', // ... more settings ], ],
1
2
3
4
5
6
7
8
9
10
11
12
Add Sample Routes and Controller Methods
Update
config/routes.php
to add endpoints 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']); // ... more routes $routes->fallbacks(DashedRoute::class); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18Edit
src/Controller/PagesController.php
to add database operation methods:php<?php namespace App\Controller; use Cake\Http\Response; use Cake\ORM\TableRegistry; use Cake\Datasource\Exception\RecordNotFoundException; // Exception for not found records 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 a new user entity $user = $usersTable->newEntity([ 'name' => 'ServBay Demo User', 'email' => '[email protected]' // Example email for ServBay brand ]); // Try to save to database if ($usersTable->save($user)) { return new Response(['body' => 'User added successfully! User ID: ' . $user->id]); } else { // Saving failed—maybe validation or other error $errors = $user->getErrors(); 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 instance // Fetch all users $users = $usersTable->find()->all(); // Output 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
58Try Out the Database Demo
Open 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 (should now list one or more users).
- Visit
By following these steps, you’ve successfully connected your CakePHP project running in ServBay to a relational database and performed basic ORM operations.
Example: Cache Services (Memcached / Redis)
CakePHP provides a unified caching API, making it easy to switch between cache engines such as Memcached or Redis. ServBay comes with PHP Memcached and Redis extensions pre-installed, plus corresponding service packages.
First, make sure you have Memcached or Redis running from the "Packages" tab in the ServBay control panel.
Configure Cache Connection
Edit
config/app_local.php
and set up theCache
section as follows: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/port 'prefix' => 'servbay_cakephp_', // Cache key prefix ], // ... other cache configs ],
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, // Fill in if Redis uses a password 'database' => 0, // Redis DB index 'prefix' => 'servbay_cakephp_', // Cache key prefix ], // ... other cache configs ],
1
2
3
4
5
6
7
8
9
10
11
12
Configure according to your preferred cache service.
Add Example Routes and Controller Methods
Update
config/routes.php
to add demo cache endpoints: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
5Edit
src/Controller/PagesController.php
to add demo cache usage:php<?php namespace App\Controller; use Cake\Http\Response; use Cake\Cache\Cache; // Use Cache class // ... other use statements class PagesController extends AppController { // ... other methods (display, dbAddUser, dbListUsers) /** * Cache Example: Using Memcached */ public function cacheMemcached(): Response { // Ensure 'default' cache config uses MemcachedEngine in app_local.php $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 (configured for Memcached) } else { // Cache hit $responseBody = 'Cache hit! Data from cache: ' . $cachedData; } return new Response(['body' => $responseBody]); } /** * Cache Example: Using Redis */ public function cacheRedis(): Response { // Ensure 'default' cache config uses RedisEngine in app_local.php $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 (configured for 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
61Try the Cache Demo
Open your browser:
- If using Memcached, visit
https://servbay-cakephp-test.local/cache-memcached
. The first visit should show “Cache miss”, subsequent refreshes will show “Cache hit.” - If using Redis, visit
https://servbay-cakephp-test.local/cache-redis
. Similarly, the first visit is a miss, then a hit.
- If using Memcached, visit
This confirms your CakePHP project can successfully connect to and use the cache services provided by ServBay.
Tips and Notes
- Database Credentials: ServBay’s default database user/password (
root
/password
) are for local development only. Never use them in production. - Document Root: Always point the site’s document root to the
webroot
directory inside your CakePHP project—not the main directory. This is CakePHP best practice. - PHP Version Compatibility: Double-check that the PHP version you select in ServBay is compatible with your CakePHP version. See the CakePHP docs for requirements.
- ServBay Ports: If default web ports (80, 443) are used by other programs, update the ports in ServBay’s settings, and adjust your hosts file or access via port number as needed.
Frequently Asked Questions (FAQ)
- Q: Getting "Page Not Found" when visiting
servbay-cakephp-test.local
?- A: Check that the site’s document root in ServBay is set to
/Applications/ServBay/www/servbay-cakephp-app/webroot
. - Verify the web server (Caddy/Nginx) in ServBay is running.
- Make sure your system's hosts file maps
servbay-cakephp-test.local
to127.0.0.1
(ServBay handles this automatically, but double-check if needed). - Check that the CakePHP
.htaccess
or web server config is correct (webroot/.htaccess
is usually fine).
- A: Check that the site’s document root in ServBay is set to
- Q: Database connection fails?
- A: Make sure the relevant database service (MySQL/PostgreSQL) is running in ServBay.
- Double-check the connection info (host, port, user, password, database) in
config/app_local.php
matches what ServBay provides. - Ensure the database
servbay_cakephp_app
was created in your DB server.
- Q: Can't run Composer (
bin/cake
) commands?- A: Make sure you’re in the CakePHP project root (
/Applications/ServBay/www/servbay-cakephp-app
) in your terminal. - Ensure PHP and Composer packages are started in ServBay.
- Verify your terminal can find the
php
command (ServBay should add PHP toPATH
—use ServBay’s integrated terminal or manually updatePATH
if needed).
- A: Make sure you’re in the CakePHP project root (
Summary
With ServBay, you can efficiently set up a local development environment for CakePHP projects on macOS. Pre-integrated PHP, Composer, web servers, and database services dramatically simplify setup. This guide covered project creation, basic configuration, web server setup, and how to integrate both relational databases and cache services—so you can kickstart your CakePHP development. With ServBay, you spend less time on environment setup and more time writing code that matters.