Skip to content
This is the documentation for pieceofcake2/cakephp, a community-maintained fork of CakePHP 2.x for PHP 8. About this fork.

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 ​

AreaOriginal CakePHP 2.10.24Piece of Cake 2 forkSee
PHPPHP 5.3 to 7.4PHP 8.0 to 8.5Installation
InstallationArchive download, PEAR or ComposerComposer only (pieceofcake2/cakephp)Installation
Plugins via ComposerOptionalcomposer/installers settings are requiredConfiguring composer.json
Application layoutapp/Modern layout (src/, templates/, config/, ...) or app/Folder Structure
Framework layoutlib/Cake/vendor/pieceofcake2/cakephp/src/Cake/Migrating from CakePHP 2.10
Class loadingApp::uses()Composer autoloading; App::uses() deprecated (2.13)Autoloading
BakeCore shellpieceofcake2/bake pluginCode Generation with Bake
UpgradeShellCore shellpieceofcake2/upgrade pluginUpgrade Shell
Cache enginesIncludes Xcache and WincacheXcache and Wincache removedCaching
TestsPHPUnit 3.7PHPUnit 9.6Testing
Controller testsControllerTestCase::testAction()Also IntegrationTestTrait and EmailTrait (v2.12.4, backports from CakePHP 5)Integration Testing
Coding standardCakePHP 2 standard (tabs, array())CakePHP 5 codesniffer (4 spaces, [])Coding Standards
CSRF protectionUnsigned tokens; some methods not validatedHMAC-signed tokens; all methods except GET/HEAD/OPTIONS validatedSecurity Fixes
SSL certificatesBundled cacert.pem (2016)System CA bundle or composer/ca-bundleSecurity Fixes
String classAlias of CakeTextRemoved; use CakeTextCakeText
Xml::build() with 'readFile' => falsehttps:// URLs still fetched (SSRF)Neither files nor URLs are readSecurity Fixes
CookieComponent 'type' in $componentsIgnored (always 'cipher')HonoredCookie
cake server default port808765Installation
Line breaks in email header valuesSent 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 missingSecurity Fixes
Protocol-relative Auth.redirect URLRedirects to another host after login (open redirect)Collapsed to a local pathSecurity Fixes
Sort direction in orderAppended to the SQL as givenASC / DESC with optional NULLS FIRST / NULLS LAST; anything else triggers E_USER_DEPRECATED (v2.12.5), an exception in a future versionSort Order
'cipher' encryption (default CookieComponent type)Default type, insecure, no warningDeprecated 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 modeCakePHP 2 layoutCakePHP 5 style dev_error layout with code excerpts and editor links (v2.12.6)Debugging
.env filesNot supportedLoaded 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 DSNNot 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 ​

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/app with 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 utf8 validation 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
  • 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) with database.php and 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/ and logs/; added the built-in server (bin/cake server) and an Apache virtual host for webroot/
    • 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 to plugins/{$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, and config/.env.local for 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.salt and Security.cipherSeed, noting that the seed does not make the 'cipher' cookie type secure
    • Database connection from DATABASE_URL (the test database in config/.env.test) and the email transport from MAILER_DSN in the configuration steps
    • The note on the classmap setting 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/; .htaccess updated to the skeleton version; legacy root/app .htaccess explained briefly
    • nginx example updated for PHP-FPM sockets; IIS web.config placed in webroot/; 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 on AllowOverride (default None since 2.3.9), SymLinksIfOwnerMatch and mixed +/- options, hidden files denied except .well-known, step 5 to deny PHP in upload directories, and an HTTPS redirect for .htaccess
    • .htaccess updated to the current skeleton: Authorization header passed only when present (or CGIPassAuth On), no !-d condition, 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.php passed 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 only index.php to PHP
    • Removed the Hiawatha section
  • CakePHP Folder Structure
    • Describes the modern layout (bin, config, logs, plugins, resources/locales, src, templates, tests, tmp, vendor, webroot) with a legacy app/ 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 .php templates 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
  • CakePHP Conventions
    • File locations use src/ and templates/; String::uuid replaced by CakeText::uuid()
  • 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/); legacy app/ layout mentioned once
    • New "Loading classes" section: Composer classmap autoloading replaces App::uses(); when App::uses() is still needed
  • 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 returns null for a request without a body (v2.13.0)
  • The Pages Controller
    • Paths updated to src/Controller and templates/Pages; skel source is the app skeleton or the Bake plugin instead of lib/Cake
  • Scaffolding
    • Paths updated to src/Model, config/core.php and templates/; Bake referred to as a plugin
  • Components
    • Component paths moved to src/Controller/Component; App::uses() removed from examples; code style fixed

