Creating and Running a CakePHP Project
What is CakePHP?
CakePHP is an open-source PHP web framework aimed at helping developers quickly build web applications. It is based on the MVC (Model-View-Controller) architecture and provides a powerful set of tools to simplify common tasks in the development process, such as database interactions, form processing, authentication, session management, etc.
Key Features and Advantages of CakePHP
- Rapid Development: Offers rich code generation tools to help developers quickly generate common code structures.
- Flexible and Powerful ORM: The built-in ORM (Object-Relational Mapping) layer simplifies database operations.
- Security: Comes with multiple security features like input validation, CSRF protection, and SQL injection prevention.
- Community Support: Has an active community and a rich ecosystem of plugins.
- Good Documentation: Provides comprehensive documentation and tutorials to help developers get started quickly.
CakePHP is suitable for various projects ranging from small applications to large enterprise systems, helping developers build high-quality web applications quickly.
Creating and Running 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 use ServBay's 'Host' feature to set up the web server and achieve project access through simple configuration.
Note: If you have been an NGINX or Apache user
ServBay uses Caddy as the web server by default. For users migrating from NGINX and Apache to ServBay, there are some key changes to be aware of:
Caddy Configuration
ServBay has Caddy built-in, and the default configuration has been optimized and debugged. Developers only need to manage sites through ServBay's 'Host' feature without manually modifying Caddy configuration files.
Rewrite Rules and .htaccess
In NGINX and Apache, developers usually need to write rewrite rules and .htaccess files to handle URL rewrites and other configurations themselves. However, ServBay has already configured Caddy's rules out of the box, so developers generally don't need to write these rules unless there are special requirements.
Learn More
For more information, refer to Rewrite and htaccess, How to migrate Apache websites to ServBay, and How to migrate NGINX websites to ServBay.
Creating a CakePHP Project
TIP
ServBay recommends developers place websites in the /Applications/ServBay/www
directory for easy management.
Install Composer
ServBay comes with Composer pre-installed, so no separate installation is needed.
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
Enter the newly created CakePHP project directory:
bashcd /Applications/ServBay/www/servbay-cakephp-app
1
Initial Configuration
Configure Environment Variables
Configure the database connection information and other environment variables in the
config/app_local.php
file. Ensure the following configurations 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
Configuring the Web Server
Using ServBay's 'Host' feature, access the CakePHP project through the web server. In ServBay's 'Host' settings, add a new host:
- Name:
My First CakePHP Dev Site
- Domain:
servbay-cakephp-test.local
- Site Type:
PHP
- PHP Version: Choose
8.3
- Site Root Directory:
/Applications/ServBay/www/servbay-cakephp-app/webroot
For detailed setup steps, refer to Adding the First Website.
Adding Sample Code
Add the following code in the config/routes.php
file to output "Hello ServBay!":
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
Add the following code in 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
Accessing the Website
Open a browser and visit https://servbay-cakephp-test.local
, you will see the page output Hello ServBay!
.
NoSQL Database Example
Memcached Example
Install the Memcached Extension
In ServBay, the Memcached extension is pre-installed, so no additional installation is needed.
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 in the
config/routes.php
file:php$routes->connect('/memcached', ['controller' => 'Pages', 'action' => 'memcached']);
1Using Memcached
Use caching 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 the Redis Extension
In ServBay, the Redis extension is pre-installed, so no additional installation is needed.
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 in the
config/routes.php
file:php$routes->connect('/redis', ['controller' => 'Pages', 'action' => 'redis']);
1Using Redis
Use caching 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
Creating Database Structure and Migration Files
Create Migration File
Use CakePHP's Bake tool to create a migration file:
bashbin/cake bake migration CreateUsers name:string email:string:unique
1Run Migration
Use the CakePHP command to run the migration 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 in 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
Save the following code in 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
8Write User Data
Write 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 in 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
Save the following code in 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
8Write User Data
Write 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 using the functionalities provided by ServBay to manage and access your project, while connecting to multiple databases and invoking data.