Mode:
Duration:
1
Coding works best on desktop or with an external keyboard.
Coding works best on desktop or with an external keyboard.
Demonstrates a simple CakePHP controller and view for a counter using session for state persistence.
<?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>CakePHP is an open-source PHP framework that follows the MVC (Model-View-Controller) pattern. It provides a structured approach for rapid web application development with conventions, built-in tools for database access, authentication, caching, and more.
Origin & Creator
Created by Michal Tatarynowicz in 2005 and maintained by the Cake Software Foundation.
Industrial Note
CakePHP is often used by PHP teams needing rapid development of enterprise web apps with clean architecture, built-in security, and standardized coding conventions.