Introduction to CakePHP
CakePHP is a PHP framework, that is, a ready-made skeleton of a site: routing, database access, forms and validation are already there. Its main idea is convention over configuration: if you name files by the rules, the framework connects them on its own. This course targets CakePHP 5.
What you need
PHP 8.1 or newer with the mbstring and intl extensions, the Composer package manager and a database: MySQL, PostgreSQL or SQLite.
Creating a project
composer create-project --prefer-dist cakephp/app:~5.0 blogThe command creates the blog folder and downloads the framework into it. If Composer asks about folder permissions, answer Y.
Running
cd blog
bin/cake serverOpen http://localhost:8765. A welcome page appears with an environment check: PHP version, folder permissions, database connection. The database line is red for now; it is set up later. Stop the server with Ctrl+C.
Project folders
blog/
├── bin/ the cake command
├── config/ settings and routes
├── src/ application code
│ ├── Controller/
│ ├── Model/
│ └── View/
├── templates/ page templates
├── webroot/ index.php, styles, scripts, images
├── tests/ tests
├── tmp/ cache and temporary files
├── logs/ log files
└── vendor/ the framework and packagesAlmost all work happens in three folders: config, src and templates. The vendor folder is filled by Composer and is never edited.
The first page
Create two files by hand. A controller is a class that prepares data for a page:
// src/Controller/HelloController.php
namespace App\Controller;
class HelloController extends AppController
{
public function index(): void
{
$this->set('name', 'CakePHP');
}
}A template is a file with the page markup, templates/Hello/index.php:
<h1>Hello, <?= h($name) ?>!</h1>Open http://localhost:8765/hello and the page shows "Hello, CakePHP!". No route was written: for the /hello address the framework found HelloController, the index() method and the template in the Hello folder by itself. These are conventions, the subject of the next lesson.
Debug panel
The DebugKit icon is visible in the bottom right corner of the page. A click opens a panel with database queries, template variables, request data and timings. The panel exists only in development mode.
Common mistake
The bin/cake command works only from the project root. Running it from another folder gives "command not found" or "No such file". Go to the project first with cd blog. In the Windows command prompt use a backslash: bin\cake server.