Create and Run a CakePHP Project
What is CakePHP?
CakePHP is an open-source PHP web framework designed to help developers build web applications quickly. It is based on the MVC (Model-View-Controller) architecture and provides a powerful set of tools that simplify common development tasks such as database interaction, form handling, authentication, and session management.
Key Features and Advantages of CakePHP
- Rapid Development: Offers rich code generation tools that help developers quickly generate common code structures.
- Flexible and Powerful ORM: The built-in ORM (Object-Relational Mapping) layer simplifies database operations.
- Security: Built-in security features such as input validation, CSRF protection, and SQL injection prevention.
- Community Support: Active community and a rich plugin ecosystem.
- Good Documentation: Provides extensive documentation and tutorials to help developers get started quickly.
CakePHP is suitable for projects ranging from small applications to large enterprise systems, helping developers to quickly build high-quality web applications.
Create and Run a CakePHP Project Using ServBay
In this article, we will use the PHP environment provided by ServBay to create and run a CakePHP project. We will utilize ServBay's "Host" feature to set up a web server and configure the project for access with simple settings.
Note: If You Have Used NGINX or Apache Before
ServBay uses Caddy as the web server by default. There are some key changes to note for users migrating from NGINX and Apache to ServBay:
Caddy Configuration
ServBay comes with Caddy pre-installed and pre-configured. Developers only need to manage sites through ServBay's "Host" feature without manually editing the Caddy configuration file.
Rewrite Rules and .htaccess
In NGINX and Apache, developers typically write their own rewrite rules and .htaccess files to handle URL rewriting and other configurations. However, ServBay already provides optimized Caddy rules out-of-the-box, so developers need not write these rules unless there are special requirements.
Learn More
For more information, refer to Rewrite and htaccess, How to Migrate Apache Site to ServBay, and How to Migrate NGINX Site to ServBay.
Create a CakePHP Project
TIP
ServBay recommends that developers place their websites in the /Applications/ServBay/www
directory for easier management.
Install Composer
ServBay comes with Composer pre-installed, so no separate installation is required.
Create a CakePHP Project
Use Composer to create a new CakePHP project:
bashcd /Applications/ServBay/www mkdir servbay-cakephp-app cd servbay-cakephp-app composer create-project --prefer-dist cakephp/app .
1
2
3
4Enter the Project Directory
Navigate to the newly created CakePHP project directory:
bashcd /Applications/ServBay/www/servbay-cakephp-app
1
Initial Configuration
Configure Environment Variables
Configure database connection information and other environment variables in the
config/app_local.php
file. Ensure the following settings are correctly set:php'Datasources' => [ 'default' => [ 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'password', 'database' => 'servbay_cakephp_app', 'url' => env('DATABASE_URL', null), ], ],
1
2
3
4
5
6
7
8
9
Configure Web Server
Use ServBay's "Host" feature to access the CakePHP project via the web server. In the Host settings of ServBay, add a new host:
- Name:
My First CakePHP Dev Site
- Domain:
servbay-cakephp-test.local
- Website Type:
PHP
- PHP Version: Select
8.3
- Website Root Directory:
/Applications/ServBay/www/servbay-cakephp-app/webroot
For detailed setup steps, refer to Adding Your First Website.
Add Sample Code
Add the following code to the config/routes.php
file to output "Hello ServBay!":
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
Add the following code to the src/Controller/PagesController.php
file:
namespace App\Controller;
use Cake\Http\Response;
class PagesController extends AppController
{
public function display()
{
return new Response(['body' => 'Hello ServBay!']);
}
}
2
3
4
5
6
7
8
9
10
11
Access the Website
Open a browser and visit https://servbay-cakephp-test.local
to see the page output Hello ServBay!
.
Example with NoSQL Databases
Memcached Example
Install Memcached Extension
The Memcached extension is already pre-installed in ServBay, so no additional installation is required.
Configure Memcached
Configure Memcached connection information in the
config/app_local.php
file:php'Cache' => [ 'default' => [ 'className' => 'Cake\Cache\Engine\MemcachedEngine', 'servers' => ['127.0.0.1'], ], ],
1
2
3
4
5
6Configure Routes
Add the following code to the
config/routes.php
file:php$routes->connect('/memcached', ['controller' => 'Pages', 'action' => 'memcached']);
1Use Memcached
Use the cache in the controller:
phpuse Cake\Cache\Cache; class PagesController extends AppController { public function memcached() { $cacheKey = 'my_cache_key'; $cachedData = Cache::read($cacheKey); if (!$cachedData) { $cachedData = 'Hello Memcached!'; Cache::write($cacheKey, $cachedData); } return new Response(['body' => $cachedData]); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Open a browser and visit
https://servbay-cakephp-test.local/memcached
Redis Example
Install Redis Extension
The Redis extension is already pre-installed in ServBay, so no additional installation is required.
Configure Redis
Configure Redis connection information in the
config/app_local.php
file:php'Cache' => [ 'default' => [ 'className' => 'Cake\Cache\Engine\RedisEngine', 'server' => '127.0.0.1', 'port' => 6379, ], ],
1
2
3
4
5
6
7Configure Routes
Add the following code to the
config/routes.php
file:php$routes->connect('/redis', ['controller' => 'Pages', 'action' => 'redis']);
1Use Redis
Use the cache in the controller:
phpuse Cake\Cache\Cache; class PagesController extends AppController { public function redis() { $cacheKey = 'my_cache_key'; $cachedData = Cache::read($cacheKey); if (!$cachedData) { $cachedData = 'Hello Redis!'; Cache::write($cacheKey, $cachedData); } return new Response(['body' => $cachedData]); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Open a browser and visit
https://servbay-cakephp-test.local/redis
Relational Database Example
Create Database Schema and Migration Files
Create Migration Files
Use CakePHP's Bake tool to create migration files:
bashbin/cake bake migration CreateUsers name:string email:string:unique
1Run Migration
Use CakePHP commands to run migrations and create database tables:
bashbin/cake migrations migrate
1
MySQL Example
Configure MySQL
Configure MySQL connection information in the
config/app_local.php
file:php'Datasources' => [ 'default' => [ 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'password', 'database' => 'servbay_cakephp_app', 'url' => env('DATABASE_URL', null), ], ],
1
2
3
4
5
6
7
8
9Configure Routes
Add the following code to the
config/routes.php
file:php$routes->connect('/mysql-add', ['controller' => 'Pages', 'action' => 'mysqlAdd']); $routes->connect('/mysql', ['controller' => 'Pages', 'action' => 'mysql']);
1
2Add User Table
Add the following code to the
src/Model/Table/UsersTable.php
file:php<?php namespace App\Model\Table; use Cake\ORM\Table; class UsersTable extends Table { }
1
2
3
4
5
6
7
8Add User Data
Add user data in the controller:
phpuse App\Model\Entity\User; use Cake\ORM\TableRegistry; class PagesController extends AppController { public function mysqlAdd() { $usersTable = TableRegistry::getTableLocator()->get('Users'); $user = $usersTable->newEntity(['name' => 'ServBay', 'email' => '[email protected]']); if ($usersTable->save($user)) { return new Response(['body' => 'User added']); } return new Response(['body' => 'Failed to add user']); } public function mysql() { $usersTable = TableRegistry::getTableLocator()->get('Users'); $users = $usersTable->find()->all(); return new Response(['body' => 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
25Open a browser and visit
https://servbay-cakephp-test.local/mysql-add
andhttps://servbay-cakephp-test.local/mysql
PostgreSQL Example
Configure PostgreSQL
Configure PostgreSQL connection information in the
config/app_local.php
file:php'Datasources' => [ 'default' => [ 'host' => '127.0.0.1', 'driver' => Postgres::Class, 'username' => 'root', 'password' => 'password', 'database' => 'servbay_cakephp_app', 'url' => env('DATABASE_URL', null), ], ],
1
2
3
4
5
6
7
8
9
10Configure Routes
Add the following code to the
config/routes.php
file:php$routes->connect('/pgsql-add', ['controller' => 'Pages', 'action' => 'pgsqlAdd']); $routes->connect('/pgsql', ['controller' => 'Pages', 'action' => 'pgsql']);
1
2Add User Table
Add the following code to the
src/Model/Table/UsersTable.php
file:php<?php namespace App\Model\Table; use Cake\ORM\Table; class UsersTable extends Table { }
1
2
3
4
5
6
7
8Add User Data
Add user data in the controller:
phpuse App\Model\Entity\User; use Cake\ORM\TableRegistry; class PagesController extends AppController { public function pgsqlAdd() { $usersTable = TableRegistry::getTableLocator()->get('Users'); $user = $usersTable->newEntity(['name' => 'ServBay', 'email' => '[email protected]']); if ($usersTable->save($user)) { return new Response(['body' => 'User added']); } return new Response(['body' => 'Failed to add user']); } public function pgsql() { $usersTable = TableRegistry::getTableLocator()->get('Users'); $users = $usersTable->find()->all(); return new Response(['body' => 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
25Open a browser and visit
https://servbay-cakephp-test.local/pgsql-add
andhttps://servbay-cakephp-test.local/pgsql
Through the above steps, you have successfully created and run a CakePHP project, used ServBay's features to manage and access your project, and connected and queried various databases.