Views ​

  • Views
    • Template, layout and element paths use templates/; view classes in src/View; legacy app/View mapping 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
  • 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
  • Themes
    • Theme paths use templates/Themed and webroot/; plugin asset example uses plugins/
  • Helpers
    • Helper paths use src/View/Helper; App::uses() removed from examples with a note on classmap autoloading; Bakery reference replaced by plugin list

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
  • Retrieving Your Data
    • New "Sort Order" section: order formats, 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
  • Associations: Linking Models Together
    • Model file paths use src/Model/
  • Saving Your Data
    • Example file comments use src/Controller/ and templates/
  • Data Validation
    • Added the utf8 rule (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
  • Callback Methods
    • Example path uses src/Model/
  • Behaviors
    • Behaviors go in src/Model/Behavior; core behaviors in vendor/pieceofcake2/cakephp/src/Cake/Model/Behavior
    • Community behaviors: link to maintained plugins instead of the CakePHP Bakery
  • 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/Datasource and plugins/
    • 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
  • Model Attributes
    • Database configuration file path is config/database.php
    • order: allowed sort directions, link to Sort Order

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.php and src/Lib/Cache/Engine; PHP 5.3 remarks removed
  • Events System
    • Examples use src/Lib/Event, config/bootstrap.php and config/events.php; App::uses and PHP 5.3 remarks removed; Composer classmap autoloading noted
  • Global Constants and Functions
    • Path constants documented with modern-layout values (APP=src/, CONFIG=config/, TESTS=tests/, TMP=tmp/, LOGS=logs/, WWW_ROOT=webroot/); legacy app/ values mentioned once
    • CAKE, CAKE_CORE_INCLUDE_PATH and CORE_PATH point into vendor/pieceofcake2/cakephp/src; new CORE_ROOT constant documented
  • Internationalization & Localization
    • Locale files in resources/locales (legacy app/Locale also searched); plugin translations in plugins/<Plugin>/Locale
    • i18n extract example for the modern layout: bin/cake i18n extract --paths src,templates --output resources/locales
  • Logging
    • Default log directory is logs/ (LOGS constant); custom log engines in src/Lib and plugins/; App::uses removed from examples
  • 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
  • Tree
    • Example path src/Model/Category.php
  • Access Control Lists
    • Paths changed to config/ (core.php, acl.ini.php, database.php, Schema/db_acl.sql); commands use bin/cake; core model path in vendor/pieceofcake2/cakephp/src/Cake/Model
  • Authentication
    • Custom auth/authorize/hasher classes in src/Controller/Component/Auth; layout in templates/Layouts; App::uses removed
  • 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.useOpenSsl already 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 the COOKIE_KEY environment variable) and Security.useOpenSsl; the example no longer writes a key in the code; Cookie.type and Cookie.key in config/core.php are the defaults since v2.12.6; link to migrating to 'aes'
  • Flash
    • Flash elements in templates/Elements/Flash
  • 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.check setting in config/core.php
  • FlashHelper
    • Flash elements in templates/Elements/Flash; core ships default/success/error elements that the app can override
  • JsHelper
    • Paths changed to webroot/js and templates/Layouts; PHP4/PHP5 method chaining remarks removed
  • PaginatorHelper
    • Example path templates/Posts/index.ctp
  • RssHelper
    • Paths changed to config/routes.php, templates/Layouts/rss and templates/Posts/rss
  • TextHelper
    • String class reference replaced with CakeText
  • TimeHelper
    • Timezone setting in config/core.php

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 in plugins/; 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 in templates/Emails and templates/Layouts/Emails, custom transports in src/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 Symfony MAILER_DSN format (smtp, smtps, sendmail, native, null), query parameters, precedence, empty values, errors, schemes of plugins and CakeEmail::parseDsn(); 'dsn' added to the configuration keys
  • 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/Http and extending HttpSocketResponse; removed App::uses() and Bakery URLs
  • 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.useOpenSsl should be enabled in config/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.salt and Security.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; use encrypt() / decrypt()
  • Set
    • Test file path updated to tests/TestCase/Utility/SetTest.php
  • 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
    • readFile disables 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 loadEntities option is removed in v2.13.0

