Learn CAKEPHP with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
1
CakePHP Simple Counter App
<?php
// src/Controller/CounterController.php
namespace App\Controller;
use App\Controller\AppController;
class CounterController extends AppController {
public function initialize(): void {
parent::initialize();
$this->loadComponent('RequestHandler');
if (!$this->request->getSession()->check('count')) {
$this->request->getSession()->write('count', 0);
}
}
public function index() {
$count = $this->request->getSession()->read('count');
$this->set(compact('count'));
}
public function increment() {
$count = $this->request->getSession()->read('count') + 1;
$this->request->getSession()->write('count', $count);
return $this->redirect(['action' => 'index']);
}
public function decrement() {
$count = $this->request->getSession()->read('count') - 1;
$this->request->getSession()->write('count', $count);
return $this->redirect(['action' => 'index']);
}
public function reset() {
$this->request->getSession()->write('count', 0);
return $this->redirect(['action' => 'index']);
}
}
// templates/Counter/index.php
<h2>Counter: <?= $count ?></h2>
<form method='post' action='/counter/increment'><button type='submit'>+</button></form>
<form method='post' action='/counter/decrement'><button type='submit'>-</button></form>
<form method='post' action='/counter/reset'><button type='submit'>Reset</button></form>
Demonstrates a simple CakePHP controller and view for a counter using session for state persistence.