Changes from the Original Book
This book is based on the CakePHP 2.x Cookbook. This page summarizes how CakePHP 2 on the Piece of Cake 2 fork differs from the original CakePHP 2.10.24, and lists the pages of this book that were changed from the original.
Differences from CakePHP 2.10.24
| Area | Original CakePHP 2.10.24 | Piece of Cake 2 fork | See |
|---|---|---|---|
| PHP | PHP 5.3 to 7.4 | PHP 8.0 to 8.5 | Installation |
| Installation | Archive download, PEAR or Composer | Composer only (pieceofcake2/cakephp) | Installation |
| Plugins via Composer | Optional | composer/installers settings are required | Configuring composer.json |
| Application layout | app/ | Modern layout (src/, templates/, config/, ...) or app/ | Folder Structure |
| Framework layout | lib/Cake/ | vendor/pieceofcake2/cakephp/src/Cake/ | Migrating from CakePHP 2.10 |
| Class loading | App::uses() | Composer autoloading; App::uses() deprecated (2.13) | Autoloading |
| Bake | Core shell | pieceofcake2/bake plugin | Code Generation with Bake |
| UpgradeShell | Core shell | pieceofcake2/upgrade plugin | Upgrade Shell |
| Cache engines | Includes Xcache and Wincache | Xcache and Wincache removed | Caching |
| Tests | PHPUnit 3.7 | PHPUnit 9.6 | Testing |
| Controller tests | ControllerTestCase::testAction() | Also IntegrationTestTrait and EmailTrait (v2.12.4, backports from CakePHP 5) | Integration Testing |
| Coding standard | CakePHP 2 standard (tabs, array()) | CakePHP 5 codesniffer (4 spaces, []) | Coding Standards |
| CSRF protection | Unsigned tokens; some methods not validated | HMAC-signed tokens; all methods except GET/HEAD/OPTIONS validated | Security Fixes |
| SSL certificates | Bundled cacert.pem (2016) | System CA bundle or composer/ca-bundle | Security Fixes |
String class | Alias of CakeText | Removed; use CakeText | CakeText |
Xml::build() with 'readFile' => false | https:// URLs still fetched (SSRF) | Neither files nor URLs are read | Security Fixes |
CookieComponent 'type' in $components | Ignored (always 'cipher') | Honored | Cookie |
cake server default port | 80 | 8765 | Installation |
| Line breaks in email header values | Sent as is by SmtpTransport; only \r\n removed by MailTransport (header injection) | Removed (folded header lines are kept) | Security Fixes |
View, layout and element names with .. | Can resolve to any file on the server (path traversal) | Must resolve inside the view paths; other files are treated as missing | Security Fixes |
Protocol-relative Auth.redirect URL | Redirects to another host after login (open redirect) | Collapsed to a local path | Security Fixes |
Sort direction in order | Appended to the SQL as given | ASC / DESC with optional NULLS FIRST / NULLS LAST; anything else triggers E_USER_DEPRECATED (v2.12.5), an exception in a future version | Sort Order |
'cipher' encryption (default CookieComponent type) | Default type, insecure, no warning | Deprecated with a logged warning; out-of-range Security.cipherSeed reported; Cookie.type / Cookie.key set the defaults (v2.12.6) | Security Fixes |
| Error pages in debug mode | CakePHP 2 layout | CakePHP 5 style dev_error layout with code excerpts and editor links (v2.12.6) | Debugging |
.env files | Not supported | Loaded by the pieceofcake2/app skeleton (v2.4.0), not by the framework; since v2.5.0 with symfony/dotenv as in Symfony (config/.env, .env.local, .env.{APP_ENV}, .env.{APP_ENV}.local) | Environment Variables |
| Configuration with a DSN | Not supported (added in CakePHP 3.0 as the url key) | 'dsn' key in datasource and email configurations; plugins register schemes with setDsnClassMap(); the skeleton reads DATABASE_URL (the test database in config/.env.test) and MAILER_DSN (v2.12.7) | Database DSNs |
For the complete list of breaking changes, see Migrating from CakePHP 2.10 and the CHANGELOG.
Pages Changed in This Book
Besides the changes listed below, all code samples follow the CakePHP 5 coding standard (short array syntax, braces on their own line), and paths use the modern directory layout. Links to the app skeleton, Bake and the maintained plugins point to their documentation sites (https://pieceofcake2.github.io/<repository>/).
New pages
- Migrating from CakePHP 2.10
- Migrating to the Modern Layout
- Security
- Reporting a Vulnerability
- Security Fixes (moved from the Appendices)
- Upstream Advisories
- Hardening Checklist
- Output Escaping and HTML Sanitization
- Migrating Tests to PHPUnit 9.6
- Integration Testing
- End-to-End Testing (pieceofcake2/panther)
- Maintained Plugins
- Static Analysis
- Continuous Integration (the CI job summaries subsection moved here from Static Analysis)
- Deploying to AWS Lambda
- Namespaced Classes
- Autoloading (how Composer loads the core, the classes of the modern and legacy layouts, plugins and vendor files)
Getting Started
- Getting Started
- Rewritten as the entry page for readers who maintain a CakePHP 2 application or know modern PHP: "About This Fork" (what the fork is, CakePHP 2 end of life, about this book; it replaces the separate "Piece of Cake 2" page, which was removed together with its sidebar group), "What's Different from CakePHP 2.10" with links to the detailed pages, "Where to Start" (existing application first, then
composer create-project pieceofcake2/appwith a note to consider CakePHP 5) and "Coming from Modern PHP" (no namespaces, array-based finders, models, components/behaviors/helpers, Configure, dispatcher filters, few native types) - Removed the introduction and the blog tutorial that was included in the page; the tutorial is under Tutorials & Examples
- Moved to the top of the "Getting Started" sidebar group; the other pages follow in the order Installation, Advanced Installation, Web Server Configuration, Folder Structure, Conventions, Structure, A Typical CakePHP Request
- "What's Different from CakePHP 2.10": the backports item links to Integration Testing instead of the upgrade guide on GitHub
- "What's Different from CakePHP 2.10": the backports item mentions the debug error pages in the CakePHP 5 style and the
utf8validation rule (v2.12.6) - "Coming from Modern PHP": the "Global class names" item (formerly "No namespaces") links to Namespaced Classes for using namespaced classes in the configuration
- Rewritten as the entry page for readers who maintain a CakePHP 2 application or know modern PHP: "About This Fork" (what the fork is, CakePHP 2 end of life, about this book; it replaces the separate "Piece of Cake 2" page, which was removed together with its sidebar group), "What's Different from CakePHP 2.10" with links to the detailed pages, "Where to Start" (existing application first, then
- Installation
- Requirements: PHP 8.0-8.5, Composer, MySQL 5.6+/PostgreSQL 9.4+/SQLite 3/SQL Server 2022+, mbstring/intl/openssl notes
- New application via
composer create-project pieceofcake2/app(modern layout) withdatabase.phpand salt/cipherSeed setup - Existing applications: replace cakephp/cakephp with pieceofcake2/cakephp and update the dispatcher files
- Removed archive/git downloads, include_path core sharing and the subdirectory "Development" setup
- Permissions now cover
tmp/andlogs/; added the built-in server (bin/cake server) and an Apache virtual host forwebroot/ - Built-in server: default port 8765 (change note: 80 before v2.12.3)
- Added "Configuring composer.json": minimal
composer.json; config.allow-plugins for composer/installers and extra.installer-paths toplugins/{$name}/are required for cakephp-plugin packages - New application: debug level, salts and database settings can also be set with environment variables (
config/.env, committed, andconfig/.env.localfor the values of your machine; app v2.5.0) - "Adding CakePHP to an Existing Application" comes before "Creating a New Application"; the closing link points to the blog tutorial instead of Getting Started
- Apache virtual host:
Options -Indexes -MultiViews +FollowSymLinks, a warning against a project-root document root and a link to the Apache 2.2 syntax - New application: commands to generate
Security.saltandSecurity.cipherSeed, noting that the seed does not make the 'cipher' cookie type secure - Database connection from
DATABASE_URL(the test database inconfig/.env.test) and the email transport fromMAILER_DSNin the configuration steps - The note on the
classmapsetting is shorter and links to Autoloading - "Adding CakePHP to an Existing Application": the steps as a numbered list
- Advanced Installation
- Removed PEAR installation, the old Composer/bake project setup and CAKE_CORE_INCLUDE_PATH core sharing
- Added Composer setup details: replace directive, plugin installer-paths, classmap autoloading, exclude-from-classmap
- Custom paths are now configured in
config/define.php(ROOT, APP_DIR, WEBROOT_DIR, WWW_ROOT, VENDORS) with a moved-webroot example - "Autoloading Your Classes" shortened, with a link to Autoloading
- "Plugin Location" split into shorter sentences
- Web Server Configuration
- Examples assume the document root is
webroot/;.htaccessupdated to the skeleton version; legacy root/app.htaccessexplained briefly - nginx example updated for PHP-FPM sockets; IIS
web.configplaced inwebroot/; removed dead links (Web Platform Installer, virtualhostx, Apache wiki) - Renamed from "URL Rewriting" to "Web Server Configuration" (the URL is unchanged), with a new "Document Root" section that warns against exposing the project directory
- Apache: HTTPS virtual host with an HTTP redirect,
Options -Indexes -MultiViews +FollowSymLinks, notes onAllowOverride(defaultNonesince 2.3.9),SymLinksIfOwnerMatchand mixed+/-options, hidden files denied except.well-known, step 5 to deny PHP in upload directories, and an HTTPS redirect for.htaccess .htaccessupdated to the current skeleton: Authorization header passed only when present (orCGIPassAuth On), no!-dcondition, so that directories are never listed- New "The Legacy Root .htaccess Files" section listing the files that become reachable when mod_rewrite is off
- Apache 2.2 syntax (
Order/Allow/Deny) in a separate legacy/EOL section, with a combined<IfModule mod_authz_core.c>example - nginx: HTTPS server with HTTP redirect, only
index.phppassed to PHP-FPM (with PATH_INFO), hidden files denied except.well-known - IIS and lighttpd sections kept for reference with a warning box (not tested by this project); lighttpd example rewritten without the
url=query parameter, passing onlyindex.phpto PHP - Removed the Hiawatha section
- Examples assume the document root is
- CakePHP Folder Structure
- Describes the modern layout (
bin,config,logs,plugins,resources/locales,src,templates,tests,tmp,vendor,webroot) with a legacyapp/mapping table - The modern layout and the legacy
app/layout in separate sections, each with a tree and a short description of each folder; a note on the.phptemplates and CakePHP 5 template directories of 2.13.0 - The steps for moving to the modern layout are left to Migrating to the Modern Layout, which the page links to
webroot/is the only document root, in development and production
- Describes the modern layout (
- CakePHP Conventions
- File locations use
src/andtemplates/; String::uuid replaced by CakeText::uuid()
- File locations use
- CakePHP Structure
- AppController/AppHelper/AppModel, routes, layouts and elements paths use the modern layout
- Examples use AuthComponent and FormHelper instead of the deprecated EmailComponent and JsHelper
CakePHP Overview
- What is CakePHP? Why use it?
- Feature list: PHP 8.0-8.5, Bake plugin, Composer; note that Bake is no longer in the core
- Where to Get Help
- Added Piece of Cake 2 GitHub issue trackers; removed IRC (freenode) and Google Groups; test cases path updated
Controllers
- Controllers
- Paths use the modern layout (
src/Controller,templates/,plugins/); legacyapp/layout mentioned once - New "Loading classes" section: Composer classmap autoloading replaces App::uses(); when App::uses() is still needed
- Paths use the modern layout (
- Request and Response objects
- Dispatcher path is
webroot/index.php; response mock example uses getMockBuilder() for PHPUnit 9 - Change note:
input()with a decoding callback returnsnullfor a request without a body (v2.13.0)
- Dispatcher path is
- The Pages Controller
- Paths updated to
src/Controllerandtemplates/Pages; skel source is the app skeleton or the Bake plugin instead oflib/Cake
- Paths updated to
- Scaffolding
- Paths updated to
src/Model,config/core.phpandtemplates/; Bake referred to as a plugin
- Paths updated to
- Components
- Component paths moved to
src/Controller/Component; App::uses() removed from examples; code style fixed
- Component paths moved to
Views
- Views
- Template, layout and element paths use
templates/; view classes insrc/View; legacyapp/Viewmapping table - Removed Flash/AMF and SOAP examples from the intro; linked the TwigView plugin
- Fixed syntax errors in the element caching example; removed App::uses() from the custom view class example
- Template, layout and element paths use
- Media Views
- Example paths use ROOT and WWW_ROOT; corrected that relative paths resolve against APP (not webroot)
- JSON and XML views
- View file path in example changed to
templates/Posts/json/index.ctp
- View file path in example changed to
- Themes
- Theme paths use
templates/Themedandwebroot/; plugin asset example usesplugins/
- Theme paths use
- Helpers
- Helper paths use
src/View/Helper; App::uses() removed from examples with a note on classmap autoloading; Bakery reference replaced by plugin list
- Helper paths use
Models
- Models
- Model files and AppModel live in
src/Model/; AppModel is not shipped by the core;App::uses()only needed without a Composer classmap
- Model files and AppModel live in
- Retrieving Your Data
- New "Sort Order" section:
orderformats, allowed sort directions, change note on the direction validation (v2.12.5), fixing code that triggers the deprecation, and a whitelist example for user-selected sorting
- New "Sort Order" section:
- Associations: Linking Models Together
- Model file paths use
src/Model/
- Model file paths use
- Saving Your Data
- Example file comments use
src/Controller/andtemplates/
- Example file comments use
- Data Validation
- Added the
utf8rule (v2.12.6, backport from CakePHP 5) - Localized validation classes in
src/Validation(autoloaded via classmap or App::uses()); Localized plugin link points to pieceofcake2/localized; removed Windows/mod_php note
- Added the
- Callback Methods
- Example path uses
src/Model/
- Example path uses
- Behaviors
- Behaviors go in
src/Model/Behavior; core behaviors invendor/pieceofcake2/cakephp/src/Cake/Model/Behavior - Community behaviors: link to maintained plugins instead of the CakePHP Bakery
- Behaviors go in
- DataSources
- Supported databases, versions and PDO extensions table; new "Connection Settings" section (
config/database.php, encoding in DSN, PostgreSQL sslmode, PHP 8.1 native int/float and ATTR_STRINGIFY_FETCHES) - SQL Server: ODBC driver on any OS instead of Windows-only Native Client; port, schema (default dbo), options, persistent settings
- Datasource example and plugin paths moved to
src/Model/Datasourceandplugins/ - Link to the pieceofcake2/datasources plugin instead of the old cakephp/datasources repository
- New "Connection DSN" subsection with the scheme table, and the SQL Server connection as a DSN (v2.12.7); plugin datasources can register a DSN scheme
- Supported databases, versions and PDO extensions table; new "Connection Settings" section (
- Model Attributes
- Database configuration file path is
config/database.php order: allowed sort directions, link to Sort Order
- Database configuration file path is
Core Libraries
- Caching
- Xcache and Wincache engines removed from the engine list (change note); Apc engine documented as APCu
- Configuration paths changed to
config/bootstrap.php,config/core.phpandsrc/Lib/Cache/Engine; PHP 5.3 remarks removed
- Events System
- Examples use
src/Lib/Event,config/bootstrap.phpandconfig/events.php; App::uses and PHP 5.3 remarks removed; Composer classmap autoloading noted
- Examples use
- Global Constants and Functions
- Path constants documented with modern-layout values (APP=
src/, CONFIG=config/, TESTS=tests/, TMP=tmp/, LOGS=logs/, WWW_ROOT=webroot/); legacyapp/values mentioned once - CAKE, CAKE_CORE_INCLUDE_PATH and CORE_PATH point into
vendor/pieceofcake2/cakephp/src; new CORE_ROOT constant documented
- Path constants documented with modern-layout values (APP=
- Internationalization & Localization
- Locale files in
resources/locales(legacyapp/Localealso searched); plugin translations inplugins/<Plugin>/Locale - i18n extract example for the modern layout:
bin/cake i18n extract --paths src,templates --output resources/locales
- Locale files in
- Logging
- Default log directory is
logs/(LOGS constant); custom log engines insrc/Libandplugins/; App::uses removed from examples
- Default log directory is
- Welcome
- Unsupported-version warning reworded for the fork (CakePHP 2 EOL upstream, use CakePHP 5 for new projects)
- Removed the PDF/EPUB download block; added the book source link and an Installation entry
- Translate
- i18n table initialization command is
bin/cake i18n
- i18n table initialization command is
- Tree
- Example path
src/Model/Category.php
- Example path
- Access Control Lists
- Paths changed to
config/(core.php,acl.ini.php,database.php,Schema/db_acl.sql); commands usebin/cake; core model path invendor/pieceofcake2/cakephp/src/Cake/Model
- Paths changed to
- Authentication
- Custom auth/authorize/hasher classes in
src/Controller/Component/Auth; layout intemplates/Layouts; App::uses removed
- Custom auth/authorize/hasher classes in
- Cookie
- Example uses type('aes') with
Security.useOpenSsl; warning that the default 'cipher' is insecure and 'rijndael' needs mcrypt - Type set with
'Cookie' => ['type' => 'aes']in$components(type() as an alternative); change note that the setting was ignored before v2.12.3;Security.useOpenSslalready enabled in the pieceofcake2/app v2.3.1 skeleton - Note that the default type is 'cipher' and is insecure with any cipherSeed; recommend 'aes' with its own key in
Cookie.key(from theCOOKIE_KEYenvironment variable) andSecurity.useOpenSsl; the example no longer writes a key in the code;Cookie.typeandCookie.keyinconfig/core.phpare the defaults since v2.12.6; link to migrating to 'aes'
- Example uses type('aes') with
- Flash
- Flash elements in
templates/Elements/Flash
- Flash elements in
- Pagination
- Which sort fields and directions PaginatorComponent accepts, with a link to Sort Order
- Security
- Change note: HMAC-signed CSRF tokens (CVE-2020-15400) and validation of _method-overridden requests (CVE-2015-8379)
- CacheHelper
Cache.checksetting inconfig/core.php
- FlashHelper
- Flash elements in
templates/Elements/Flash; core ships default/success/error elements that the app can override
- Flash elements in
- JsHelper
- Paths changed to
webroot/jsandtemplates/Layouts; PHP4/PHP5 method chaining remarks removed
- Paths changed to
- PaginatorHelper
- Example path
templates/Posts/index.ctp
- Example path
- RssHelper
- Paths changed to
config/routes.php,templates/Layouts/rssandtemplates/Posts/rss
- Paths changed to
- TextHelper
- String class reference replaced with CakeText
- TimeHelper
- Timezone setting in
config/core.php
- Timezone setting in
Core Utility Libraries
- App Class
- Loading classes rewritten around Composer classmap autoloading; App::uses() only for classes Composer does not know (app classes without classmap, non-Composer plugins)
- Overriding core classes: a copy in
src/Cake/loaded by the classmap, with the core file in exclude-from-classmap (v2.13.0) - Vendor files: Composer libraries need no loading; hand-copied files in
vendors/; plugin paths inplugins/; removed CakePHP 1.3 to 2.0 migration notes - "Loading classes" shortened, with links to Autoloading
- "Packages" split into shorter sentences
- CakeEmail
- Config in
config/email.php, templates intemplates/Emailsandtemplates/Layouts/Emails, custom transports insrc/Lib/Network/Email; removed EmailComponent comparisons and App::uses() - Gmail: app password instead of the defunct "less secure apps" setting; STARTTLS example uses port 587; change note for the typed MailTransport::_mail() signature
- New "Mailer DSN" section (v2.12.7): the
'dsn'key of a profile in the SymfonyMAILER_DSNformat (smtp,smtps,sendmail,native,null), query parameters, precedence, empty values, errors, schemes of plugins andCakeEmail::parseDsn();'dsn'added to the configuration keys
- Config in
- Folder & File
- Folder and File are autoloaded; removed App::uses()
- Hash
- Removed the PHP 5.4 requirement note for natural sorting
- HttpSocket
- CA certificates: system CA bundle with composer/ca-bundle fallback explained in the text; custom response/auth classes in
src/Lib/Network/Httpand extending HttpSocketResponse; removed App::uses() and Bakery URLs
- CA certificates: system CA bundle with composer/ca-bundle fallback explained in the text; custom response/auth classes in
- CakeNumber
- Removed unneeded App::uses() from the example
- Data Sanitization
- Sanitize is not present in CakePHP 3.0 and later (instead of "will be removed")
- Accepting user submitted HTML: points to the new Output Escaping and HTML Sanitization page instead of recommending HTML Purifier only
- Security
- Explain that mcrypt is not bundled since PHP 7.2 and
Security.useOpenSslshould be enabled inconfig/core.php(compatible format); rijndael() needs PECL mcrypt; Cookie 'cipher' type warning - Noted that the pieceofcake2/app skeleton (v2.3.1 and later) already enables
Security.useOpenSsl - Which methods use
Security.saltandSecurity.cipherSeed, with a link to generating them - Warning on
cipher(): only seeds from 1 to 4294967295 are meaningful, the well-known default ends up as seed 0, and in-range seeds can still be brute-forced - Change note:
cipher()is deprecated since v2.12.6 and logs a warning; useencrypt()/decrypt()
- Explain that mcrypt is not bundled since PHP 7.2 and
- Set
- Test file path updated to
tests/TestCase/Utility/SetTest.php
- Test file path updated to
- CakeText
- Removed String class deprecation note and App::uses() from the example; one change note about the removed String class
- CakeTime
- strftime() formats now explained in the text (IntlDateFormatter via php81_bc/strftime, intl needed for non-English names); fixed syntax error and removed App::uses() in the example
- Xml
- Removed CakePHP 1.3 "old method" comparisons and App::uses(); documented Xml::build() options (return, readFile, parseHuge) and a warning about passing user input; fixed broken examples
readFiledisables both file and URL loading; user input example uses'readFile' => false; change note that https URLs were fetched before v2.12.3- Change note: the
loadEntitiesoption is removed in v2.13.0
Console & Shells
- Shells, Tasks & Console Tools
- Console started with
bin/cake(orvendor/bin/cake); shells insrc/Console/Command/, legacyapp/Console/cakementioned once - Updated console welcome output and core shell list for v2.12.2 (bake/upgrade are plugins now)
- Removed instructions for adding
lib/Cake/Consoleto the system PATH (Windows steps, cake.bat) - Task loading example uses an application task instead of the removed core ProjectTask
- Console started with
- Code Generation with Bake
- Rewritten for the pieceofcake2/bake plugin: Composer install,
CakePlugin::load('Bake'),bin/cake bakecommands - Documented where Bake writes models, controllers, views, tests and fixtures in the modern and legacy layouts (
templates/,tests/TestCase/,tests/Fixture/with pieceofcake2/bake 1.0.3 or later) - Bake theme locations updated (
plugins/Bake/Console/Templates/default,src/Console/Templates/[theme]);lib/Cake/Console/Templatesremoved
- Rewritten for the pieceofcake2/bake plugin: Composer install,
- Schema management and migrations
- Commands use
bin/cake schema; schema files live inconfig/Schema
- Commands use
- ACL Shell
- Commands use
bin/cake
- Commands use
- Completion Shell
- Commands use
bin/cake; examples refer to the Bake plugin shell asBake.bake; removed corebake/upgradefrom the command list
- Commands use
- Running Shells as cronjobs
- Cron example uses
cd /path/to/my_app && bin/cake
- Cron example uses
- Shell Helpers
- Custom helper example fixed: class/file must use the
ShellHelpersuffix (src/Console/Helper/HeadingShellHelper.php), noApp::uses() output()examples pass arguments as an array (passing a string or closure directly causes a TypeError on PHP 8)
- Custom helper example fixed: class/file must use the
- I18N shell
- Extraction example scans
srcandtemplatesand writes toresources/locales; noted that model validation messages are then not extracted
- Extraction example scans
- Test shell
- Added
bin/cake test app AllTestsexample and PHPUnit 9.6 via Composer
- Added
- Upgrade shell
- Rewritten for the pieceofcake2/upgrade plugin (Composer install,
CakePlugin::load('Upgrade')); removed the manual download/copy walkthrough
- Rewritten for the pieceofcake2/upgrade plugin (Composer install,
Development
- Configuration
- Config files described in
config/(core, bootstrap, database, routes, email, acl, Schema); legacyapp/Config/and theCONFIGconstant explained in text - Database: built-in PDO drivers listed;
encodingpassed in the DSN; addedflags(PHP 8.1ATTR_STRINGIFY_FETCHES),schema(PostgreSQL/SQL Server),sslmode,options; removed PHP 5.3.7 notes - Change note: SQL Server driver targets SQL Server 2022+,
port/schema/optionshandling - Class loading rewritten around Composer classmap (
composer dump-autoload,App::uses()only for non-autoloaded plugins); change note on the framework's move to classmap - Core settings: Session sub-key
namecorrected tocookie, addedcacheLimiter, modern handler/schema paths andbin/cake;.htaccessremoval forApp.baseUrlper layout - Security:
Security.saltusage documented; change note on HMAC-signed CSRF tokens;cipherSeedonly for weak Cookie 'cipher'; newSecurity.useOpenSslentry (required on PHP 8 for encrypt()/Cookie 'aes'; already enabled in the pieceofcake2/app v2.3.1 skeleton) - Cache: available engines listed (File, Apc/APCu, Memcached, Memcache, Redis); change note on removed Xcache/Wincache
- Config readers: readers default to
CONFIG; custom reader example moved tosrc/Lib/Configure, declares its property (PHP 8.2), noApp::uses(); ja example renamed fromXmlReader(clashes with PHP's XMLReader) toMyXmlReader; ConfigReaderInterface/ConfigureException reference fixed - Inflector path
src/Cake/Utility/Inflector.phpand bootstrapconfig/bootstrap.phpfolded into text; era-specific examples (old IE/Chrome Frame, AMF/SOAP) modernized; ja:$mergedescription corrected,Configure::consume()added - New "Environment Variables" section: the pieceofcake2/app skeleton loads
config/.envand the project-root.envwith josegonzalez/dotenv at the top ofconfig/core.php(backport of the.envsupport of the CakePHP 3+/5 app skeleton; change note: added in app v2.4.0), symfony/dotenv since app v2.5.0, loaded withloadEnv()(config/.env,config/.env.local,config/.env.{APP_ENV},config/.env.{APP_ENV}.localmerged, later files and real environment variables win,APP_ENVdefaultdevandprodin production, only.localfiles ignored; change note on the loaders of v2.4.0 to v2.4.2), the syntax of symfony/dotenv, adding the one-line loader to legacy-layout and older applications, and the variables read by the skeleton (APP_ENV,APP_DEBUGwith debug level 0 when not set,SECURITY_SALT,SECURITY_CIPHER_SEED,COOKIE_KEY,DATABASE_URL,MAILER_DSN; theDB_*variables and theAPP_ENVbranch of earlier skeletons and how to replace them) App.baseUrl: keep the document root atwebroot/when the.htaccessfiles are removed- New "Generating the Security Salts" section: secure one-liners (PHP and shell), what depends on each value (the 'aes' cookie type mixes in
Security.salteven with its own key), and how to rotate them - New "cipherSeed and the 'cipher' Cookie Type" section: how
Security::cipher()uses the seed, only 1-4294967295 meaningful, values with 27 or more digits (the default of the originalconfig/core.php, the blog tutorial example and the old.env.examplegenerator) end up as seed 0, in-range seeds are still not secure, impact, which action to take, migrating to 'aes' with a 32-byte key inCookie.key(fromCOOKIE_KEY),Cookie.typeset to 'aes' andSecurity.useOpenSslset to true (Cookie.typeandCookie.keycan be set in configuration from v2.12.6; controller form for v2.12.5 and earlier; exception when the fallback keySecurity.saltis shorter than 32 bytes), and the warnings Security.cipherSeedentry: only 1-4294967295 is meaningful and no value makes 'cipher' secure, with a link to the new section- "Planned for v2.12.6" replaced by "Warnings Since v2.12.6": the deprecation warning for 'cipher' (once per process,
E_USER_DEPRECATEDin debug mode), the seed range warning and notice, the in-range default seed'2659758734'of the core's fallbackconfig/core.php, andCookie.type/Cookie.key; the former default seed is noted as the default up to v2.12.5 - New "Database DSNs" section (v2.12.7): the
'dsn'key of a connection, scheme to datasource mapping, DSN parts to keys, SQLite paths, precedence of the DSN over the array keys, empty values, encoding, query parameters, IPv6, errors, schemes of plugins,ConnectionManager::create()andConnectionManager::parseDsn();dsnadded to the list of connection keys
- Config files described in
- Routing
- Routes file path changed to
config/routes.php(legacyapp/Config/routes.phpnoted with link to the folder structure page) - Built-in routes located in
vendor/pieceofcake2/cakephp/config/routes.php; disabling them means removing the require line fromconfig/routes.php - Prefix routing:
Routing.prefixesinconfig/core.php, prefix view intemplates/Users/admin_edit.ctp - Custom route classes go in
src/Routing/Routeand are autoloaded via Composer classmap (composer dump-autoload) instead of App::uses() - Code samples: modern path comments, valid PHP class in passed-arguments example
- ja: added explicit anchors (routes-configuration, connecting-routes, route-elements, prefix-routing, route-conditions, passed-arguments, named-parameters) so links from other pages work
- Routes file path changed to
- Sessions
- Paths updated to modern layout (
tmp/sessions,src/Model/Datasource/Session/,config/Schema/sessions.php,bin/cake schema create sessions) with legacy paths in text - Handler example fixed: 6 callables,
checkAgentinstead ofuserAgent,session.-prefixed ini keys; noted PHP 8.4 deprecation of the callables form - Change note: handlers support
session.use_strict_mode(PHP 8.6 default) viaSessionHandlerAdapter; requirements for customread()/destroy() - Xcache removed from cache session text (APCu, Memcached, Redis); ComboSession example uses APCu, drops
App::uses(), modern path; code blocks marked as PHP
- Paths updated to modern layout (
- Dispatcher Filters
- Filters configured in
config/bootstrap.php; app filter classes insrc/Routing/Filter, plugin filters inplugins/MyPlugin/Routing/Filter - Removed App::uses() for framework classes and PHP 5.3 closure caveats; noted
composer dump-autoloadand class_exists() requirement for settings form - Fixed invalid closure placeholders in examples and broken markup
- (ja) Corrected mistranslation about filter priority and plugin notation
- Filters configured in
- Exceptions
- Restored the missing exception class names in the built-in exception lists (as tables)
- Paths use the modern layout (
templates/Errors,templates/Layouts,src/Lib/Error,config/core.php); documentedException.skipLog; the core templates intemplates/Error/of the framework, with theerroranddev_errorlayouts - Exception handlers receive any Throwable; examples typed with Throwable, PHP 5.3 caveat removed, no App::uses() for framework classes
- Change note: overriding CakeErrorController in the app is unreliable with Composer classmap autoloading; use _getController()
- Error Handling
- Paths and examples use the modern layout (
config/core.php,config/bootstrap.php,src/Lib/AppError.php) - Documented
Error.extraFatalErrorMemoryand where errors are logged (logs/error.log,logs/debug.log) - Change note: default handler checks error_reporting() & $code so @-suppressed errors are ignored on PHP 8
- Explained that PHP 7/8 Error objects (TypeError etc.) go to the exception handler, and that PHP 8 no longer passes $context
- Removed PHP 5.3 caveat; handler examples updated for PHP 8
- Paths and examples use the modern layout (
- Debugging
- debug() signature updated; trace/excerpt examples use fork paths (APP/CORE/ROOT); invoke() replaced with getInstance()
- Logs written to
logs/(debug.log/error.log); Object replaced with CakeObject; App::uses('CakeLog') removed - DebugKit: install pieceofcake2/debug_kit with Composer and load it in
config/bootstrap.php; links to the DebugKit documentation of the fork - DebugKit: describes the current toolbar (CakePHP icon in the bottom right-hand corner, panels, request history)
- New "Debug Error Pages" section (v2.12.6): the
dev_errorlayout ported from CakePHP 5,Debugger.editorandDebugger.editorBasePathfor the(edit)links, and overridingLayouts/dev_error.ctp; the layout switching of CakePHP 5 (AJAX requests in debug mode, theerrorlayout in production) since the release after 2.13.0
- Testing
- PHPUnit 9.6 installed with Composer (require-dev); PHPUnit 3.7/4.x/5.x, .phar and autoloader workaround instructions removed
- Test cases in
tests/TestCaseand fixtures intests/Fixture; configuration inconfig/; legacyapp/Testlayout mentioned as fallback - Running tests:
vendor/bin/phpunitwithphpunit.xml.dist(bootstraptests/bootstrap.php, CakeFixtureInjector listener, stderr) andbin/cake test;lib/Cake/Console/cakeand--appexamples removed - Test case listing (
bin/cake test appwithout a case, web runner list) searchestests/TestCase, falling back toTest/Case - Web runner:
webroot/test.phpfrom the skeleton, run a case via ?case=; command line recommended - Code samples updated for PHPUnit 9: setUp()/tearDown(): void, assertStringContainsString, assertIsArray, assertMatchesRegularExpression, willReturn(), PHPUnit\Framework\TestCase
- New section on createMock()/getMockBuilder(), deprecated CakeTestCase::getMock(), getMockForModel() signature and expectException()
- staticExpects() example replaced with writing Auth.User to the session
- Coverage requires Xdebug or PCOV; output to
tmp/coverage - Test suites use TESTS . 'TestCase'; note that
phpunit.xml.distmakes AllTests optional - Plugin tests in
plugins/<Name>/tests/TestCase(Test/Casefallback) - Jenkins: moved to the end of the new Continuous Integration page (after the GitHub Actions workflow), with
composer installstep,config/database.php,vendor/bin/phpunitand jenkins.io links; ja: explicit test-database-setup and generating-code-coverage anchors - New "Types of Tests" section: unit tests with fixtures, controller tests with testAction() and browser End-to-End tests (links to End-to-End Testing); ja: explicit testing-controllers anchor
- "Types of Tests" also lists integration tests with
IntegrationTestTrait(links to Integration Testing) and notes thatControllerTestCaseremains supported; tip linking to Integration Testing in "Testing Controllers" - Test database from
DATABASE_URLinconfig/.env.test(v2.12.7); new "The Test Database of the Skeleton" subsection:vendor/bin/phpunitandbin/cake testrun withAPP_ENV=testby default and load the committedconfig/.env.test, with per-machine values inconfig/.env.test.local, loaded after it; both connections readDATABASE_URL
- REST
- Paths updated to
config/routes.php,src/Controllerandtemplates/Recipes/xml - Corrected HTTP method override precedence (X-HTTP-Method-Override header before _method)
- ja: added explicit custom-rest-routing anchor
- Paths updated to
Deployment
- Deployment
- Document root,
core.phpand plugin symlink paths use the modern layout - Added
composer install --no-dev --optimize-autoloaderand conditional loading of development-only plugins - Debug level read from the
APP_DEBUGenvironment variable of the skeleton instead of a customCAKEPHP_DEBUGvariable; other settings link to the environment variables section - Added a "Deploying to AWS Lambda" section linking to the new page
- "Check your security" rewritten as a short checklist linking to the Security section (debug, salts and cookie cipher, document root, HTTPS, SecurityComponent, validation, escaping and sanitizing HTML, dependencies, permissions, secrets); removed the Data Sanitization link
- Warnings about a project-root document root and
APP_DEBUG=2on a production server; settingAPP_ENV=prodwith Apache, nginx and PHP-FPM (app v2.5.0); secrets from environment variables or a secret store, not in the repository or logs - New sections on deployed files, file permissions (no 777), uploaded files, HTTPS (secure session cookie behind a proxy, supported PHP versions) and clearing the cache (and OPcache)
DATABASE_URLandMAILER_DSNare secrets, as they contain the passwords
- Document root,
- Deploying to AWS Lambda
- New page: deploying the pieceofcake2/app skeleton to AWS Lambda with Bref 3 and Docker container images (TMP/LOGS in /tmp, SCRIPT_NAME and HTTPS for Bref's FPM runtime, logs to stderr), configuration with environment variables and SSM Parameter Store (
bref-ssm:), DynamoDB sessions and SES email with pieceofcake2/aws, cache, S3 uploads with presigned URLs, static assets with Lift (S3 + CloudFront), RDS, console commands and schedules, local testing with the Runtime Interface Emulator, and deployment from GitHub Actions with OIDC - Tip: pieceofcake2/async-aws offers the same session handler, SES transport, cache engine and S3 stream wrapper with smaller dependencies (AsyncAws); the cache section points to its
AsyncAws.DynamoDbengine, and the S3 section mentions its stream wrapper - SES permission limited to the sender identity, uploads bucket with S3 Block Public Access, authorization check noted in the download example, public database discouraged for production, no secrets in logs, private assets bucket with CloudFront OAC, exact OIDC
subcondition (no wildcards) and noAdministratorAccessfor the deploy role DATABASE_URLfrom an SSMSecureStringparameter instead of theDB_*variables; SES SMTP interface withMAILER_DSNfrom SSM as an alternative to the SES API transportAPP_ENV: prod, and the committedconfig/.envkept in the image (app v2.5.0)
- New page: deploying the pieceofcake2/app skeleton to AWS Lambda with Bref 3 and Docker container images (TMP/LOGS in /tmp, SCRIPT_NAME and HTTPS for Bref's FPM runtime, logs to stderr), configuration with environment variables and SSM Parameter Store (
Security
- Security
- New section and overview page: supported versions from the organization's
SECURITY.md(security fixes for the latest release; so far released as patch releases), how fixes are announced (GitHub Security Advisories, CHANGELOG/UPGRADE.md, this book)
- New section and overview page: supported versions from the organization's
- Reporting a Vulnerability
- New page: private vulnerability reporting (Security tab, Report a vulnerability), what to include and the disclosure process from
SECURITY.md; moved from the "Reporting a Vulnerability" section of Security Fixes
- New page: private vulnerability reporting (Security tab, Report a vulnerability), what to include and the disclosure process from
- Security Fixes
- Moved from
/appendices/security-fixes(the old URL redirects to this page); the reporting section moved to Reporting a Vulnerability - Added the
Xml::build()SSRF with'readFile' => false(fixed in 2.12.3); Cookie type set in$components; skeleton note forSecurity.useOpenSsl - Added the email header injection in SmtpTransport/MailTransport (GHSA-4f9q-3c4x-52cv), the path traversal in view, layout and element names (GHSA-w2mh-x92p-5p95) and the open redirect after login in AuthComponent (GHSA-x4p9-p4cx-gxwx), all fixed in 2.12.5; the table lists GHSA IDs; note that applications on the original CakePHP 2.x can switch to pieceofcake2/cakephp to get the fixes
- Added the weak 'cipher' encryption and
Security.cipherSeed(GHSA-65v5-h65v-8pgg): what 2.12.6 changed (deprecation warning, seed range warning, in-range default seed,Cookie.type/Cookie.key), that 'cipher' remains insecure, and switching to 'aes' withSecurity.useOpenSsl; link to the cipherSeed section of Configuration - XML external entities: the
loadEntitiesoption is removed in v2.13.0 and has no effect
- Moved from
- Upstream Advisories
- New page: status of the upstream CakePHP advisories that concern CakePHP 2.x (fixed in the fork, or not applicable), from the fork's CHANGELOG,
UPGRADE.mdand advisories - Note that the 'cipher' weakness (GHSA-65v5-h65v-8pgg) has no upstream advisory and affects the original CakePHP 2.x, where it will not be fixed
- New page: status of the upstream CakePHP advisories that concern CakePHP 2.x (fixed in the fork, or not applicable), from the fork's CHANGELOG,
- Hardening Checklist
- New page: debug 0, unique salt and cipher seed, Composer updates, SecurityComponent/CSRF, cookie and session flags, file permissions, HTTPS, supported PHP versions; links to the pages that describe each setting
- Output Escaping and HTML Sanitization
- New page: escaping at output time by context with
h()and the helpers, URLs and JavaScript (json_encode()withJSON_HEX_*), sanitizing user HTML with Symfony HtmlSanitizer or HTML Purifier, Markdown, the deprecated Sanitize class, and a strict nonce-based Content Security Policy
- New page: escaping at output time by context with
Tutorials & Examples
- Tutorials & Examples
- Replaced links to CakePackages and the Bakery with a link to the maintained plugins page
- Simple Authentication and Authorization Application
- Paths updated to
src/andtemplates/; removed unneededApp::uses()calls; UsersController described as generated by the Bake plugin posts.user_idadded asINT UNSIGNED(integer display width is deprecated in MySQL 8)
- Paths updated to
- Blog Tutorial
- Setup rewritten:
composer create-project pieceofcake2/app blog, PHP 8.0+, built-in server viabin/cake server(default port 8765); removed archive download/git clone steps - Paths updated to
config/database.php,config/core.php,tmp/andlogs/; MySQL example usesutf8mb4 - mod_rewrite section replaced by a short "Using Apache" section (DocumentRoot =
webroot/) - Salt and cipher seed generated with commands instead of example values; cipher seed from 1 to 4294967295, noting that it is used only by the insecure 'cipher' cookie type, which the tutorial does not use
- Setup rewritten:
- Blog Tutorial - Adding a layer
- Files placed in
src/Model,src/Controller,templates/Posts,config/routes.php view()anddelete()take$id = nullso a missing ID raises NotFoundException instead of an ArgumentCountError on PHP 8
- Files placed in
- Simple Acl controlled Application - part 2
- AclExtras installed with Composer (
pieceofcake2/acl_extras) intoplugins/AclExtras, run withbin/cake AclExtras.AclExtras - Session flash calls replaced with FlashComponent/FlashHelper; complete
login()action shown
- AclExtras installed with Composer (
- Simple Acl controlled Application
- Setup via
composer create-project pieceofcake2/app acl, Bake plugin loaded inconfig/bootstrap.php,bin/cakecommands, modern paths - SQL works on MySQL 8:
groupsquoted (reserved word), no integer display widths - Passwords hashed with BlowfishPasswordHasher (VARCHAR(255) column) instead of deprecated
AuthComponent::password(); beforeSave no longer touches a missing password - AppController loads FlashComponent/FlashHelper (used by baked controllers); login uses Flash and
Form->create()withurl; removed CakePHP 2.0allow('*') - Bake writes the views to
templates/<Controller>/(pieceofcake2/bake 1.0.3 or later); removed the instruction to move them
- Setup via
Plugins
- Plugins
- Intro explains PHP 8 compatibility of CakePHP 2 plugins and links to the maintained Piece of Cake 2 forks
- How To Create Plugins
- Plugin paths use
plugins/andtemplates/Pluginoverrides; internal plugin structure and test directories explained; App::uses() kept in plugin code with the reason - Bake commands use
bin/cakewith the Bake plugin; added the missing asset plugin-syntax example; removedflash/asset folder - Publishing: removed plugins.cakephp.org/awesome-cakephp; added a
composer.jsonexample (type cakephp-plugin, composer/installers, installer-name) - New "Registering DSN Schemes" section (v2.12.7):
setDsnClassMap()/getDsnClassMap()ofConnectionManagerandCakeEmailin the plugin bootstrap, class names and callables,nullremoval, themethod_exists()guard and when the maps are read - The legacy plugin layout and the modern plugin layout (v2.13.0) in separate sections, each with a tree; the modern layout keeps only namespaced classes in
src/; the publishing section lists thecomposer.jsonsettings and links to Autoloading - The warning on plugins and namespaces rewritten in short sentences, with the namespaced classes of the modern layout as an alternative; the modern template paths in "Plugin Views" and "Plugin Tips"
- Plugin paths use
- How To Install Plugins
- Composer is the primary method (pieceofcake2/debug_kit example, composer/installers and installer-paths for
plugins/); manual and Git installs useplugins/and https URLs - Plugins are loaded in
config/bootstrap.php; when App::uses() is still needed for plugin classes composer.jsoninstaller-paths and allow-plugins (composer/installers, Composer 2.2+) documented as required so plugins land inplugins/<Name>/- Plugins that Composer does not load link to Autoloading
- Composer is the primary method (pieceofcake2/debug_kit example, composer/installers and installer-paths for
- How To Use Plugins
- Plugin loading shown in
config/bootstrap.phpwith pluginConfig/file locations; schema command usesbin/cake - Plugin bootstraps that register DSN schemes
- Plugin loading shown in
- Maintained Plugins
- The AsyncAws plugin is described as a lighter alternative to the Aws plugin
- "Installing a plugin" links to Autoloading
Contributing
- Contributing
- Contributions go to the pieceofcake2/* repositories on GitHub (framework, app skeleton, plugins, docs)
- The contribution process is described in the organization's
CONTRIBUTING.md; the pages of this chapter give an overview and link to its sections
- Documentation
- Docs hosted at pieceofcake2/docs (2.x), Markdown + VitePress, deployed by GitHub Actions, local preview with
bin/dev-server.sh; only en/ja maintained; Jenkins, IRC and docs mailing list removed - Rewritten as the guide to editing this book: local development, repository layout, editing guidelines, translations, and a Markdown/VitePress formatting guide (headings and anchors, links, code blocks, alerts, info/pieceofcake2 containers, includes) that replaces the reStructuredText/Sphinx one
- Docs hosted at pieceofcake2/docs (2.x), Markdown + VitePress, deployed by GitHub Actions, local preview with
- Tickets
- Issues go to pieceofcake2/* repositories; check CHANGELOG/upgrade guide before reporting; Stack Overflow for questions (IRC and Google Group removed)
- Security issues reported via GitHub private vulnerability reporting (Security tab, Report a vulnerability) per
SECURITY.md; security@cakephp.org removed - Reporting details link to
CONTRIBUTING.mdandSECURITY.md
- Code
- Setup: PHP 8.0+, Composer; PHPUnit 9.6, PHP_CodeSniffer and PHPStan installed as dev dependencies; removed PHP 5.3, mcrypt and PHPUnit 3.7 requirements
- New "Running the Tests" section: copy
tests/config/database.phpintovendor/pieceofcake2/app/config, select the database withDB, runvendor/bin/phpunitandvendor/bin/phpcs - Single maintained branch 2.x; branch from and target upstream/2.x; removed 2.next/4.0 targets and Cake Software Foundation ownership note
- Setup, running the tests and the pull request steps link to
CONTRIBUTING.md
- Coding Standards
- Rewritten as the CakePHP 5 based standard (cakephp/cakephp-codesniffer ^5.0, PSR-12): 4 spaces, short arrays, trailing commas, braces on own line for classes/methods, elseif, no Yoda, ?? and ?:, visibility on constants, DocBlock rules
- Added how to install and run phpcs/phpcbf, the CakePHP 2 exclusions of the framework
phpcs.xml, the applicationphpcs.xmlfrom pieceofcake2/app (with legacy layout paths), and a table of differences from the original CakePHP 2 standard
- Backwards Compatibility Guide
- Rewritten: what to expect from fork releases (some included breaking changes, e.g. cache engines, directory layout, autoloading), migration guides; the guidelines for contributors link to
CONTRIBUTING.md; upstream semver tables removed
- Rewritten: what to expect from fork releases (some included breaking changes, e.g. cache engines, directory layout, autoloading), migration guides; the guidelines for contributors link to
- CakePHP Development Process
- Rewritten for the fork's maintenance-only process: version numbers (2.10.24.x, 2.11.0, 2.12.x); goals, branches and releases link to
CONTRIBUTING.md; IRC and upstream branch model removed
- Rewritten for the fork's maintenance-only process: version numbers (2.10.24.x, 2.11.0, 2.12.x); goals, branches and releases link to
Appendices
- Changes from the Original Book
- This page; moved from
/pieceofcake2/changesin the removed "Piece of Cake 2" sidebar group to the Appendices
- This page; moved from
- Migrating from CakePHP 2.10
- Added a v2.12.3 section (Xml::build() SSRF fix, Cookie
'type'setting, ServerShell port, test case listing, SQL Server ERRMODE); Cookie example uses$components - Added a v2.12.5 section (security fixes for email headers, view/layout/element names and the login redirect; deprecation of invalid ORDER BY directions)
- Added a v2.12.6 section ('cipher' deprecation and seed warnings,
Cookie.type/Cookie.key, debug error pages in the CakePHP 5 style, exceptions instead ofE_USER_ERROR, ConsoleLog colors,Validation::utf8(), Folder stream wrapper schemes, the console without an applicationcore.php, PHPStan level 5 docblocks); the 'cipher' breaking-change section links to it
- Added a v2.12.3 section (Xml::build() SSRF fix, Cookie
- Migrating from SimpleTest to PHPUnit 3.7
- Retitled "Migrating from SimpleTest to PHPUnit 3.7" and linked to the new PHPUnit 9.6 guide