Console & Shells ​

  • Shells, Tasks & Console Tools
    • Console started with bin/cake (or vendor/bin/cake); shells in src/Console/Command/, legacy app/Console/cake mentioned once
    • Updated console welcome output and core shell list for v2.12.2 (bake/upgrade are plugins now)
    • Removed instructions for adding lib/Cake/Console to the system PATH (Windows steps, cake.bat)
    • Task loading example uses an application task instead of the removed core ProjectTask
  • Code Generation with Bake
    • Rewritten for the pieceofcake2/bake plugin: Composer install, CakePlugin::load('Bake'), bin/cake bake commands
    • 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/Templates removed
  • Schema management and migrations
    • Commands use bin/cake schema; schema files live in config/Schema
  • ACL Shell
    • Commands use bin/cake
  • Completion Shell
    • Commands use bin/cake; examples refer to the Bake plugin shell as Bake.bake; removed core bake/upgrade from the command list
  • Running Shells as cronjobs
    • Cron example uses cd /path/to/my_app && bin/cake
  • Shell Helpers
    • Custom helper example fixed: class/file must use the ShellHelper suffix (src/Console/Helper/HeadingShellHelper.php), no App::uses()
    • output() examples pass arguments as an array (passing a string or closure directly causes a TypeError on PHP 8)
  • I18N shell
    • Extraction example scans src and templates and writes to resources/locales; noted that model validation messages are then not extracted
  • Test shell
    • Added bin/cake test app AllTests example and PHPUnit 9.6 via Composer
  • Upgrade shell
    • Rewritten for the pieceofcake2/upgrade plugin (Composer install, CakePlugin::load('Upgrade')); removed the manual download/copy walkthrough

Development ​

  • Configuration
    • Config files described in config/ (core, bootstrap, database, routes, email, acl, Schema); legacy app/Config/ and the CONFIG constant explained in text
    • Database: built-in PDO drivers listed; encoding passed in the DSN; added flags (PHP 8.1 ATTR_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/options handling
    • 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 name corrected to cookie, added cacheLimiter, modern handler/schema paths and bin/cake; .htaccess removal for App.baseUrl per layout
    • Security: Security.salt usage documented; change note on HMAC-signed CSRF tokens; cipherSeed only for weak Cookie 'cipher'; new Security.useOpenSsl entry (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 to src/Lib/Configure, declares its property (PHP 8.2), no App::uses(); ja example renamed from XmlReader (clashes with PHP's XMLReader) to MyXmlReader; ConfigReaderInterface/ConfigureException reference fixed
    • Inflector path src/Cake/Utility/Inflector.php and bootstrap config/bootstrap.php folded into text; era-specific examples (old IE/Chrome Frame, AMF/SOAP) modernized; ja: $merge description corrected, Configure::consume() added
    • New "Environment Variables" section: the pieceofcake2/app skeleton loads config/.env and the project-root .env with josegonzalez/dotenv at the top of config/core.php (backport of the .env support of the CakePHP 3+/5 app skeleton; change note: added in app v2.4.0), symfony/dotenv since app v2.5.0, loaded with loadEnv() (config/.env, config/.env.local, config/.env.{APP_ENV}, config/.env.{APP_ENV}.local merged, later files and real environment variables win, APP_ENV default dev and prod in production, only .local files 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_DEBUG with debug level 0 when not set, SECURITY_SALT, SECURITY_CIPHER_SEED, COOKIE_KEY, DATABASE_URL, MAILER_DSN; the DB_* variables and the APP_ENV branch of earlier skeletons and how to replace them)
    • App.baseUrl: keep the document root at webroot/ when the .htaccess files 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.salt even 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 original config/core.php, the blog tutorial example and the old .env.example generator) 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 in Cookie.key (from COOKIE_KEY), Cookie.type set to 'aes' and Security.useOpenSsl set to true (Cookie.type and Cookie.key can be set in configuration from v2.12.6; controller form for v2.12.5 and earlier; exception when the fallback key Security.salt is shorter than 32 bytes), and the warnings
    • Security.cipherSeed entry: 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_DEPRECATED in debug mode), the seed range warning and notice, the in-range default seed '2659758734' of the core's fallback config/core.php, and Cookie.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() and ConnectionManager::parseDsn(); dsn added to the list of connection keys
  • Routing
    • Routes file path changed to config/routes.php (legacy app/Config/routes.php noted 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 from config/routes.php
    • Prefix routing: Routing.prefixes in config/core.php, prefix view in templates/Users/admin_edit.ctp
    • Custom route classes go in src/Routing/Route and 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
  • 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, checkAgent instead of userAgent, 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) via SessionHandlerAdapter; requirements for custom read()/destroy()
    • Xcache removed from cache session text (APCu, Memcached, Redis); ComboSession example uses APCu, drops App::uses(), modern path; code blocks marked as PHP
  • Dispatcher Filters
    • Filters configured in config/bootstrap.php; app filter classes in src/Routing/Filter, plugin filters in plugins/MyPlugin/Routing/Filter
    • Removed App::uses() for framework classes and PHP 5.3 closure caveats; noted composer dump-autoload and class_exists() requirement for settings form
    • Fixed invalid closure placeholders in examples and broken markup
    • (ja) Corrected mistranslation about filter priority and plugin notation
  • 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); documented Exception.skipLog; the core templates in templates/Error/ of the framework, with the error and dev_error layouts
    • 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.extraFatalErrorMemory and 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
  • 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_error layout ported from CakePHP 5, Debugger.editor and Debugger.editorBasePath for the (edit) links, and overriding Layouts/dev_error.ctp; the layout switching of CakePHP 5 (AJAX requests in debug mode, the error layout 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/TestCase and fixtures in tests/Fixture; configuration in config/; legacy app/Test layout mentioned as fallback
    • Running tests: vendor/bin/phpunit with phpunit.xml.dist (bootstrap tests/bootstrap.php, CakeFixtureInjector listener, stderr) and bin/cake test; lib/Cake/Console/cake and --app examples removed
    • Test case listing (bin/cake test app without a case, web runner list) searches tests/TestCase, falling back to Test/Case
    • Web runner: webroot/test.php from 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.dist makes AllTests optional
    • Plugin tests in plugins/<Name>/tests/TestCase (Test/Case fallback)
    • Jenkins: moved to the end of the new Continuous Integration page (after the GitHub Actions workflow), with composer install step, config/database.php, vendor/bin/phpunit and 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 that ControllerTestCase remains supported; tip linking to Integration Testing in "Testing Controllers"
    • Test database from DATABASE_URL in config/.env.test (v2.12.7); new "The Test Database of the Skeleton" subsection: vendor/bin/phpunit and bin/cake test run with APP_ENV=test by default and load the committed config/.env.test, with per-machine values in config/.env.test.local, loaded after it; both connections read DATABASE_URL
  • REST
    • Paths updated to config/routes.php, src/Controller and templates/Recipes/xml
    • Corrected HTTP method override precedence (X-HTTP-Method-Override header before _method)
    • ja: added explicit custom-rest-routing anchor

Deployment ​

  • Deployment
    • Document root, core.php and plugin symlink paths use the modern layout
    • Added composer install --no-dev --optimize-autoloader and conditional loading of development-only plugins
    • Debug level read from the APP_DEBUG environment variable of the skeleton instead of a custom CAKEPHP_DEBUG variable; 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=2 on a production server; setting APP_ENV=prod with 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_URL and MAILER_DSN are secrets, as they contain the passwords
  • 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.DynamoDb engine, 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 sub condition (no wildcards) and no AdministratorAccess for the deploy role
    • DATABASE_URL from an SSM SecureString parameter instead of the DB_* variables; SES SMTP interface with MAILER_DSN from SSM as an alternative to the SES API transport
    • APP_ENV: prod, and the committed config/.env kept in the image (app v2.5.0)

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)
  • 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
  • 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 for Security.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' with Security.useOpenSsl; link to the cipherSeed section of Configuration
    • XML external entities: the loadEntities option is removed in v2.13.0 and has no effect
  • 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.md and 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
  • 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() with JSON_HEX_*), sanitizing user HTML with Symfony HtmlSanitizer or HTML Purifier, Markdown, the deprecated Sanitize class, and a strict nonce-based Content Security Policy

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/ and templates/; removed unneeded App::uses() calls; UsersController described as generated by the Bake plugin
    • posts.user_id added as INT UNSIGNED (integer display width is deprecated in MySQL 8)
  • Blog Tutorial
    • Setup rewritten: composer create-project pieceofcake2/app blog, PHP 8.0+, built-in server via bin/cake server (default port 8765); removed archive download/git clone steps
    • Paths updated to config/database.php, config/core.php, tmp/ and logs/; MySQL example uses utf8mb4
    • 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
  • Blog Tutorial - Adding a layer
    • Files placed in src/Model, src/Controller, templates/Posts, config/routes.php
    • view() and delete() take $id = null so a missing ID raises NotFoundException instead of an ArgumentCountError on PHP 8
  • Simple Acl controlled Application - part 2
    • AclExtras installed with Composer (pieceofcake2/acl_extras) into plugins/AclExtras, run with bin/cake AclExtras.AclExtras
    • Session flash calls replaced with FlashComponent/FlashHelper; complete login() action shown
  • Simple Acl controlled Application
    • Setup via composer create-project pieceofcake2/app acl, Bake plugin loaded in config/bootstrap.php, bin/cake commands, modern paths
    • SQL works on MySQL 8: groups quoted (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() with url; removed CakePHP 2.0 allow('*')
    • Bake writes the views to templates/<Controller>/ (pieceofcake2/bake 1.0.3 or later); removed the instruction to move them

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/ and templates/Plugin overrides; internal plugin structure and test directories explained; App::uses() kept in plugin code with the reason
    • Bake commands use bin/cake with the Bake plugin; added the missing asset plugin-syntax example; removed flash/ asset folder
    • Publishing: removed plugins.cakephp.org/awesome-cakephp; added a composer.json example (type cakephp-plugin, composer/installers, installer-name)
    • New "Registering DSN Schemes" section (v2.12.7): setDsnClassMap() / getDsnClassMap() of ConnectionManager and CakeEmail in the plugin bootstrap, class names and callables, null removal, the method_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 the composer.json settings 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"
  • How To Install Plugins
    • Composer is the primary method (pieceofcake2/debug_kit example, composer/installers and installer-paths for plugins/); manual and Git installs use plugins/ and https URLs
    • Plugins are loaded in config/bootstrap.php; when App::uses() is still needed for plugin classes
    • composer.json installer-paths and allow-plugins (composer/installers, Composer 2.2+) documented as required so plugins land in plugins/<Name>/
    • Plugins that Composer does not load link to Autoloading
  • How To Use Plugins
    • Plugin loading shown in config/bootstrap.php with plugin Config/ file locations; schema command uses bin/cake
    • Plugin bootstraps that register DSN schemes
  • 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
  • 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.md and SECURITY.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.php into vendor/pieceofcake2/app/config, select the database with DB, run vendor/bin/phpunit and vendor/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 application phpcs.xml from 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
  • 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

Appendices ​

  • Changes from the Original Book
    • This page; moved from /pieceofcake2/changes in the removed "Piece of Cake 2" sidebar group to the Appendices
  • 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 of E_USER_ERROR, ConsoleLog colors, Validation::utf8(), Folder stream wrapper schemes, the console without an application core.php, PHPStan level 5 docblocks); the 'cipher' breaking-change section links to it
  • Migrating from SimpleTest to PHPUnit 3.7
    • Retitled "Migrating from SimpleTest to PHPUnit 3.7" and linked to the new PHPUnit 9.6 guide

Based on the CakePHP Cookbook. Content licensed under CC BY-NC-SA 4.0. Not affiliated with the Cake Software Foundation.