diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..197a929bc2 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,23 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at https://editorconfig.org + +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.bat] +end_of_line = crlf + +[*.yml] +indent_size = 2 + +[Makefile] +indent_style = tab + +[*.neon] +indent_style = tab diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..b8be3562ac --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +version: 2 +updates: +- package-ecosystem: pip + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 + ignore: + - dependency-name: sphinx + versions: + - ">= 3.a" + - "< 4" +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 diff --git a/.github/workflows/deploy_2.yml b/.github/workflows/deploy_2.yml new file mode 100644 index 0000000000..45ccc847ba --- /dev/null +++ b/.github/workflows/deploy_2.yml @@ -0,0 +1,28 @@ +--- +name: 'deploy_2' + +on: + push: + branches: + - 2.x + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Cloning repo + uses: actions/checkout@v5 + with: + fetch-depth: 0 + + - name: Push to dokku + uses: dokku/github-action@master + with: + branch: '2.x' + git_remote_url: 'ssh://dokku@apps.cakephp.org:22/newbook-2' + git_push_flags: '-f' + ssh_private_key: ${{ secrets.DOKKU_SSH_PRIVATE_KEY }} diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000000..47bbb9dbfb --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,29 @@ +name: Mark stale issues and pull requests + +on: + schedule: + - cron: "0 0 * * *" + +permissions: + contents: read + +jobs: + stale: + + permissions: + issues: write # for actions/stale to close stale issues + pull-requests: write # for actions/stale to close stale PRs + runs-on: ubuntu-latest + + steps: + - uses: actions/stale@v10 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: 'This issue is stale because it has been open for 120 days with no activity. Remove the `stale` label or comment or this will be closed in 15 days' + stale-pr-message: 'This pull request is stale because it has been open 120 days with no activity. Remove the `stale` label or comment on this issue, or it will be closed in 15 days' + stale-issue-label: 'stale' + stale-pr-label: 'stale' + days-before-stale: 120 + days-before-close: 15 + exempt-issue-labels: 'pinned' + exempt-pr-labels: 'pinned' diff --git a/.gitignore b/.gitignore index cb48f5b9ac..1de888e91c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,26 @@ -*.pyc -build/* -*/_build/* -.DS_Store +# Project specific files # +########################## +.vitepress/dist +.vitepress/cache +.vitepress/.temp +/node_modules/ +.temp/ + +# IDE and editor specific files # +################################# +/nbproject +.idea .project +.vscode +.zed + +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +Icon? +ehthumbs.db +Thumbs.db diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..80ffb5a73e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,51 @@ +# ---------------------- +# 1. Build stage +# ---------------------- +FROM node:22-alpine AS builder + +# Install git and rsync +RUN apk add --no-cache git rsync + +WORKDIR /app + +# Bust cache by fetching latest commit info +ADD https://api.github.com/repos/cakephp/docs-skeleton/git/refs/heads/main /tmp/cache-bust.json + +# Clone cakephp-docs-skeleton into vitepress directory +RUN git clone --depth 1 https://github.com/cakephp/docs-skeleton.git vitepress + +# Copy documentation and config files into the skeleton +# Use rsync to merge docs instead of replacing to preserve shared public assets +RUN --mount=type=bind,source=docs,target=/tmp/docs \ + rsync -av /tmp/docs/ vitepress/docs/ + +COPY config.js vitepress/config.js +COPY toc_en.json vitepress/toc_en.json +COPY toc_ja.json vitepress/toc_ja.json + +# Install vitepress deps +WORKDIR /app/vitepress +RUN npm install + +# Increase max-old-space-size to avoid memory issues during build +ENV NODE_OPTIONS="--max-old-space-size=8192" + +# Build VitePress site +RUN npm run docs:build + +# ---------------------- +# 2. Runtime stage (nginx) +# ---------------------- +FROM nginx:1.27-alpine AS runner + +# Copy built files +COPY --from=builder /app/vitepress/.vitepress/dist /usr/share/nginx/html + +# Expose port +EXPOSE 80 + +# Health check (optional) +HEALTHCHECK CMD wget --quiet --tries=1 --spider http://localhost:80/ || exit 1 + +# Start nginx +CMD ["nginx", "-g", "daemon off;"] diff --git a/Makefile b/Makefile deleted file mode 100644 index f73e8bdd73..0000000000 --- a/Makefile +++ /dev/null @@ -1,83 +0,0 @@ -# MakeFile for building all the docs at once. -# Inspired by the Makefile used by bazaar. -# http://bazaar.launchpad.net/~bzr-pqm/bzr/2.3/ - -PYTHON = python -ES_HOST = - -.PHONY: all clean html latexpdf epub htmlhelp website website-dirs - -# Languages that can be built. -LANGS = en es fr ja pt ru ro sr zh - -# pdflatex does not like ja or ru for some reason. -PDF_LANGS = en es fr pt ro - -DEST = website - -# Dependencies to perform before running other builds. -# Clone the en/Makefile everywhere. -SPHINX_DEPENDENCIES = $(foreach lang, $(LANGS), $(lang)/Makefile) - -# Copy-paste the English Makefile everywhere it's needed. -%/Makefile: en/Makefile - cp $< $@ - -# -# The various formats the documentation can be created in. -# -# Loop over the possible languages and call other build targets. -# -html: $(foreach lang, $(LANGS), html-$(lang)) -htmlhelp: $(foreach lang, $(LANGS), htmlhelp-$(lang)) -epub: $(foreach lang, $(LANGS), epub-$(lang)) -latex: $(foreach lang, $(PDF_LANGS), latex-$(lang)) -pdf: $(foreach lang, $(PDF_LANGS), pdf-$(lang)) -htmlhelp: $(foreach lang, $(LANGS), htmlhelp-$(lang)) -populate-index: $(foreach lang, $(LANGS), populate-index-$(lang)) - - -# Make the HTML version of the documentation with correctly nested language folders. -html-%: $(SPHINX_DEPENDENCIES) - cd $* && make html LANG=$* - -htmlhelp-%: $(SPHINX_DEPENDENCIES) - cd $* && make htmlhelp LANG=$* - -epub-%: $(SPHINX_DEPENDENCIES) - cd $* && make epub LANG=$* - -latex-%: $(SPHINX_DEPENDENCIES) - cd $* && make latex LANG=$* - -pdf-%: $(SPHINX_DEPENDENCIES) - cd $* && make latexpdf LANG=$* - -populate-index-%: $(SPHINX_DEPENDENCIES) - php scripts/populate_search_index.php $* $(ES_HOST) - -website-dirs: - # Make the directory if its not there already. - [ ! -d $(DEST) ] && mkdir $(DEST) || true - - # Make the downloads directory - [ ! -d $(DEST)/_downloads ] && mkdir $(DEST)/_downloads || true - - # Make downloads for each language - $(foreach lang, $(LANGS), [ ! -d $(DEST)/_downloads/$(lang) ] && mkdir $(DEST)/_downloads/$(lang) || true;) - -website: website-dirs html populate-index epub pdf - # Move HTML - $(foreach lang, $(LANGS), cp -r build/html/$(lang) $(DEST)/$(lang);) - - # Move EPUB files - $(foreach lang, $(LANGS), cp -r build/epub/$(lang)/*.epub $(DEST)/_downloads/$(lang) || true;) - - # Move PDF files - $(foreach lang, $(PDF_LANGS), [ -f build/latex/$(lang)/*.pdf ] && cp -r build/latex/$(lang)/*.pdf $(DEST)/_downloads/$(lang) || true;) - -clean: - rm -rf build/* - -clean-website: - rm -rf $(DEST)/* diff --git a/README.md b/README.md new file mode 100644 index 0000000000..2e1b236a23 --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +CakePHP Documentation +===================== + +[![License: CC BY-NC-SA 4.0](https://img.shields.io/badge/License-CC%20BY--NC--SA%204.0-lightgreen.svg)](https://creativecommons.org/licenses/by-nc-sa/4.0/) +[![Build Status](https://github.com/cakephp/docs/actions/workflows/ci.yml/badge.svg?branch=5.x)](https://github.com/cakephp/docs/actions/workflows/ci.yml) + +This is the official documentation for the CakePHP project. It is available +online at https://book.cakephp.org. + +Contributing to the documentation is pretty simple. Please read the +documentation on contributing to the documentation over on [the +cookbook](https://book.cakephp.org/5/en/contributing/documentation.html) for +help. You can read all the documentation within as it is just in plain text +files, marked up with Markdown formatting. + +## Local Development + +For working with the documentation markdown files locally, use the provided development server script: + +```bash +./bin/dev-server.sh +``` + +This script will: +- Set up a clean `.temp` working directory +- Clone the VitePress skeleton repository +- Sync your documentation files +- Install dependencies +- Start a local development server with hot-reload + +The documentation will be available at `http://localhost:5173` + +### Development Server Options + +```bash +# Start on a custom port +./bin/dev-server.sh --port 3000 + +# Adjust docs sync interval (default: 1 second) +./bin/dev-server.sh --sync-interval 2 +``` + +### Prerequisites + +The development server requires: +- `git` - Version control +- `node` - JavaScript runtime +- `npm` - Package manager +- `rsync` - File synchronization + +Press `Ctrl+C` to stop the development server. + +## Build the Documentation with Docker + +Docker will let you create a container with all packages needed to build the +docs. You need to have docker installed, see the [official docs of +docker](https://docs.docker.com/desktop/) for more information. + +### Build the image locally + +Starting in the top-level directory, you can build the provided `Dockerfile` +and tag it with the name `cakephp/docs` by running: + +```bash +docker build -f Dockerfile -t cakephp/docs . +``` + +This can take a little while, because all packages needs to be downloaded, but +you'll only need to do this once. + +Now that the image is built, you can run the commands to build the docs: + +##### To build the static site: +```bash +docker build --progress=plain --no-cache -f Dockerfile -t cake-docs . +``` + +##### To run the development server: +```bash +docker run -d -p 8080:80 --name cakedocs cake-vitepress +``` + +The built documentation will output to the `.vitepress/dist` directory. + +## Contributing + +You are welcome to make suggestions for new content as commits in a +GitHub fork. Please make any totally new sections in a separate branch. This +makes changes far easier to integrate later on. + +The documentation is written in Markdown and uses VitePress for static site generation. +All documentation files are located in the `docs/` directory, organized by version. + +## Search Functionality + +The documentation includes built-in search functionality powered by VitePress's local search feature. +Search works automatically in both development and production builds without requiring any additional setup. diff --git a/README.mdown b/README.mdown deleted file mode 100644 index 7e1fbe5336..0000000000 --- a/README.mdown +++ /dev/null @@ -1,103 +0,0 @@ -CakePHP Documentation -===================== - -This is the official documentation for the CakePHP project. It is available online in HTML, PDF and EPUB formats at http://book.cakephp.org. - -Requirements ------------- - -You can read all of the documentation within as its just in plain text files, marked up with ReST text formatting. To build the documentation you'll need the following: - -* Make -* Python -* Sphinx -* PhpDomain for sphinx - -You can install sphinx using: - - easy_install sphinx - -You can install the phpdomain using: - - easy_install sphinxcontrib-phpdomain - -*To run the easy_install command, the setuptools package must be previously installed.* - -Building the Documentation --------------------------- - -After installing the required packages, you can build the documentation using `make`. - - # Create all the HTML docs. Including all the languages. - make html - - # Create just the English HTML docs. - make html-en - - # Create all the EPUB (e-book) docs. - make epub - - # Create just the English EPUB docs. - make epub-en - - # Populate the search index - make populate-index - -This will generate all the documentation in an HTML form. Other output such as 'htmlhelp' are not fully complete at this time. - -After making changes to the documentation, you can build the HTML version of the docs by using `make html` again. This will build only the HTML files that have had changes made to them. - -Building the PDF ----------------- - -Building the PDF is a non-trivial task. - -1. Install LaTeX - This varies by distribution/OS so refer to your package manager. You should install the full LaTeX package. The basic one requires many additional packages to be installed with `tlmgr` -2. Run `make latex-en`. -3. Run `make pdf-en`. - -At this point the completed PDF should be in build/latex/en/CakePHPCookbook.pdf. - - -Contributing ------------- - -Contributing to the documentation is pretty simple. Please read the documentation on contributing to the documentation over on [the cookbook](http://book.cakephp.org/2.0/en/contributing/documentation.html) for help. - -There are currently a number of outstanding issues that need to be addressed. We've tried to flag these with `.. todo::` where possible. To see all the outstanding todo's add the following to your `config/all.py` - - todo_include_todos = True - -After rebuilding the HTML content, you should see a list of existing todo items at the bottom of the table of contents. - -You are also welcome to make and suggestions for new content as commits in a GitHub fork. Please make any totally new sections in a separate branch. This makes changes far easier to integrate later on. - -Translations ------------- - -Contributing translations requires that you make a new directory using the two letter name for your language. As content is translated, directories mirroring the english content should be created with localized content. - - -Generating Meta Tags --------------------- - -If you are providing translations and want to automatically generate meta tags for the resulting HTML files, a MetatagShell is provided in -the `scripts` folder of this repo. In order to use it, copy it into any CakePHP 2.0 empty application inside `app/Console/Command`, execute -`Console/cake metatag` and follow the instructions. - -The script will process all the files under one of the translation folders and generate the possible description terms using an external API, -it is a good idea to go over the generated terms and clean-up whatever noise it might have generated. - -Making Search Work Locally --------------------------- - -* Install elasticsearch. This varies based on your platform, but most - package managers have a package for it. -* Clone the [docs_search](https://github.com/cakephp/docs_search) into a - web accessible directory. -* Modify `searchUrl` in `themes/cakephp/static/app.js` to point at the - baseurl for your docs_search clone. -* Start elasticsearch with the default configuration. -* Populate the search index using `make populate-index`. -* You should now be able to search the docs using elasticsearch. - diff --git a/bin/dev-server.sh b/bin/dev-server.sh new file mode 100755 index 0000000000..9423fa1a1f --- /dev/null +++ b/bin/dev-server.sh @@ -0,0 +1,319 @@ +#!/bin/bash + +# ============================================================================== +# CakePHP vitepress docs dev server orchestration script +# ------------------------------------------------------------------------------ +# This script orchestrates the VitePress development environment by: +# 1. Cleaning and setting up .temp directory +# 2. Cloning the cakephp-docs-skeleton repository +# 3. Syncing docs folder and symlinking config files +# 4. Installing dependencies +# 5. Starting the VitePress dev server with live sync +# ------------------------------------------------------------------------------ +# Usage: ./dev-server.sh [OPTIONS] +# --port PORT Specify the port (default: 5173) +# --sync-interval N Rsync interval in seconds (default: 1) +# --skeleton-path PATH Use local skeleton repo instead of cloning +# --help Show this help message +# ============================================================================== + +set -e # Exit on error + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Configuration +PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TEMP_DIR="${PROJECT_ROOT}/.temp" +SKELETON_REPO="https://github.com/cakephp/docs-skeleton.git" +SKELETON_PATH="" +DEV_PORT=5173 +SYNC_INTERVAL=1 +RSYNC_PID="" + +# Parse arguments +while [[ $# -gt 0 ]]; do + case $1 in + --port) + DEV_PORT="$2" + shift 2 + ;; + --sync-interval) + SYNC_INTERVAL="$2" + shift 2 + ;; + --skeleton-path) + SKELETON_PATH="$2" + shift 2 + ;; + -h|--help) + head -n 17 "$0" | tail -n 14 | sed 's/^# //' + exit 0 + ;; + *) + echo "Unknown option: $1" + exit 1 + ;; + esac +done + +# Helper functions +log_info() { + echo -e "${BLUE}ℹ ${1}${NC}" +} + +log_success() { + echo -e "${GREEN}✓ ${1}${NC}" +} + +log_warn() { + echo -e "${YELLOW}⚠ ${1}${NC}" +} + +log_error() { + echo -e "${RED}✗ ${1}${NC}" +} + +# Check prerequisites +check_prerequisites() { + log_info "Checking prerequisites..." + + local missing_tools=() + + if ! command -v git &> /dev/null; then + missing_tools+=("git") + fi + + if ! command -v node &> /dev/null; then + missing_tools+=("node") + fi + + if ! command -v npm &> /dev/null; then + missing_tools+=("npm") + fi + + if ! command -v rsync &> /dev/null; then + missing_tools+=("rsync") + fi + + if [ ${#missing_tools[@]} -gt 0 ]; then + log_error "Missing required tools: ${missing_tools[*]}" + exit 1 + fi + + log_success "All prerequisites installed" + echo " - node: $(node --version)" + echo " - npm: $(npm --version)" + echo " - rsync: $(rsync --version | head -1 | awk '{print $3}')" +} + +# Setup .temp directory +setup_temp_dir() { + if [ -d "$TEMP_DIR" ]; then + log_info "Removing existing .temp directory..." + rm -rf "$TEMP_DIR" + fi + + log_info "Creating .temp directory..." + mkdir -p "$TEMP_DIR" + log_success ".temp directory ready" +} + +# Clone or copy skeleton repository +clone_skeleton() { + if [ -n "$SKELETON_PATH" ]; then + # Convert to absolute path + local abs_skeleton_path + abs_skeleton_path="$(cd "$SKELETON_PATH" && pwd)" + + log_info "Copying local skeleton from: $abs_skeleton_path" + + if [ ! -d "$abs_skeleton_path" ]; then + log_error "Skeleton path not found: $abs_skeleton_path" + exit 1 + fi + + # Copy all files and directories from skeleton to .temp (excluding docs, node_modules, .git) + rsync -a \ + --exclude='docs/' \ + --exclude='node_modules/' \ + --exclude='.git/' \ + --exclude='package-lock.json' \ + "$abs_skeleton_path/" "$TEMP_DIR/" + + log_success "Local skeleton copied" + else + log_info "Cloning docs-skeleton repository..." + git clone --depth 1 "$SKELETON_REPO" "$TEMP_DIR" 2>&1 | grep -E "(Cloning|Resolving|Receiving)" || true + log_success "Skeleton repository cloned" + fi +} + +# Initial sync of docs folder +sync_docs_initial() { + log_info "Syncing docs folder..." + + local src="${PROJECT_ROOT}/docs/" + local dest="${TEMP_DIR}/docs/" + + if [ ! -d "$src" ]; then + log_error "Source docs directory not found: $src" + exit 1 + fi + + # Ensure destination directory exists + mkdir -p "$dest" + + # Initial sync + rsync -az "$src" "$dest" + log_success "Docs folder synced" +} + +# Start background rsync watcher +start_rsync_watcher() { + log_info "Starting docs sync watcher..." + + local src="${PROJECT_ROOT}/docs/" + local dest="${TEMP_DIR}/docs/" + + # Start rsync in background loop + ( + while true; do + rsync -az "$src" "$dest" 2>/dev/null + sleep "$SYNC_INTERVAL" + done + ) & + + RSYNC_PID=$! + log_success "Docs sync watcher started (PID: $RSYNC_PID)" +} + +# Create symlinks for config files +create_symlinks() { + log_info "Creating symlinks for config files..." + + # List of files to symlink (not docs, which is synced) + local items=( + "config.js" + "toc_en.json" + "toc_ja.json" + ) + + for item in "${items[@]}"; do + local src="${PROJECT_ROOT}/${item}" + local dest="${TEMP_DIR}/${item}" + + if [ ! -e "$src" ]; then + log_warn "Source not found: $src (skipping)" + continue + fi + + # Remove existing file/symlink if it exists + if [ -e "$dest" ] || [ -L "$dest" ]; then + rm -rf "$dest" + fi + + ln -s "$src" "$dest" + log_success "Symlinked: $item" + done +} + +# Install dependencies +install_dependencies() { + log_info "Installing VitePress dependencies..." + + cd "$TEMP_DIR" + npm install --quiet + log_success "Dependencies installed" +} + +# Display start information +show_startup_info() { + echo "" + echo -e "${GREEN}════════════════════════════════════════════════════════${NC}" + echo -e "${GREEN} VitePress Dev Server Ready${NC}" + echo -e "${GREEN}════════════════════════════════════════════════════════${NC}" + echo "" + echo " 📂 Project Root: ${PROJECT_ROOT}" + echo " 📂 Temp Directory: ${TEMP_DIR}" + if [ -n "$SKELETON_PATH" ]; then + echo " 📦 Skeleton Source: ${SKELETON_PATH} (local)" + else + echo " 📦 Skeleton Source: ${SKELETON_REPO} (remote)" + fi + echo " 🔗 Port: ${DEV_PORT}" + echo " 🔄 Docs Sync: Active (rsync every ${SYNC_INTERVAL}s)" + echo "" + echo " 📚 Documentation: http://localhost:${DEV_PORT}" + echo "" + echo " ℹ️ Docs folder syncs every ${SYNC_INTERVAL}s via rsync" + echo " ℹ️ Config files (config.js, toc_*.json) are symlinked" + echo "" + echo " To stop the server: Press Ctrl+C" + echo "" + echo -e "${GREEN}════════════════════════════════════════════════════════${NC}" + echo "" +} + +# Start dev server +start_dev_server() { + log_info "Starting VitePress dev server on port ${DEV_PORT}..." + log_warn "Please wait, VitePress server may take a moment to start up..." + cd "$TEMP_DIR" + npm run docs:dev -- --port "$DEV_PORT" +} + +# Cleanup on exit +cleanup_on_exit() { + echo "" + log_info "Shutting down..." + + # Kill rsync watcher if running + if [ -n "$RSYNC_PID" ] && kill -0 "$RSYNC_PID" 2>/dev/null; then + log_info "Stopping docs sync watcher (PID: $RSYNC_PID)..." + kill "$RSYNC_PID" 2>/dev/null || true + fi + + log_success "Dev server stopped" +} + +trap cleanup_on_exit EXIT INT TERM + +# Main execution +main() { + echo "" + log_info "VitePress Dev Server Setup" + log_info "================================" + echo "" + + check_prerequisites + echo "" + + setup_temp_dir + echo "" + + clone_skeleton + echo "" + + sync_docs_initial + echo "" + + create_symlinks + echo "" + + install_dependencies + echo "" + + start_rsync_watcher + echo "" + + show_startup_info + + start_dev_server +} + +main "$@" diff --git a/config.js b/config.js new file mode 100644 index 0000000000..66d8b105e7 --- /dev/null +++ b/config.js @@ -0,0 +1,74 @@ +import { createRequire } from "module"; +const require = createRequire(import.meta.url); +const toc_en = require("./toc_en.json"); +const toc_ja = require("./toc_ja.json"); + +const versions = { + text: "2.x", + items: [ + { text: "5.x (latest)", link: "https://book.cakephp.org/5.x/", target: '_self' }, + { text: "4.x", link: "https://book.cakephp.org/4.x/", target: '_self' }, + { text: "3.x", link: "https://book.cakephp.org/3.x/", target: '_self' }, + { text: "2.x", link: "https://book.cakephp.org/2.x/", target: '_self' }, + { text: "Next releases", items: [ + { text: "5.next", link: "https://book.cakephp.org/5.next/", target: '_self' }, + { text: "6.x", link: "https://book.cakephp.org/6.x/", target: '_self' }, + ]}, + ], +}; + +// This file contains overrides for .vitepress/config.js +export default { + base: '/2.x/', + rewrites: { + "en/:slug*": ":slug*", + }, + sitemap: { + hostname: "https://book.cakephp.org/2.x/", + }, + themeConfig: { + socialLinks: [ + { icon: "github", link: "https://github.com/cakephp/cakephp" }, + ], + editLink: { + pattern: "https://github.com/cakephp/docs/edit/2.x/docs/:path", + text: "Edit this page on GitHub", + }, + sidebar: toc_en, + nav: [ + { text: "Getting Started", link: "/getting-started" }, + { text: "API", link: "https://api.cakephp.org/" }, + { text: "Documentation", link: "/" }, + { ...versions }, + ], + versionBanner: { + message: 'This version of the documentation is for CakePHP 2.x.', + link: '/latest/', + linkText: 'Go to latest docs.' + } + }, + substitutions: { + '|phpversion|': { value: '5.x', format: 'bold' }, + '|minphpversion|': { value: '5.x', format: 'italic' }, + '|cakeversion|': '2.x', + }, + locales: { + root: { + label: "English", + lang: "en", + }, + ja: { + label: "Japanese", + lang: "ja", + themeConfig: { + nav: [ + { text: "ガイド", link: "/ja/intro" }, + { text: "API", link: "https://api.cakephp.org/" }, + { text: "ドキュメント", link: "/ja/" }, + { ...versions }, + ], + sidebar: toc_ja, + }, + }, + }, +}; diff --git a/config/__init__.py b/config/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/config/all.py b/config/all.py deleted file mode 100644 index a1eb0c2e38..0000000000 --- a/config/all.py +++ /dev/null @@ -1,303 +0,0 @@ -# Global configuration information used across all the -# translations of documentation. -# - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = [ - 'sphinx.ext.todo', - 'sphinxcontrib.phpdomain', - 'config.cakei18n', - 'config.cakebranch' -] - -# Add any paths that contain templates here, relative to this directory. -# templates_path = [] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'contents' - -# General information about the project. -project = u'CakePHP Cookbook' -copyright = u'2014, Cake Software Foundation, Inc' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '2.x' - -# The full version, including alpha/beta/rc tags. -release = '2.x' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [ - 'themes', - 'core-libraries/components/email.rst' -] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - -highlight_language = 'phpinline' - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'cakephp' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -html_theme_path = ['../themes'] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None -html_short_title = u'Cookbook 2.x' - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -html_sidebars = { - '**' : ['globaltoc.html', 'localtoc.html'] -} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'CakePHPCookbookdoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -# The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' - -# The font size ('10pt', '11pt' or '12pt'). -latex_font_size = '11pt' - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('pdf-contents', 'CakePHPCookbook.tex', u'CakePHP Cookbook Documentation', - u'Cake Software Foundation', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -latex_logo = '../themes/cakephp/static/pdf-logo.png' - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = True - -# If true, show URL addresses after external links. -latex_show_urls = 'footnote' - -# Additional stuff for the LaTeX preamble. -#latex_preamble = '' - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -preamb = ur''' -% Custom colors. -\definecolor{ChapterColor}{RGB}{201,36,52} -\definecolor{TitleColor}{RGB}{0,0,0} - -% No section numbering -\setcounter{secnumdepth}{0} - -% Make chapter titles red. -\ChNameVar{\color{TitleColor}\Large} -\ChNumVar{\color{TitleColor}\Large} -\ChTitleVar{\color{ChapterColor}\Huge\sf} - -% link colors -\definecolor{InnerLinkColor}{RGB}{65,114,130} -\definecolor{OuterLinkColor}{RGB}{0,61,76} - -% background and border for code examples. -\definecolor{VerbatimColor}{RGB}{242,242,242} -\definecolor{VerbatimBorderColor}{RGB}{230,230,230} -''' - -latex_elements ={ - 'preamble': preamb, - 'fncychap': '\\usepackage[Sonny]{fncychap}' -} - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'cakephpcookbook', u'CakePHP Cookbook Documentation', - [u'CakePHP'], 1) -] - - -# -- Options for Epub output --------------------------------------------------- - -# Bibliographic Dublin Core info. -epub_title = u'CakePHP Cookbook' -epub_author = u'Cake Software Foundation, Inc.' -epub_publisher = u'Cake Software Foundation, Inc.' -epub_copyright = u'2013, Cake Software Foundation, Inc.' - -epub_theme = 'cakephp-epub' - -# The cover page information. -epub_cover = ('_static/epub-logo.png', 'epub-cover.html') - -# The language of the text. It defaults to the language option -# or en if the language is not set. -#epub_language = '' - -# The scheme of the identifier. Typical schemes are ISBN or URL. -epub_scheme = 'URL' - -# The unique identifier of the text. This can be a ISBN number -# or the project homepage. -epub_identifier = 'http://cakephp.org' - -# A unique identification for the text. -epub_uid = 'cakephpcookbook1393624653' - -# HTML files that should be inserted before the pages created by sphinx. -# The format is a list of tuples containing the path and title. -#epub_pre_files = [] - -# HTML files shat should be inserted after the pages created by sphinx. -# The format is a list of tuples containing the path and title. -#epub_post_files = [] - -# A list of files that should not be packed into the epub file. -epub_exclude_files = [ - 'index.html', - 'pdf-contents.html', - 'search.html', - 'contents.html' -] - -# The depth of the table of contents in toc.ncx. -epub_tocdepth = 2 - -# Allow duplicate toc entries. -epub_tocdup = False - -# If true, add an index to the epub document. -epub_use_index = False - -# Languages available. -languages = ['en', 'pt', 'es', 'ja', 'ru', 'fr', 'zh_CN'] - -# The GitHub branch name for this version of the docs -branch = 'master' - -# Hack to render the php source code without the 1: - folder = tokens[0] - else: - folder = lang - return SEP.join(dots) + SEP + folder + SEP + path + app.builder.link_suffix - - def has_lang(lang, path): - """ - Check to see if a language file exists for a given path/RST doc.: - """ - tokens = lang.split('_') - if len(tokens) > 1: - folder = tokens[0] - else: - folder = lang - possible = '..' + SEP + folder + SEP + path + app.config.source_suffix - full_path = os.path.realpath(os.path.join(os.getcwd(), possible)) - - return os.path.isfile(full_path) - - ctx['lang_link'] = lang_link - ctx['has_lang'] = has_lang - - ctx['languages'] = app.config.languages - ctx['language'] = app.config.language diff --git a/docs/en/appendices.md b/docs/en/appendices.md new file mode 100644 index 0000000000..4c5ae7cd46 --- /dev/null +++ b/docs/en/appendices.md @@ -0,0 +1,60 @@ +# Appendices + +Appendices contain information regarding the new features +introduced in 2.x, and the migration path from 1.3 to 2.0. + +## 2.10 Migration Guide + +- [2.10 Migration Guide](appendices/2-10-migration-guide) + +## 2.9 Migration Guide + +- [2.9 Migration Guide](appendices/2-9-migration-guide) + +## 2.8 Migration Guide + +- [2.8 Migration Guide](appendices/2-8-migration-guide) + +## 2.7 Migration Guide + +- [2.7 Migration Guide](appendices/2-7-migration-guide) + +## 2.6 Migration Guide + +- [2.6 Migration Guide](appendices/2-6-migration-guide) + +## 2.5 Migration Guide + +- [2.5 Migration Guide](appendices/2-5-migration-guide) + +## 2.4 Migration Guide + +- [2.4 Migration Guide](appendices/2-4-migration-guide) + +## 2.3 Migration Guide + +- [2.3 Migration Guide](appendices/2-3-migration-guide) + +## 2.2 Migration Guide + +- [2.2 Migration Guide](appendices/2-2-migration-guide) + +## 2.1 Migration Guide + +- [2.1 Migration Guide](appendices/2-1-migration-guide) +- [New Features in CakePHP 2.1](appendices/new-features-in-cakephp-2-1) + +## 2.0 Migration Guide + +- [2.0 Migration Guide](appendices/2-0-migration-guide) +- [New Features in CakePHP 2.0](appendices/new-features-in-cakephp-2-0) +- [PHPUnit Migration Hints](appendices/phpunit-migration-hints) + +## Migration from 1.2 to 1.3 + +- [Migrating from CakePHP 1.2 to 1.3](appendices/migrating-from-cakephp-1-2-to-1-3) +- [New features in CakePHP 1.3](appendices/new-features-in-cakephp-1-3) + +## General Information + +- [Glossary](appendices/glossary) diff --git a/docs/en/appendices/2-0-migration-guide.md b/docs/en/appendices/2-0-migration-guide.md new file mode 100644 index 0000000000..57563c15c1 --- /dev/null +++ b/docs/en/appendices/2-0-migration-guide.md @@ -0,0 +1,1251 @@ +# 2.0 Migration Guide + +This page summarizes the changes from CakePHP 1.3 that will assist in a project +migration to 2.0, as well as for a developer reference to get up to date with +the changes made to the core since the CakePHP 1.3 branch. Be sure to read the +other pages in this guide for all the new features and API changes. + +> [!TIP] +> Be sure to checkout the [Upgrade Shell](../console-and-shells/upgrade-shell#upgrade-shell) included in the 2.0 core to help you +> migrate your 1.3 code to 2.0. + +## PHP Version Support + +CakePHP 2.x supports PHP Version 5.2.8 and above. PHP4 support has been dropped. +For developers that are still working with production PHP4 environments, the +CakePHP 1.x versions continue to support PHP4 for the lifetime of their +development and support lifetime. + +The move to PHP 5 means all methods and properties have been updated with +visibility keywords. If your code is attempting access to private or protected +methods from a public scope, you will encounter errors. + +While this does not really constitute a large framework change, it means that +access to tighter visibility methods and variables is now not possible. + +## File and Folder naming + +In CakePHP 2.0 we rethought the way we are structuring our files and folders. +Given that PHP 5.3 is supporting namespaces we decided to prepare our code base +for adopting in a near future this PHP version, so we adopted the +. At first +we glanced at the internal structure of CakePHP 1.3 and realized that after all +these years there was no clear organization in the files, nor did the directory +structure really hint where each file should be located. With this change we +would be allowed to experiment a little with (almost) automatic class loading +for increasing the overall framework performance. + +Biggest roadblock for achieving this was maintaining some sort of backwards +compatibility in the way the classes are loaded right now, and we definitely did +not want to become a framework of huge class prefixes, having class names like +`My_Huge_Class_Name_In_Package`. We decided adopting a strategy of keeping simple +class names while offering a very intuitive way of declaring class locations and +clear migration path for future PHP 5.3 version of CakePHP. First let's +highlight the main changes in file naming standard we adopted: + +### File names + +All files containing classes should be named after the class it contains. No +file should contain more than one class. So, no more lowercasing and +underscoring your file names. Here are some examples: + +- `my_things_controller.php` becomes `MyThingsController.php` +- `form.php` (a Helper) becomes `FormHelper.php` +- `session.php` (a Component) becomes `SessionComponent.php` + +This makes file naming a lot more clear and consistent across applications, +and also avoids a few edge cases where the file loader would get confused in the +past and load files it should not. + +### Folder Names + +Most folders should be also CamelCased, especially when containing classes. +Think of namespaces, each folder represents a level in the namespacing +hierarchy, folders that do not contain classes, or do not constitute a +namespace on themselves, should be lowercased. + +CamelCased Folders: + +- Config +- Console +- Controller +- Controller/Component +- Lib +- Locale +- Model +- Model/Behavior +- Plugin +- Test +- Vendor +- View +- View/Helper + +lowercased Folders: + +- tmp +- webroot + +## htaccess (URL Rewriting) + +In your `app/webroot/.htaccess` replace line `RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]` with `RewriteRule ^(.*)$ index.php [QSA,L]` + +## AppController / AppModel / AppHelper / AppShell + +The `app/app_controller.php`, `app/app_model.php`, `app/app_helper.php` are now located and +named as `app/Controller/AppController.php`, `app/Model/AppModel.php` and `app/View/Helper/AppHelper.php` respectively. + +Also all shell/task now extend AppShell. You can have your custom AppShell.php at `app/Console/Command/AppShell.php` + +## Internationalization / Localization + +`__()` (Double underscore shortcut function) always returns the translation +(not echo anymore). + +If you want to echo the result of the translation, use: + +``` text +echo __('My Message'); +``` + +This change includes all shortcut translation methods: + +``` text +__() +__n() +__d() +__dn() +__dc() +__dcn() +__c() +``` + +Alongside this, if you pass additional parameters, the translation will call +[sprintf](https://www.php.net/manual/en/function.sprintf.php) with these +parameters before returning. For example: + +``` text +// Will return something like "Called: MyClass:myMethod" +echo __('Called: %s:%s', $className, $methodName); +``` + +It is valid for all shortcut translation methods. + +More information about the specifiers, you can see in +[sprintf](https://www.php.net/manual/en/function.sprintf.php) function. + +## Class location and constants changed + +The constants `APP` and `CORE_PATH` +have consistent values between the web and console environments. In previous +versions of CakePHP these values changed depending on your environment. + +## Basics.php + +- `getMicrotime()` has been removed. Use the native `microtime(true)` + instead. +- `e()` was removed. Use `echo`. +- `r()` was removed. Use `str_replace`. +- `a()` was removed. `Use array()` +- `aa()` was removed. Use `array()` +- `up()` was removed. Use `strtoupper()` +- `low()` was removed. Use `strtolower()` +- `params()` was removed. It was not used anywhere in CakePHP. +- `ife()` was removed. Use a ternary operator. +- `uses()` was removed. Use `App::import()` instead. +- Compatibility functions for PHP4 have been removed. +- PHP5 constant has been removed. +- Global var called `$TIME_START` was removed use the constant + `TIME_START` or `$_SERVER['REQUEST_TIME']` instead. + +### Removed Constants + +A number of constants were removed, as they were no longer accurate, or +duplicated. + +- APP_PATH +- BEHAVIORS +- COMPONENTS +- CONFIGS +- CONSOLE_LIBS +- CONTROLLERS +- CONTROLLER_TESTS +- ELEMENTS +- HELPERS +- HELPER_TESTS +- LAYOUTS +- LIB_TESTS +- LIBS +- MODELS +- MODEL_TESTS +- SCRIPTS +- VIEWS + +## CakeRequest + +This new class encapsulates the parameters and functions related to an incoming +request. It replaces many features inside `Dispatcher`, +`RequestHandlerComponent` and Controller. It also replaces +`$this->params` array in all places. `CakeRequest` implements +`ArrayAccess` so many interactions with the old params array do not need to +change. See the CakeRequest new features for more information. + +## Request handling, \$\_GET\['url'\] and .htaccess files + +CakePHP no longer uses `$_GET['url']` for handling application request paths. +Instead it uses `$_SERVER['PATH_INFO']`. This provides a more uniform way of +handling requests between servers with URL rewriting and those without. Because +of these changes, you'll need to update your .htaccess files and +`app/webroot/index.php`, as these files were changed to accommodate the +changes. Additionally `$this->params['url']['url']` no longer exists. Instead +you should be using \$this-\>request-\>url to access the same value. +This attribute now contains the url without the leading slash `/` prepended. + +Note: For the homepage itself (`http://domain/`) \$this-\>request-\>url now returns +boolean `false` instead of `/`. Make sure you check on that accordingly: + +``` php +if (!$this->request->url) {} // instead of $this->request->url === '/' +``` + +## Components + +Component is now the required base class for all components. You should update +your components and their constructors, as both have changed: + +``` php +class PrgComponent extends Component { + public function __construct(ComponentCollection $collection, + $settings = array()) { + parent::__construct($collection, $settings); + } +} +``` + +As with helpers it is important to call `parent::__construct()` in components with +overridden constructors. Settings for a component are also passed into the +constructor now, and not the `initialize()` callback. This makes getting well +constructed objects easier, and allows the base class to handle setting the +properties up. + +Since settings have been moved to the component constructor, the +`initialize()` callback no longer receives `$settings` as its 2nd parameter. +You should update your components to use the following method signature: + +``` php +public function initialize(Controller $controller) { } +``` + +Additionally, the initialize() method is only called on components that are +enabled. This usually means components that are directly attached to the +controller object. + +### Deprecated callbacks removed + +All the deprecated callbacks in Component have not been transferred to +ComponentCollection. Instead you should use the trigger() method to interact +with callbacks. If you need to trigger a callback you could do so by calling: + +``` php +$this->Components->trigger('someCallback', array(&$this)); +``` + +### Changes in disabling components + +In the past you were able to disable components via \$this-\>Auth-\>enabled = +false; for example. In CakePHP 2.0 you should use the ComponentCollection's +disable method, \$this-\>Components-\>disable('Auth');. Using the enabled +property will not work. + +### AclComponent + +- `AclComponent` implementations are now required to implement + `AclInterface`. +- `AclComponent::adapter()` has been added to allow runtime modification of + the `ACL` implementation the component uses. +- `AclComponent::grant()` has been deprecated, it will be removed in a future + version. Use `AclComponent::allow()` instead. +- `AclComponent::revoke()` has been deprecated, it will be removed in a + future version. Use AclComponent::deny() instead. + +### RequestHandlerComponent + +Many of RequestHandlerComponent's methods are just proxies for `CakeRequest` +methods. The following methods have been deprecated and will be removed in +future versions: + +- `isSsl()` +- `isAjax()` +- `isPost()` +- `isPut()` +- `isFlash()` +- `isDelete()` +- `getReferer()` +- `getClientIp()` +- `accepts()`, `prefers()`, `requestedWith()` All deal in mapped content + types now. They no longer work with mime-types. You can use + `RequestHandler::setContent()` to create new content types. +- `RequestHandler::setContent()` no longer accepts an array as a single + argument, you must supply both arguments. + +### SecurityComponent + +SecurityComponent no longer handles Basic and Digest Authentication. These are +both handled by the new AuthComponent. The following methods have been removed +from SecurityComponent: + +- requireLogin() +- generateDigestResponseHash() +- loginCredentials() +- loginRequest() +- parseDigestAuthData() + +In addition the following properties were removed: + +- \$loginUsers +- \$requireLogin + +Moving these features to AuthComponent was done to provide a single place for +all types of authentication and to streamline the roles of each component. + +### AuthComponent + +The AuthComponent was entirely re-factored for 2.0, this was done to help reduce +developer confusion and frustration. In addition, AuthComponent was made more +flexible and extensible. You can find out more in +the [Authentication](../core-libraries/components/authentication) guide. + +### EmailComponent + +The EmailComponent has been deprecated and has created a new library class to +send e-mails. See [CakeEmail](../core-utility-libraries/email) Email changes for more details. + +### SessionComponent + +Session component has lost the following methods. + +- activate() +- active() +- \_\_start() + +## cakeError removed + +The `cakeError()` method has been removed. It's recommended that you switch all +uses of `cakeError` to use exceptions. `cakeError` was removed because it +was simulating exceptions. Instead of simulation, real exceptions are used in +CakePHP 2.0. + +## Error handling + +The error handling implementation has dramatically changed in 2.0. Exceptions +have been introduced throughout the framework, and error handling has been +updated to offer more control and flexibility. You can read more in the +[Exceptions](../development/exceptions) and [Error Handling](../development/errors) section. + +## Lib classes + +### App + +The API for `App::build()` has changed to `App::build($paths, $mode).` It +now allows you to either append, prepend or reset/replace existing paths. The +\$mode param can take any of the following 3 values: App::APPEND, +App::PREPEND, `App::RESET`. The default behavior of the function remains the +same (ie. Prepending new paths to existing list). + +#### App::path() + +- Now supports plugins, App::path('Controller', 'Users') will return the folder + location of the controllers in the Users plugin. +- Won't merge core paths anymore, it will + only return paths defined in App::build() or default ones in app (or + corresponding plugin). + +#### App::build() + +- Will not merge app path with core paths anymore. + +#### App::objects() + +- Now supports plugins, App::objects('Users.Model') will return the models in + plugin Users. +- Returns array() instead of false for empty results or invalid types. +- Does not return core objects anymore, App::objects('core') will return array(). +- Returns the complete class name. + +App class lost the following properties, use method App::path() to access their value + +- App::\$models +- App::\$behaviors +- App::\$controllers +- App::\$components +- App::\$datasources +- App::\$libs +- App::\$views +- App::\$helpers +- App::\$plugins +- App::\$vendors +- App::\$locales +- App::\$shells + +#### App::import() + +- No longer looks for classes recursively, it strictly uses the values for the + paths defined in App::build(). +- Will not be able to load App::import('Component', 'Component') use + App::uses('Component', 'Controller'); +- Using App::import('Lib', 'CoreClass') to load core classes is no longer + possible. +- Importing a non-existent file, supplying a wrong type or package name, or null + values for \$name and \$file parameters will result in a false return value. +- App::import('Core', 'CoreClass') is no longer supported, use App::uses() + instead and let the class autoloading do the rest. +- Loading Vendor files does not look recursively in the vendors folder, it will + also no longer convert the file to underscored as it did in the past. + +#### App::core() + +- First parameter is no longer optional, it will always return one path +- It can't be used anymore to get the vendors paths +- It will only accept new style package names + +#### Class loading with App::uses() + +Although there has been a huge refactoring in how the classes are loaded, in very +few occasions you will need to change your application code to respect the way you were +used to doing it. The biggest change is the introduction of a new method: + +``` php +App::uses('AuthComponent', 'Controller/Component'); +``` + +We decided the function name should emulate PHP 5.3's `use` keyword, just as a way +of declaring where a class name should be located. The first parameter of +`App::uses()` is the complete name of the class you intend to load, +and the second one, the package name (or namespace) where it belongs to. The +main difference with CakePHP 1.3's `App::import()` is that the former +won't actually import the class, it will just setup the system so when the class +is used for the first time it will be located. + +Some examples on using `App::uses()` when migrating from +`App::import()`: + +``` php +App::import('Controller', 'Pages'); +// becomes +App::uses('PagesController', 'Controller'); + +App::import('Component', 'Auth'); +// becomes +App::uses('AuthComponent', 'Controller/Component'); + +App::import('View', 'Media'); +// becomes +App::uses('MediaView', 'View'); + +App::import('Core', 'Xml'); +// becomes +App::uses('Xml', 'Utility'); + +App::import('Datasource', 'MongoDb.MongoDbSource'); +// becomes +App::uses('MongoDbSource', 'MongoDb.Model/Datasource'); +``` + +All classes that were loaded in the past using `App::import('Core', $class);` +will need to be loaded using `App::uses()` referring to the correct package. +See the API to locate the classes in their new folders. Some examples: + +``` php +App::import('Core', 'CakeRoute'); +// becomes +App::uses('CakeRoute', 'Routing/Route'); + +App::import('Core', 'Sanitize'); +// becomes +App::uses('Sanitize', 'Utility'); + +App::import('Core', 'HttpSocket'); +// becomes +App::uses('HttpSocket', 'Network/Http'); +``` + +In contrast to how `App::import()` worked in the past, the new class +loader will not locate classes recursively. This led to an impressive +performance gain even on develop mode, at the cost of some seldom used features +that always caused side effects. To be clear again, the class loader will only +fetch the class in the exact package in which you told it to find it. + +#### App::build() and core paths + +`App::build()` will not merge app paths with core paths anymore. + +Examples: + +``` php +App::build(array('controllers' => array('/full/path/to/controllers'))); +//becomes +App::build(array('Controller' => array('/full/path/to/Controller'))); + +App::build(array('helpers' => array('/full/path/to/controllers'))); +//becomes +App::build(array('View/Helper' => array('/full/path/to/View/Helper'))); +``` + +### CakeLog + +- Log streams now need to implement `CakeLogInterface`. Exceptions will be raised + if a configured logger does not. + +### Cache + +- `Cache` is now a static class, it no longer has a getInstance() method. +- CacheEngine is now an abstract class. You cannot directly create instances of + it anymore. +- CacheEngine implementations must extend CacheEngine, exceptions will be + raised if a configured class does not. +- FileCache now requires trailing slashes to be added to the path setting when + you are modifying a cache configuration. +- Cache no longer retains the name of the last configured cache engine. This + means that operations you want to occur on a specific engine need to have the + \$config parameter equal to the config name you want the operation to occur + on. + +``` php +Cache::config('something'); +Cache::write('key', $value); + +// would become +Cache::write('key', $value, 'something'); +``` + +### Router + +- You can no longer modify named parameter settings with + `Router::setRequestInfo()`. You should use `Router::connectNamed()` to + configure how named parameters are handled. + +- Router no longer has a `getInstance()` method. It is a static class, call + its methods and properties statically. + +- `Router::getNamedExpressions()` is deprecated. Use the new router + constants. `Router::ACTION`, `Router::YEAR`, `Router::MONTH`, + `Router::DAY`, `Router::ID`, and `Router::UUID` instead. + +- `Router::defaults()` has been removed. Delete the core routes file + inclusion from your applications routes.php file to disable default routing. + Conversely if you want default routing, you will have to add an include to + `Cake/Config/routes.php` in your routes file. + +- When using Router::parseExtensions() the extension parameter is no longer + under `$this->params['url']['ext']`. Instead it is available at + `$this->request->params['ext']`. + +- Default plugin routes have changed. Plugin short routes are no longer built + in for any actions other than index. Previously `/users` and `/users/add` + would map to the UsersController in the Users plugin. In 2.0, only the + `index` action is given a short route. If you wish to continue using short + routes, you can add a route like: + + ``` php + Router::connect( + '/users/:action', + array('controller' => 'users', 'plugin' => 'users') + ); + ``` + + To your routes file for each plugin you need short routes on. + +Your app/Config/routes.php file needs to be updated adding this line at the bottom of the file: + +``` text +require CAKE . 'Config' . DS . 'routes.php'; +``` + +This is needed in order to generate the default routes for your application. If you do not wish to have such routes, +or want to implement your own standard you can include your own file with custom router rules. + +### Dispatcher + +- Dispatcher has been moved inside of cake/libs, you will have to update your + `app/webroot/index.php` file. +- `Dispatcher::dispatch()` now takes two parameters. The request and + response objects. These should be instances of `CakeRequest` & + `CakeResponse` or a subclass thereof. +- `Dispatcher::parseParams()` now only accepts a `CakeRequest` object. +- `Dispatcher::baseUrl()` has been removed. +- `Dispatcher::getUrl()` has been removed. +- `Dispatcher::uri()` has been removed. +- `Dispatcher::$here` has been removed. + +### Configure + +- `Configure::read()` with no parameter no longer returns the value of + 'debug' instead it returns all values in Configure. Use + `Configure::read('debug');` if you want the value of debug. +- `Configure::load()` now requires a ConfigReader to be setup. Read + [Loading Configuration Files](../development/configuration#loading-configuration-files) for more information. +- `Configure::store()` now writes values to a given Cache configuration. Read + [Loading Configuration Files](../development/configuration#loading-configuration-files) for more information. + +### Scaffold + +- Scaffold 'edit' views should be renamed to 'form'. This was done to make + scaffold and bake templates consistent. + - `views/scaffolds/edit.ctp` -\> `View/Scaffolds/form.ctp` + - `views/posts/scaffold.edit.ctp` -\> `View/Posts/scaffold.form.ctp` + +### Xml + +- The class Xml was completely re-factored. Now this class does not manipulate + data anymore, and it is a wrapper to SimpleXMLElement. You can use the following + methods: + - `Xml::build()`: static method that you can pass an xml string, array, path + to file or url. The result will be a SimpleXMLElement instance or an + exception will be thrown in case of error. + - `Xml::fromArray():` static method that returns a SimpleXMLElement from an + array. + - `Xml::toArray()`: static method that returns an array from + SimpleXMLElement. + +You should see the `Xml` documentation for more information on the changes made to +the Xml class. + +### Inflector + +- Inflector no longer has a `getInstance()` method. +- `Inflector::slug()` no longer supports the \$map argument. Use + `Inflector::rules()` to define transliteration rules. + +### CakeSession + +CakeSession is now a fully static class, both `SessionHelper` and +`SessionComponent` are wrappers and sugar for it. It can now easily be used +in models or other contexts. All of its methods are called statically. + +Session configuration has also changed [see the session section for more +information](../development/sessions) + +### HttpSocket + +- HttpSocket doesn't change the header keys. Following other places in core, + the HttpSocket does not change the headers. `2616` says that headers are case + insensitive, and HttpSocket preserves the values the remote host sends. +- HttpSocket returns responses as objects now. Instead of arrays, HttpSocket + returns instances of HttpResponse. See the `HttpSocket` + documentation for more information. +- Cookies are stored internally by host, not per instance. This means that, if + you make two requests to different servers, cookies from domain1 won't be sent + to domain2. This was done to avoid possible security problems. + +## Helpers + +### Constructor changed + +In order to accommodate View being removed from the ClassRegistry, the signature +of Helper::\_\_construct() was changed. You should update any subclasses to use +the following: + +``` php +public function __construct(View $View, $settings = array()) +``` + +When overriding the constructor you should always call parent::\_\_construct as +well. Helper::\_\_construct stores the view instance at \$this-\>\_View for +later reference. The settings are not handled by the parent constructor. + +### HelperCollection added + +After examining the responsibilities of each class involved in the View layer, +it became clear that View was handling much more than a single task. The +responsibility of creating helpers is not central to what View does, and was +moved into HelperCollection. HelperCollection is responsible for loading and +constructing helpers, as well as triggering callbacks on helpers. By default, +View creates a HelperCollection in its constructor, and uses it for subsequent +operations. The HelperCollection for a view can be found at \$this-\>Helpers + +The motivations for refactoring this functionality came from a few issues. + +- View being registered in ClassRegistry could cause registry poisoning issues + when requestAction or the EmailComponent were used. +- View being accessible as a global symbol invited abuse. +- Helpers were not self contained. After constructing a helper, you had to + manually construct several other objects in order to get a functioning object. + +You can read more about HelperCollection in the +[Collections](../core-libraries/collections) documentation. + +### Deprecated properties + +The following properties on helpers are deprecated, you should use the request +object properties or Helper methods instead of directly accessing these +properties as they will be removed in a future release. + +- `Helper::$webroot` is deprecated, use the request object's webroot + property. +- `Helper::$base` is deprecated, use the request object's base property. +- `Helper::$here` is deprecated, use the request object's here property. +- `Helper::$data` is deprecated, use the request object's data property. +- `Helper::$params` is deprecated, use the `$this->request` instead. + +### XmlHelper, AjaxHelper and JavascriptHelper removed + +The AjaxHelper and JavascriptHelper have been removed as they were deprecated in +version 1.3. The XmlHelper was removed, as it was made obsolete and redundant +with the improvements to `Xml`. The `Xml` class should be used to +replace previous usage of XmlHelper. + +The AjaxHelper, and JavascriptHelper are replaced with the JsHelper and HtmlHelper. + +### JsHelper + +- `JsBaseEngineHelper` is now abstract, you will need to implement all the + methods that previously generated errors. + +### PaginatorHelper + +- `PaginatorHelper::sort()` now takes the title and key arguments in the + reverse order. \$key will always be first now. This was done to prevent + needing to swap arguments when adding a second one. +- PaginatorHelper had a number of changes to the paging params used internally. + The default key has been removed. +- PaginatorHelper now supports generating links with paging parameters in the + querystring. + +There have been a few improvements to pagination in general. For more +information on that you should read the new pagination features page. + +### FormHelper + +#### \$selected parameter removed + +The `$selected` parameter was removed from several methods in `FormHelper`. +All methods now support a `$attributes['value']` key now which should be used +in place of `$selected`. This change simplifies the `FormHelper` methods, +reducing the number of arguments, and reduces the duplication that `$selected` +created. The effected methods are: + +- FormHelper::select() +- FormHelper::dateTime() +- FormHelper::year() +- FormHelper::month() +- FormHelper::day() +- FormHelper::hour() +- FormHelper::minute() +- FormHelper::meridian() + +#### Default URLs on forms is the current action + +The default url for all forms, is now the current url including passed, named, +and querystring parameters. You can override this default by supplying +`$options['url']` in the second parameter of `$this->Form->create()`. + +#### FormHelper::hidden() + +Hidden fields no longer remove the class attribute. This means that if there are +validation errors on hidden fields, the `error-field` class name will be +applied. + +### CacheHelper + +CacheHelper has been fully decoupled from View, and uses helper callbacks to +generate caches. You should remember to place CacheHelper after other helpers +that modify content in their `afterRender` and `afterLayout` callbacks. If +you don't some changes will not be part of the cached content. + +CacheHelper also no longer uses `` to indicate un-cached +regions. Instead it uses special HTML/XML comments. `` and +``. This helps CacheHelper generate valid markup and still +perform the same functions as before. You can read more CacheHelper and View +changes. + +### Helper Attribute format more flexible + +The Helper class has more 3 protected attributes: + +- `Helper::_minimizedAttributes`: array with minimized attributes (ie: + `array('checked', 'selected', ...)`); +- `Helper::_attributeFormat`: how attributes will be generated (ie: + `%s="%s"`); +- `Helper::_minimizedAttributeFormat`: how minimized attributes will be + generated: (ie `%s="%s"`) + +By default the values used in CakePHP 1.3 were not changed. But now you can +use boolean attributes from HTML, like ``. To +this, just change `$_minimizedAttributeFormat` in your AppHelper to `%s`. + +To use with Html/Form helpers and others, you can write: + +``` php +$this->Form->checkbox('field', array('checked' => true, 'value' => 'some_value')); +``` + +Other facility is that minimized attributes can be passed as item and not as +key. For example: + +``` php +$this->Form->checkbox('field', array('checked', 'value' => 'some_value')); +``` + +Note that `checked` have a numeric key. + +## Controller + +- Controller's constructor now takes two parameters. A CakeRequest, and + CakeResponse objects. These objects are used to populate several deprecated + properties and will be set to \$request and \$response inside the controller. +- `Controller::$webroot` is deprecated, use the request object's webroot + property. +- `Controller::$base` is deprecated, use the request object's base property. +- `Controller::$here` is deprecated, use the request object's here property. +- `Controller::$data` is deprecated, use the request object's data property. +- `Controller::$params` is deprecated, use the `$this->request` instead. +- `Controller::$Component` has been moved to `Controller::$Components`. See + the [Collections](../core-libraries/collections) documentation for more information. +- `Controller::$view` has been renamed to `Controller::$viewClass`. + `Controller::$view` is now used to change which view file is rendered. +- `Controller::render()` now returns a CakeResponse object. + +The deprecated properties on Controller will be accessible through a `__get()` +method. This method will be removed in future versions, so it's recommended that +you update your application. + +Controller now defines a maxLimit for pagination. This maximum limit is set to +100, but can be overridden in the \$paginate options. + +### Pagination + +Pagination has traditionally been a single method in Controller, this created a +number of problems though. Pagination was hard to extend, replace, or modify. For +2.0 pagination has been extracted into a component. `Controller::paginate()` still +exists, and serves as a convenience method for loading and using the +`PaginatorComponent`. + +For more information on the new features offered by pagination in 2.0, see the +[Pagination](../core-libraries/components/pagination) documentation. + +## View + +### View no longer registered in ClassRegistry + +The view being registered ClassRegistry invited abuse and affectively created a +global symbol. In 2.0 each Helper receives the current View instance in its +constructor. This allows helpers access to the view in a similar fashion as in +the past, without creating global symbols. You can access the view instance at +\$this-\>\_View in any helper. + +### Deprecated properties + +- `View::$webroot` is deprecated, use the request object's webroot property. +- `View::$base` is deprecated, use the request object's base property. +- `View::$here` is deprecated, use the request object's here property. +- `View::$data` is deprecated, use the request object's data property. +- `View::$params` is deprecated, use the `$this->request` instead. +- `View::$loaded` has been removed. Use the `HelperCollection` to access + loaded helpers. +- `View::$model` has been removed. This behavior is now on `Helper` +- `View::$modelId` has been removed. This behavior is now on + `Helper` +- `View::$association` has been removed. This behavior is now on + `Helper` +- `View::$fieldSuffix` has been removed. This behavior is now on + `Helper` +- `View::entity()` has been removed. This behavior is now on + `Helper` +- `View::_loadHelpers()` has been removed, used `View::loadHelpers()` + instead. +- How `View::element()` uses caching has changed, see below for more + information. +- View callbacks have been shifted around, see below for more information +- API for `View::element()` has changed. Read here for more info. + +The deprecated properties on View will be accessible through a `__get()` +method. This method will be removed in future versions, so it's recommended that +you update your application. + +### Removed methods + +- `View::_triggerHelpers()` Use `$this->Helpers->trigger()` instead. +- `View::_loadHelpers()` Use `$this->loadHelpers()` instead. Helpers now lazy + load their own helpers. + +### Added methods + +- `View::loadHelper($name, $settings = array());` Load a single helper. +- `View::loadHelpers()` Loads all the helpers indicated in `View::$helpers`. + +### View-\>Helpers + +By default View objects contain a `HelperCollection` at `$this->Helpers`. + +### Themes + +To use themes in your Controller you no longer set `public $view = 'Theme';`. +Use `public $viewClass = 'Theme';` instead. + +### Callback positioning changes + +beforeLayout used to fire after scripts_for_layout and content_for_layout were +prepared. In 2.0, beforeLayout is fired before any of the special variables are +prepared, allowing you to manipulate them before they are passed to the layout. +The same was done for beforeRender. It is now fired well before any view +variables are manipulated. In addition to these changes, helper callbacks always +receive the name of the file about to be rendered. This combined with helpers +being able to access the view through `$this->_View` and the current view +content through `$this->_View->output` gives you more power than ever before. + +### Helper callback signature changes + +Helper callbacks now always get one argument passed in. For beforeRender and +afterRender it is the view file being rendered. For beforeLayout and afterLayout +it is the layout file being rendered. Your helpers function signatures should +look like: + +``` php +public function beforeRender($viewFile) { + +} + +public function afterRender($viewFile) { + +} + +public function beforeLayout($layoutFile) { + +} + +public function afterLayout($layoutFile) { + +} +``` + +Element caching, and view callbacks have been changed in 2.0 to help provide you +with more flexibility and consistency. [Read more about those +changes](../views). + +### CacheHelper decoupled + +In previous versions there was a tight coupling between `CacheHelper` +and `View`. For 2.0 this coupling has been removed and CacheHelper +just uses callbacks like other helpers to generate full page caches. + +### CacheHelper `` tags changed + +In previous versions, CacheHelper used a special `` tag as +markers for output that should not be part of the full page cache. These tags +were not part of any XML schema, and were not possible to validate in HTML or +XML documents. For 2.0, these tags have been replaced with HTML/XML comments: + +``` html + becomes + becomes +``` + +The internal code for full page view caches has also changed, so be sure to +clear out view cache files when updating. + +### MediaView changes + +`MediaView::render()` now forces download of unknown file types +instead of just returning false. If you want you provide an alternate download +filename you now specify the full name including extension using key 'name' in +the array parameter passed to the function. + +## PHPUnit instead of SimpleTest + +All of the core test cases and supporting infrastructure have been ported to use +PHPUnit 3.7. Of course you can continue to use SimpleTest in your application by +replacing the related files. No further support will be given for SimpleTest and +it is recommended that you migrate to PHPUnit as well. For some additional +information on how to migrate your tests see PHPUnit migration hints. + +### No more group tests + +PHPUnit does not differentiate between group tests and single test cases in the +runner. Because of this, the group test options, and support for old style group +tests has been removed. It is recommended that GroupTests be ported to +`PHPUnit_Framework_Testsuite` subclasses. You can find several examples of this +in CakePHP's test suite. Group test related methods on `TestManager` have also +been removed. + +### Testsuite shell + +The testsuite shell has had its invocation simplified and expanded. You no +longer need to differentiate between `case` and `group`. It is assumed that +all tests are cases. In the past you would have done +`cake testsuite app case models/post` you can now do `cake testsuite app Model/Post`. + +The testsuite shell has been refactored to use the PHPUnit CLI tool. It now +supports all the command line options supported by PHPUnit. +`cake testsuite help` will show you a list of all possible modifiers. + +## Model + +Model relationships are now lazy loaded. You can run into a situation where +assigning a value to a nonexistent model property will throw errors: + +``` text +$Post->inexistentProperty[] = 'value'; +``` + +will throw the error "Notice: Indirect modification of overloaded property +\$inexistentProperty has no effect". Assigning an initial value to the property +solves the issue: + +``` text +$Post->nonexistentProperty = array(); +$Post->nonexistentProperty[] = 'value'; +``` + +Or just declare the property in the model class: + +``` php +class Post { + public $nonexistentProperty = array(); +} +``` + +Either of these approaches will solve the notice errors. + +The notation of `find()` in CakePHP 1.2 is no longer supported. Finds should use +notation `$model->find('type', array(PARAMS))` in CakePHP 1.3. + +- `Model::$_findMethods` is now `Model::$findMethods`. This property is now + public and can be modified by behaviors. + +### Database objects + +CakePHP 2.0 introduces some changes to Database objects that should not greatly +affect backwards compatibility. The biggest one is the adoption of PDO for +handling database connections. If you are using a vanilla installation of PHP 5 +you will already have installed the needed extensions, but you may need to +activate individual extensions for each driver you wish to use. + +Using PDO across all DBOs let us homogenize the code for each one and provide +more reliable and predictable behavior for all drivers. It also allowed us to +write more portable and accurate tests for database related code. + +The first thing users will probably miss is the "affected rows" and "total rows" +statistics, as they are not reported due to the more performant and lazy design +of PDO, there are ways to overcome this issue but very specific to each +database. Those statistics are not gone, though, but could be missing or even +inaccurate for some drivers. + +A nice feature added after the PDO adoption is the ability to use prepared +statements with query placeholders using the native driver if available. + +#### List of Changes + +- DboMysqli was removed, we will support DboMysql only. + +- API for DboSource::execute has changed, it will now take an array of query + values as second parameter: + + ``` php + public function execute($sql, $params = array(), $options = array()) + ``` + + became: + + ``` php + public function execute($sql, $options = array(), $params = array()) + ``` + + third parameter is meant to receive options for logging, currently it only + understands the "log" option. + +- DboSource::value() looses its third parameter, it was not used anyways + +- DboSource::fetchAll() now accepts an array as second parameter, to pass values + to be bound to the query, third parameter was dropped. Example: + + ``` php + $db->fetchAll( + 'SELECT + * from users + WHERE + username = ? + AND + password = ?', + array('jhon', '12345') + ); + $db->fetchAll( + 'SELECT + * from users + WHERE + username = :username + AND + password = :password', + array('username' => 'jhon', 'password' => '12345') + ); + ``` + +The PDO driver will automatically escape those values for you. + +- Database statistics are collected only if the "fullDebug" property of the + corresponding DBO is set to true. +- New method DboSource::getConnection() will return the PDO object in case you + need to talk to the driver directly. +- Treatment of boolean values changed a bit to make it more cross-database + friendly, you may need to change your test cases. +- PostgreSQL support was immensely improved, it now correctly creates schemas, + truncate tables, and is easier to write tests using it. +- DboSource::insertMulti() will no longer accept sql string, just pass an array + of fields and a nested array of values to insert them all at once +- TranslateBehavior was refactored to use model virtualFields, this makes the + implementation more portable. +- All tests cases with MySQL related stuff were moved to the corresponding + driver test case. This left the DboSourceTest file a bit skinny. +- Transaction nesting support. Now it is possible to start a transaction several + times. It will only be committed if the commit method is called the same + amount of times. +- SQLite support was greatly improved. The major difference with cake 1.3 is + that it will only support SQLite 3.x . It is a great alternative for + development apps, and quick at running test cases. +- Boolean column values will be casted to PHP native boolean type automatically, + so make sure you update your test cases and code if you were expecting the + returned value to be a string or an integer: If you had a "published" column in + the past using MySQL all values returned from a find would be numeric in the + past, now they are strict boolean values. + +## Behaviors + +### BehaviorCollection + +- `BehaviorCollection` no longer `strtolower()'s` mappedMethods. Behavior + mappedMethods are now case sensitive. + +### AclBehavior and TreeBehavior + +- No longer supports strings as configuration. Example: + + ``` php + public $actsAs = array( + 'Acl' => 'Controlled', + 'Tree' => 'nested' + ); + ``` + + became: + + ``` php + public $actsAs = array( + 'Acl' => array('type' => 'Controlled'), + 'Tree' => array('type' => 'nested') + ); + ``` + +## Plugins + +Plugins no longer magically append their plugin prefix to components, helpers +and models used within them. You must be explicit with the components, models, +and helpers you wish to use. In the past: + +``` php +public $components = array('Session', 'Comments'); +``` + +Would look in the controller's plugin before checking app/core components. It +will now only look in the app/core components. If you wish to use objects from a +plugin you must put the plugin name: + +``` php +public $components = array('Session', 'Comment.Comments'); +``` + +This was done to reduce hard to debug issues caused by magic misfiring. It also +improves consistency in an application, as objects have one authoritative way to +reference them. + +### Plugin App Controller and Plugin App Model + +The plugin AppController and AppModel are no longer located directly in the +plugin folder. They are now placed into the plugin's Controller and Model +folders as such: + + /app + /Plugin + /Comment + /Controller + CommentAppController.php + /Model + CommentAppModel.php + +## Console + +Much of the console framework was rebuilt for 2.0 to address many of the +following issues: + +- Tightly coupled. +- It was difficult to make help text for shells. +- Parameters for shells were tedious to validate. +- Plugin tasks were not reachable. +- Objects with too many responsibilities. + +### Backwards incompatible Shell API changes + +- `Shell` no longer has an `AppModel` instance. This `AppModel` instance + was not correctly built and was problematic. +- `Shell::_loadDbConfig()` has been removed. It was not generic enough to + stay in Shell. You can use the `DbConfigTask` if you need to ask the user + to create a db config. +- Shells no longer use `$this->Dispatcher` to access stdin, stdout, and + stderr. They have `ConsoleOutput` and `ConsoleInput` objects to handle + that now. +- Shells lazy load tasks, and use `TaskCollection` to provide an interface + similar to that used for Helpers, Components, and Behaviors for on the fly + loading of tasks. +- `Shell::$shell` has been removed. +- `Shell::_checkArgs()` has been removed. Configure a `ConsoleOptionParser` +- Shells no longer have direct access to `ShellDispatcher`. You should use + the `ConsoleInput`, and `ConsoleOutput` objects instead. If you need to + dispatch other shells, see the section on 'Invoking other shells from your + shell'. + +### Backwards incompatible ShellDispatcher API changes + +- `ShellDispatcher` no longer has stdout, stdin, stderr file handles. +- `ShellDispatcher::$shell` has been removed. +- `ShellDispatcher::$shellClass` has been removed. +- `ShellDispatcher::$shellName` has been removed. +- `ShellDispatcher::$shellCommand` has been removed. +- `ShellDispatcher::$shellPaths` has been removed, use + `App::path('shells');` instead. +- `ShellDispatcher` no longer uses 'help' as a magic method that has special + status. Instead use the `--help/-h` options, and an option parser. + +### Backwards incompatible Shell Changes + +- Bake's ControllerTask no longer takes `public` and `admin` as passed + arguments. They are now options, indicated like `--admin` and `--public`. + +It's recommended that you use the help on shells you use to see what if any +parameters have changed. It's also recommended that you read the console new +features for more information on new APIs that are available. + +## Debugging + +The `debug()` function now defaults to outputting HTML safe strings. This is +disabled if being used in the console. The `$showHtml` option for `debug()` +can be set to false to disable HTML-safe output from debug. + +## ConnectionManager + +`ConnectionManager::enumConnectionObjects()` will now return the current +configuration for each connection created, instead of an array with filename, +class name and plugin, which wasn't really useful. + +When defining database connections you will need to make some changes to the way +configs were defined in the past. Basically in the database configuration class, +the key "driver" is not accepted anymore, only "datasource", in order to make it +more consistent. Also, as the datasources have been moved to packages you will +need to pass the package they are located in. Example: + +``` php +public $default = array( + 'datasource' => 'Database/Mysql', + 'persistent' => false, + 'host' => 'localhost', + 'login' => 'root', + 'password' => 'root', + 'database' => 'cake', +); +``` diff --git a/docs/en/appendices/2-1-migration-guide.md b/docs/en/appendices/2-1-migration-guide.md new file mode 100644 index 0000000000..f5dc30ea6e --- /dev/null +++ b/docs/en/appendices/2-1-migration-guide.md @@ -0,0 +1,320 @@ +# 2.1 Migration Guide + +CakePHP 2.1 is a fully API compatible upgrade from 2.0. This page outlines the +changes and improvements made for 2.1. + +## AppController, AppHelper, AppModel and AppShell + +These classes are now required to be part of the app directory, as they were +removed from the CakePHP core. If you do not already have these classes, you +can use the following while upgrading: + +``` php +// app/View/Helper/AppHelper.php +App::uses('Helper', 'View'); +class AppHelper extends Helper { +} + +// app/Model/AppModel.php +App::uses('Model', 'Model'); +class AppModel extends Model { +} + +// app/Controller/AppController.php +App::uses('Controller', 'Controller'); +class AppController extends Controller { +} + +// app/Console/Command/AppShell.php +App::uses('Shell', 'Console'); +class AppShell extends Shell { +} +``` + +If your application already has these files/classes you don't need to do +anything. +Additionally if you were using the core PagesController, you would need to copy +this to your app/Controller directory as well. + +## .htaccess files + +The default `.htaccess` files have changed, you should remember to update them +or update your webservers URL re-writing scheme to match the changes done in +`.htaccess` + +## Models + +- The `beforeDelete` callback will be fired before behaviors beforeDelete callbacks. + This makes it consistent with the rest of the events triggered in the model layer. +- `Model::find('threaded')` now accepts `$options['parent']` if using other field + then `parent_id`. Also if the model has TreeBehavior attached and set up with other + parent field, the threaded find will by default use that. +- Parameters for queries using prepared statements will now be part of the SQL + dump. +- Validation arrays can now be more specific with when a field is required. + The `required` key now accepts `create` and `update`. These values will + make a field required when creating or updating. +- Model now has a `schemaName` property. If your application switches + datasources by modifying `Model::$useDbConfig` you should also + modify `schemaName` or use `Model::setDataSource()` method which + handles this for you. + +### CakeSession + +::: info Changed in version 2.1.1 +CakeSession no longer sets the P3P header, as this is the responsibility of your application. +::: + +## Behaviors + +### TranslateBehavior + +- `I18nModel` has been moved into a separate file. + +## Exceptions + +The default exception rendering now includes more detailed stack traces +including file excerpts and argument dumps for all functions in the stack. + +## Utility + +### Debugger + +- `Debugger::getType()` has been added. It can be used to get the type of + variables. +- `Debugger::exportVar()` has been modified to create more readable + and useful output. + +### debug() + +debug() now uses `Debugger` internally. This makes it consistent +with Debugger, and takes advantage of improvements made there. + +### Set + +- `Set::nest()` has been added. It takes in a flat array and returns a nested array + +### File + +- `File::info()` includes filesize & mimetype information. +- `File::mime()` was added. + +### Cache + +- `CacheEngine` has been moved into a separate file. + +### Configure + +- `ConfigReaderInterface` has been moved into a separate file. + +### App + +- `App::build()` now has the ability to register new packages using + `App::REGISTER`. See [App Build Register](../core-utility-libraries/app#app-build-register) for more information. +- Classes that could not be found on configured paths will be searched inside + `APP` as a fallback path. This makes autoloading nested directories in + `app/Vendor` easier. + +## Console + +### Test Shell + +A new TestShell has been added. It reduces the typing required to run unit +tests, and offers a file path based UI: + + ./Console/cake test app Model/Post + ./Console/cake test app Controller/PostsController + ./Console/cake test Plugin View/Helper/MyHelper + +The old testsuite shell and its syntax are still available. + +### General + +- Generated files no longer contain timestamps with the generation datetime. + +## Routing + +### Router + +- Routes can now use a special `/**` syntax to include all trailing arguments + as a single passed argument. See the section on [Connecting Routes](../development/routing#connecting-routes) for + more information. +- `Router::resourceMap()` was added. +- `Router::defaultRouteClass()` was added. This method allows you to + set the default route class used for all future routes that are connected. + +## Network + +### CakeRequest + +- Added `is('requested')` and `isRequested()` for detecting requestAction. + +### CakeResponse + +- Added `CakeResponse::cookie()` for setting cookies. +- Added a number of methods for [Cake Response Caching](../controllers/request-response#cake-response-caching) + +## Controller + +### Controller + +- `Controller::$uses` was modified the default value is now `true` + instead of false. Additionally different values are handled slightly + differently, but will behave the same in most cases. + + > - `true` Will load the default model and merge with AppController. + > - An array will load those models and merge with AppController. + > - An empty array will not load any models other than those declared in the + > base class. + > - `false` will not load any models, and will not merge with the base class + > either. + +## Components + +### AuthComponent + +- `AuthComponent::allow()` no longer accepts `allow('*')` as a wildcard + for all actions. Just use `allow()`. This unifies the API between allow() + and deny(). +- `recursive` option was added to all authentication adapters. Allows you to + more easily control the associations stored in the session. + +### AclComponent + +- `AclComponent` no longer lowercases and inflects the class name used for + `Acl.classname`. Instead it uses the provided value as is. +- Acl backend implementations should now be put in `Controller/Component/Acl`. +- Acl implementations should be moved into the Component/Acl directory from + Component. For example if your Acl class was called `CustomAclComponent`, + and was in `Controller/Component/CustomAclComponent.php`. + It should be moved into `Controller/Component/Acl/CustomAcl.php`, and be + named `CustomAcl`. +- `DbAcl` has been moved into a separate file. +- `IniAcl` has been moved into a separate file. +- `AclInterface` has been moved into a separate file. + +## Helpers + +### TextHelper + +- `TextHelper::autoLink()`, `TextHelper::autoLinkUrls()`, + `TextHelper::autoLinkEmails()` now HTML escape their input by + default. You can control this with the `escape` option. + +### HtmlHelper + +- `HtmlHelper::script()` had a `block` option added. +- `HtmlHelper::scriptBlock()` had a `block` option added. +- `HtmlHelper::css()` had a `block` option added. +- `HtmlHelper::meta()` had a `block` option added. +- The `$startText` parameter of `HtmlHelper::getCrumbs()` can now be + an array. This gives more control and flexibility over the first crumb link. +- `HtmlHelper::docType()` now defaults to HTML5. +- `HtmlHelper::image()` now has a `fullBase` option. +- `HtmlHelper::media()` has been added. You can use this method to + create HTML5 audio/video elements. +- `plugin syntax` support has been added for + `HtmlHelper::script()`, `HtmlHelper::css()`, `HtmlHelper::image()`. + You can now easily link to plugin assets using `Plugin.asset`. +- `HtmlHelper::getCrumbList()` had the `$startText` parameter added. + +## View + +- `View::$output` is deprecated. + +- `$content_for_layout` is deprecated. Use `$this->fetch('content');` + instead. + +- `$scripts_for_layout` is deprecated. Use the following instead: + + ``` php + echo $this->fetch('meta'); + echo $this->fetch('css'); + echo $this->fetch('script'); + ``` + + `$scripts_for_layout` is still available, but the [view blocks](../views#view-blocks) API + gives a more extensible & flexible replacement. + +- The `Plugin.view` syntax is now available everywhere. You can use this + syntax anywhere you reference the name of a view, layout or element. + +- The `$options['plugin']` option for `~View::element()` is + deprecated. You should use `Plugin.element_name` instead. + +### Content type views + +Two new view classes have been added to CakePHP. A new `JsonView` +and `XmlView` allow you to easily generate XML and JSON views. You +can learn more about these classes in the section on +[JSON and XML views](../views/json-and-xml-views) + +### Extending views + +`View` has a new method allowing you to wrap or 'extend' a +view/element/layout with another file. See the section on +[Extending Views](../views#extending-views) for more information on this feature. + +### Themes + +The `ThemeView` class is deprecated in favor of the `View` class. Simply +setting `$this->theme = 'MyTheme'` will enable theme support, and all custom +View classes which extend from `ThemeView` should extend `View`. + +### View blocks + +View blocks are a flexible way to create slots or blocks in your views. Blocks +replace `$scripts_for_layout` with a more robust and flexible API. See the +section on [View Blocks](../views#view-blocks) for more information. + +## Helpers + +### New callbacks + +Two new callbacks have been added to Helpers. +`Helper::beforeRenderFile()` and `Helper::afterRenderFile()` +these new callbacks are fired before/after every view fragment is rendered. +This includes elements, layouts and views. + +### CacheHelper + +- `` tags now work inside elements correctly. + +### FormHelper + +- FormHelper now omits disabled fields from the secured fields hash. This makes + working with `SecurityComponent` and disabled inputs easier. +- The `between` option when used in conjunction with radio inputs, now behaves + differently. The `between` value is now placed between the legend and first + input elements. +- The `hiddenField` option with checkbox inputs can now be set to a specific + value such as 'N' rather than just 0. +- The `for` attribute for date + time inputs now reflects the first generated + input. This may result in the for attribute changing for generated datetime + inputs. +- The `type` attribute for `FormHelper::button()` can be removed now. It still + defaults to 'submit'. +- `FormHelper::radio()` now allows you to disable all options. + You can do this by setting either `'disabled' => true` or `'disabled' => 'disabled'` + in the `$attributes` array. + +### PaginatorHelper + +- `PaginatorHelper::numbers()` now has a `currentClass` option. + +## Testing + +- Web test runner now displays the PHPUnit version number. +- Web test runner now defaults to displaying app tests. +- Fixtures can be created in different datasources other than \$test. +- Models loaded using the ClassRegistry and using another datasource will get + their datasource name prepended with `test_` (e.g datasource master will + try to use test_master in the testsuite) +- Test cases are generated with class specific setup methods. + +## Events + +- A new generic events system has been built and it replaced the way callbacks + were dispatched. This should not represent any change to your code. +- You can dispatch your own events and attach callbacks to them at will, useful + for inter-plugin communication and easier decoupling of your classes. diff --git a/docs/en/appendices/2-10-migration-guide.md b/docs/en/appendices/2-10-migration-guide.md new file mode 100644 index 0000000000..fb7f63f7f7 --- /dev/null +++ b/docs/en/appendices/2-10-migration-guide.md @@ -0,0 +1,54 @@ +# 2.10 Migration Guide + +CakePHP 2.10 is a fully API compatible upgrade from 2.9. This page outlines +the changes and improvements made in 2.10. + +## Console + +- Using undefined CLI options will now result in an error. This behavior has + been backported from 3.x + +## Core + +- The `CONFIG` constant was added. This constant defaults to `app/Config`, + and is intended to increase forwards compatibility with 3.x + +## Model + +- New internal data types were added for `smallinteger` and `tinyinteger`. + Existing `SMALLINT` and `TINYINT` columns will now be reflected as these + new internal data types. `TINYINT(1)` columns will continue to be treated as + boolean columns in MySQL. +- `Model::find()` now supports `having` and `lock` options that enable you + to add `HAVING` and `FOR UPDATE` locking clauses to your find operations. +- `TranslateBehavior` now supports loading translations with LEFT JOIN. Use + the `joinType` option to use this feature. + +## Components + +- `SecurityComponent` now emits more verbose error messages when form + tampering or CSRF protection fails in debug mode. This feature was backported + from 3.x +- `SecurityComponent` will blackhole post requests that have no request data + now. This change helps protect actions that create records using database + defaults alone. +- `FlashComponent` now stacks messages of the same type. This is a feature + backport from 3.x. To disable this behavior, add `'clear' => true` to the + configuration for FlashComponent. +- `PaginatorComponent` now supports multiple paginators through the + `queryScope` option. Using this option when paginating data will force + PaginatorComponent to read from scoped query parameters instead of the root + query string data. + +## Helpers + +- `HtmlHelper::image()` now supports the `base64` option. This option will + read local image files and create base64 data URIs. +- `HtmlHelper::addCrumb()` had the `prepend` option added. This lets you + prepend a breadcrumb instead of appending to the list. +- `FormHelper` creates 'numeric' inputs for `smallinteger` and + `tinyinteger` types. + +## Routing + +- `Router::reverseToArray()` was added. diff --git a/docs/en/appendices/2-2-migration-guide.md b/docs/en/appendices/2-2-migration-guide.md new file mode 100644 index 0000000000..a1c73e656d --- /dev/null +++ b/docs/en/appendices/2-2-migration-guide.md @@ -0,0 +1,281 @@ +# 2.2 Migration Guide + +CakePHP 2.2 is a fully API compatible upgrade from 2.0/2.1. This page outlines the +changes and improvements made for 2.2. + + + +## Required steps to upgrade + +When upgrading to CakePHP 2.2 its important to add a few new configuration +values to `app/Config/bootstrap.php`. Adding these will ensure consistent +behavior with 2.1.x: + +``` php +// Enable the Dispatcher filters for plugin assets, and +// CacheHelper. +Configure::write('Dispatcher.filters', array( + 'AssetDispatcher', + 'CacheDispatcher' +)); + +// Add logging configuration. +CakeLog::config('debug', array( + 'engine' => 'FileLog', + 'types' => array('notice', 'info', 'debug'), + 'file' => 'debug', +)); +CakeLog::config('error', array( + 'engine' => 'FileLog', + 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'), + 'file' => 'error', +)); +``` + +You will also need to modify `app/Config/core.php`. Change the value of +`LOG_ERROR` to `LOG_ERR`: + +``` text +define('LOG_ERROR', LOG_ERR); +``` + +When using `Model::validateAssociated()` or `Model::saveAssociated()` and +primary model validation fails, the validation errors of associated models are no longer wiped out. +`Model::$validationErrors` will now always show all the errors. +You might need to update your test cases to reflect this change. + +## Console + +### I18N extract shell + +- An option was added to overwrite existing POT files by default: + + ./Console/cake i18n extract --overwrite + +## Models + +- `Model::find('count')` will now call the custom find methods with + `$state = 'before'` and `$queryData['operation'] = 'count'`. + In many cases custom finds already return correct counts for pagination, + but `'operation'` key allows more flexibility to build other queries, + or drop joins which are required for the custom finder itself. + As the pagination of custom find methods never worked quite well it required + workarounds for this in the model level, which are now no longer needed. +- `Model::find('first')` will now return an empty array when no records are found. + +## Datasources + +- Dbo datasources now supports real nested transactions. If you need to use this + feature in your application, enable it using + `ConnectionManager::getDataSource('default')->useNestedTransactions = true;` + +## Testing + +- The webrunner now includes links to re-run a test with debug output. +- Generated test cases for Controller now subclass + `ControllerTestCase`. + +## Error Handling + +- When repeat exceptions, or exception are raised when rendering error pages, + the new `error` layout will be used. It's recommended to not use additional + helpers in this layout as its intended for development level errors only. This + fixes issues with fatal errors in rendering error pages due to helper usage in + the `default` layout. +- It is important to copy the `app/View/Layouts/error.ctp` into your app + directory. Failing to do so will make error page rendering fail. +- You can now configure application specific console error handling. By setting + `Error.consoleHandler`, and `Exception.consoleHandler` you can define the + callback that will handle errors/exceptions raised in console applications. +- The handler configured in `Error.handler` and `Error.consoleHandler` will + receive fatal error codes (ie. `E_ERROR`, `E_PARSE`, `E_USER_ERROR`). + +### Exceptions + +- The `NotImplementedException` was added. + +## Core + +### Configure + +- `Configure::dump()` was added. It is used to persist configuration + data in durable storage like files. Both `PhpReader` and + `IniReader` work with it. +- A new config parameter 'Config.timezone' is available in which you can set + users' timezone string. eg. You can do `Configure::write('Config.timezone', 'Europe/Paris')`. If a method of `CakeTime` class is called with + `$timezone` parameter as null and 'Config.timezone' is set, then the value + of 'Config.timezone' will be used. This feature allows you to set users' + timezone just once instead of passing it each time in function calls. + +## Controller + +### AuthComponent + +- The options for adapters defined in `AuthComponent::$authenticate` + now accepts a `contain` option. This is used to set containable options for + when user records are loaded. + +### CookieComponent + +- You can now encrypt cookie values with the rijndael cipher. This requires + the [mcrypt](https://www.php.net/mcrypt) extension to be installed. Using + rijndael gives cookie values actual encryption, and is recommended in place of + the XOR cipher available in previous releases. The XOR cipher is still the + default cipher scheme to maintain compatibility with previous releases. You + can read more in the `Security::rijndael()` documentation. + +## Pagination + +- Paginating custom finders will now return correct counts, see Model changes + for more info. + +## Network + +### CakeEmail + +- `CakeEmail::charset()` and `CakeEmail::headerCharset()` + were added. +- Legacy Japanese encodings are now handled correctly. `ISO-2202-JP` is used + when the encoding is `ISO-2202-JP-MS` which works around a number of issues + in mail clients when dealing with the CP932 and Shift_JIS encodings. +- `CakeEmail::theme()` was added. +- `CakeEmail::domain()` was added. You can use this method to set the + domain name used when sending email from a CLI script or if you want to + control the hostname used to send email. +- You can now define `theme` and `helpers` in your EmailConfig class. + +### CakeRequest + +- CakeRequest will now automatically decode + `application/x-www-form-urlencoded` request bodies on `PUT` and `DELETE` + requests. This data will be available as `$this->data` just like POST data + is. + +## Utility + +### Set + +- The `Set` class is now deprecated, and replaced by the `Hash` class. + Set will not be removed until 3.0. +- `Set::expand()` was added. + +### Hash + +The `Hash` class was added in 2.2. It replaced Set providing a more +consistent, reliable and performant API to doing many of the same tasks Set +does. See the [Hash](../core-utility-libraries/hash) page for more detail. + +### CakeTime + +- The `$userOffset` parameter has been replaced with `$timezone` parameter + in all relevant functions. So instead of numeric offset you can now pass in a + timezone string or DateTimeZone object. Passing numeric offsets for + `$timezone` parameter is still possible for backwards compatibility. +- `CakeTime::timeAgoInWords()` had the `accuracy` option added. + This option allows you to specify how accurate formatted times should be. +- New methods added: + - `CakeTime::toServer()` + - `CakeTime::timezone()` + - `CakeTime::listTimezones()` +- The `$dateString` parameter in all methods now accepts a DateTime object. + +## Helpers + +### FormHelper + +- FormHelper now better handles adding required classes to inputs. It now + honors the `on` key. +- `FormHelper::radio()` now supports an `empty` which works similar + to the empty option on `select()`. +- Added `FormHelper::inputDefaults()` to set common properties for + each of the inputs generated by the helper + +### TimeHelper + +- Since 2.1, TimeHelper uses the CakeTime class for all its relevant methods. + The `$userOffset` parameter has been replaced with `$timezone` parameter. +- `TimeHelper::timeAgoInWords()` has the `element` option added. + This allows you to specify an HTML element to wrap the formatted time. + +### HtmlHelper + +- `HtmlHelper::tableHeaders()` now supports setting attributes per + table cell. + +## Routing + +### Dispatcher + +- Event listeners can now be attached to the dispatcher calls, those will have + the ability to change the request information or the response before it is + sent to the client. Check the full documentation for this new features in + [Dispatcher Filters](../development/dispatch-filters) +- With the addition of [Dispatcher Filters](../development/dispatch-filters) you'll need to + update `app/Config/bootstrap.php`. See + [Required Steps To Upgrade 2 2](#required-steps-to-upgrade-2-2). + +### Router + +- `Router::setExtensions()` has been added. With the new method you can + now add more extensions to be parsed, for example within a plugin routes file. + +## Cache + +### Redis Engine + +A new caching engine was added using the [phpredis extension](https://github.com/phpredis/phpredis) it is configured similarly to the +Memcache engine. + +### Cache groups + +It is now possible to tag or label cache keys under groups. This makes it +simpler to mass-delete cache entries associated to the same label. Groups are +declared at configuration time when creating the cache engine: + +``` php +Cache::config(array( + 'engine' => 'Redis', + ... + 'groups' => array('post', 'comment', 'user') +)); +``` + +You can have as many groups as you like, but keep in mind they cannot be +dynamically modified. + +The `Cache::clearGroup()` class method was added. It takes the group +name and deletes all entries labeled with the same string. + +## Log + +Changes in `CakeLog` now require, some additional configuration in +your `app/Config/bootstrap.php`. See [Required Steps To Upgrade 2 2](#required-steps-to-upgrade-2-2), +and [Logging](../core-libraries/logging). + +- The `CakeLog` class now accepts the same log levels as defined in + [RFC 5424](https://tools.ietf.org/html/rfc5424). Several convenience + methods have also been added: + - `CakeLog::emergency($message, $scope = array())` + - `CakeLog::alert($message, $scope = array())` + - `CakeLog::critical($message, $scope = array())` + - `CakeLog::error($message, $scope = array())` + - `CakeLog::warning($message, $scope = array())` + - `CakeLog::notice($message, $scope = array())` + - `CakeLog::info($message, $scope = array())` + - `CakeLog::debug($message, $scope = array())` +- A third argument `$scope` has been added to `CakeLog::write`. + See [Logging Scopes](../core-libraries/logging#logging-scopes). +- A new log engine: `ConsoleLog` has been added. + +## Model Validation + +- A new object `ModelValidator` was added to delegate the work of validating + model data, it should be transparent to the application and fully backwards + compatible. It also exposes a rich API to add, modify and remove validation + rules. Check docs for this object in [Data Validation](../models/data-validation). +- Custom validation functions in your models need to have "public" visibility + so that they are accessible by `ModelValidator`. +- New validation rules added: + - `Validation::naturalNumber()` + - `Validation::mimeType()` + - `Validation::uploadError()` diff --git a/docs/en/appendices/2-3-migration-guide.md b/docs/en/appendices/2-3-migration-guide.md new file mode 100644 index 0000000000..01c1abaf92 --- /dev/null +++ b/docs/en/appendices/2-3-migration-guide.md @@ -0,0 +1,272 @@ +# 2.3 Migration Guide + +CakePHP 2.3 is a fully API compatible upgrade from 2.2. This page outlines +the changes and improvements made in 2.3. + +## Constants + +An application can now easily define `CACHE` and `LOGS`, +as they are conditionally defined by CakePHP now. + +## Caching + +- FileEngine is always the default cache engine. In the past a number of people + had difficulty setting up and deploying APC correctly both in CLI + web. + Using files should make setting up CakePHP simpler for new developers. +- Configure::write('Cache.viewPrefix', 'YOURPREFIX'); has been added to core.php + to allow multiple domains/languages per setup. + +## Component + +### AuthComponent + +- A new property `AuthComponent::$unauthorizedRedirect` has been added. + - For default `true` value user is redirected to referrer URL upon authorization failure. + - If set to a string or array user is redirected to that URL. + - If set to false a ForbiddenException exception is thrown instead of redirecting. +- A new authenticate adapter has been added to support blowfish/bcrypt hashed + passwords. You can now use `Blowfish` in your `$authenticate` array to + allow bcrypt passwords to be used. +- `AuthComponent::redirect()` has been deprecated. + Use `AuthComponent::redirectUrl()` instead. + +### PaginatorComponent + +- PaginatorComponent now supports the `findType` option. This can be used to + specify what find method you want used for pagination. This is a bit easier + to manage and set than the 0'th index. +- PaginatorComponent now throws a NotFoundException when trying to access a page + which is out of range (i.e. requested page is greater than total page count). + +### SecurityComponent + +- SecurityComponent now supports the `unlockedActions` option. This can be used to + disable all security checks for any actions listed in this option. + +### RequestHandlerComponent + +- `RequestHandlerComponent::viewClassMap()` has been added, which is used to map a type + to view class name. You can add `$settings['viewClassMap']` for automatically setting + the correct viewClass based on extension/content type. + +### CookieComponent + +- `CookieComponent::check()` was added. This method works the same as + `CakeSession::check()` does. + +## Console + +- The `server` shell was added. You can use this to start the PHP5.4 + webserver for your CakePHP application. +- Baking a new project now sets the application's cache prefix to the name of + the application. + +## I18n + +### L10n + +- `nld` is now the default locale for Dutch as specified by ISO 639-3 and `dut` its alias. + The locale folders have to be adjusted accordingly (from /Locale/dut/ to /Locale/nld/). +- Albanian is now `sqi`, Basque is now `eus`, Chinese is now `zho`, Tibetan is now `bod`, + Czech is now `ces`, Farsi is now `fas`, French is now `fra`, Icelandic is now `isl`, + Macedonian is now `mkd`, Malaysian is now `msa`, Romanian is now `ron`, Serbian is now `srp` + and Slovak is now `slk`. The corresponding locale folders have to be adjusted, as well. + +## Core + +### CakePlugin + +- `CakePlugin::load()` can now take a new `ignoreMissing` option. Setting it to true will + prevent file include errors when you try to load routes or bootstrap but they don't exist for a plugin. + So essentially you can now use the following statement which will load all plugins and their routes and + bootstrap for whatever plugin it can find:: + `CakePlugin::loadAll(array(array('routes' => true, 'bootstrap' => true, 'ignoreMissing' => true)))` + +### Configure + +- `Configure::check()` was added. This method works the same as + `CakeSession::check()` does. +- `ConfigReaderInterface::dump()` was added. Please ensure any custom readers you have now + implement a `dump()` method. +- The `$key` parameter of `IniReader::dump()` now supports keys like PluginName.keyname + similar to `PhpReader::dump()`. + +## Error + +### Exceptions + +- CakeBaseException was added, which all core Exceptions now extend. The base exception + class also introduces the `responseHeader()` method which can be called on created Exception instances + to add headers for the response, as Exceptions don't reuse any response instance. + +## Model + +- Support for the biginteger type was added to all core datasources, and + fixtures. +- Support for `FULLTEXT` indexes was added for the MySQL driver. + +### Models + +- `Model::find('list')` now sets the `recursive` based on the max + containment depth or recursive value. When list is used with + ContainableBehavior. +- `Model::find('first')` will now return an empty array when no records are found. + +### Validation + +- Missing validation methods will **always** trigger errors now instead of + only in development mode. + +## Network + +### SmtpTransport + +- TLS/SSL support was added for SMTP connections. + +### CakeRequest + +- `CakeRequest::onlyAllow()` was added. +- `CakeRequest::query()` was added. + +### CakeResponse + +- `CakeResponse::file()` was added. +- The content types application/javascript, application/xml, + application/rss+xml now also send the application charset. + +### CakeEmail + +- The `contentDisposition` option was added to + `CakeEmail::attachments()`. This allows you to disable the + Content-Disposition header added to attached files. + +### HttpSocket + +- `HttpSocket` now verifies SSL certificates by default. If you are + using self-signed certificates or connecting through proxies you may need to + use some of the new options to augment this behavior. See + [Http Socket Ssl Options](../core-utility-libraries/httpsocket#http-socket-ssl-options) for more information. +- `HttpResponse` was renamed to `HttpSocketResponse`. This + avoids a common issue with the HTTP PECL extension. There is an + `HttpResponse` class provided as well for compatibility reasons. + +## Routing + +### Router + +- Support for `tel:`, `sms:` were added to `Router::url()`. + +## View + +- MediaView is deprecated, and you can use new features in + `CakeResponse` to achieve the same results. +- Serialization in Json and Xml views has been moved to `_serialize()` +- beforeRender and afterRender callbacks are now being called in Json and Xml + views when using view templates. +- `View::fetch()` now has a `$default` argument. This argument can + be used to provide a default value should a block be empty. +- `View::prepend()` has been added to allow prepending content to + existing block. +- `XmlView` now uses the `_rootNode` view variable to customize the + top level XML node. +- `View::elementExists()` was added. You can use this method to check + if elements exist before using them. +- `View::element()` had the `ignoreMissing` option added. You can + use this to suppress the errors triggered by missing view elements. +- `View::startIfEmpty()` was added. + +### Layout + +- The doctype for layout files in the app folder and the bake templates in the + cake package has been changed from XHTML to HTML5. + +## Helpers + +- New property `Helper::$settings` has been added for your helper setting. The + `$settings` parameter of `Helper::__construct()` is merged with + `Helper::$settings`. + +### FormHelper + +- `FormHelper::select()` now accepts a list of values in the disabled + attribute. Combined with `'multiple' => 'checkbox'`, this allows you to + provide a list of values you want disabled. +- `FormHelper::postLink()` now accepts a `method` key. This allows + you to create link forms using HTTP methods other than POST. +- When creating inputs with `FormHelper::input()` you can now set the + `errorMessage` option to false. This will disable the error message display, + but leave the error class names intact. +- The FormHelper now also adds the HTML5 `required` attribute to your input + elements based on validation rules for a field. If you have a "Cancel" button + in your form which submits the form then you should add `'formnovalidate' => true` + to your button options to prevent the triggering of validation in HTML. You + can also prevent the validation triggering for the whole form by adding + `'novalidate' => true` in your FormHelper::create() options. +- `FormHelper::input()` now generates input elements of type `tel` + and `email` based on field names if `type` option is not specified. + +### HtmlHelper + +- `HtmlHelper::getCrumbList()` now has the `separator`, + `firstClass` and `lastClass` options. These allow you to better control + the HTML this method generates. + +### TextHelper + +- `TextHelper::tail()` was added to truncate text starting from the end. +- ending in `TextHelper::truncate()` is deprecated in favor of ellipsis + +### PaginatorHelper + +- `PaginatorHelper::numbers()` now has a new option `currentTag` to + allow specifying extra tag for wrapping current page number. +- For methods: `PaginatorHelper::prev()` and `PaginatorHelper::next()` it + is now possible to set the `tag` option to `false` to disable the wrapper. + Also a new option disabledTag has been added for these two methods. + +## Testing + +- A core fixture for the default `cake_sessions` table was added. You can use + it by adding `core.cake_sessions` to your fixture list. +- `CakeTestCase::getMockForModel()` was added. This simplifies getting + mock objects for models. + +## Utility + +### CakeNumber + +- `CakeNumber::fromReadableSize()` was added. +- `CakeNumber::formatDelta()` was added. +- `CakeNumber::defaultCurrency()` was added. + +### Folder + +- `Folder::copy()` and `Folder::move()` now support the + ability to merge the target and source directories in addition to + skip/overwrite. + +### String + +- `String::tail()` was added to truncate text starting from the end. +- ending in `String::truncate()` is deprecated in favor of ellipsis + +### Debugger + +- `Debugger::exportVar()` now outputs private and protected properties + in PHP \>= 5.3.0. + +### Security + +- Support for [bcrypt](https://codahale.com/how-to-safely-store-a-password/) + was added. See the `Security::hash()` documentation for more + information on how to use bcrypt. + +### Validation + +- `Validation::fileSize()` was added. + +### ObjectCollection + +- `ObjectCollection::attached()` was deprecated in favor of the new + method `ObjectCollection::loaded()`. This unifies the access to the + ObjectCollection as load()/unload() already replaced attach()/detach(). diff --git a/docs/en/appendices/2-4-migration-guide.md b/docs/en/appendices/2-4-migration-guide.md new file mode 100644 index 0000000000..540ff1f640 --- /dev/null +++ b/docs/en/appendices/2-4-migration-guide.md @@ -0,0 +1,243 @@ +# 2.4 Migration Guide + +CakePHP 2.4 is a fully API compatible upgrade from 2.3. This page outlines +the changes and improvements made in 2.4. + +## Console + +- Logged notice messages will now be colourized in terminals that support + colours. +- ConsoleShell is now deprecated. + +### SchemaShell + +- `cake schema generate` now supports the `--exclude` parameter. +- The constant `CAKEPHP_SHELL` is now deprecated and will be removed in CakePHP 3.0. + +### BakeShell + +- `cake bake model` now supports baking `$behaviors`. Finding lft, rght and parent_id fields + in your table it will add the Tree behavior, for example. You can also extend the ModelTask to support your own + behaviors to be recognized. +- `cake bake` for views, models, controllers, tests and fixtures now supports a `-f` or `--force` parameter to + force overwriting of files. +- Tasks in core can now be aliased in the same way you would Helpers, Components and Behaviors + +### FixtureTask + +- `cake bake fixture` now supports a `--schema` parameter to allow baking all fixtures with noninteractive "all" + while using schema import. + +## Core + +### Constants + +- Constants `IMAGES_URL`, `JS_URL`, `CSS_URL` have been deprecated and + replaced with config variables `App.imageBaseUrl`, `App.jsBaseUrl`, + `App.cssBaseUrl` respectively. +- Constants `IMAGES`, `JS`, `CSS` have been deprecated. + +### Object + +- `Object::log()` had the `$scope` parameter added. + +## Components + +### AuthComponent + +- AuthComponent now supports proper stateless mode when using 'Basic' or 'Digest' + authenticators. Starting of session can be prevented by setting `AuthComponent::$sessionKey` + to false. Also now when using only 'Basic' or 'Digest' you are no longer + redirected to login page. For more info check the `AuthComponent` page. +- Property `AuthComponent::$authError` can be set to boolean `false` to suppress flash message from being displayed. + +### PasswordHasher + +- Authenticating objects now use new password hasher objects for password hash + generation and checking. See [Hashing Passwords](../core-libraries/components/authentication#hashing-passwords) for more info. + +### DbAcl + +- DbAcl now uses `INNER` joins instead of `LEFT` joins. This improves + performance for some database vendors. + +## Model + +### Models + +- `Model::save()`, `Model::saveField()`, `Model::saveAll()`, + `Model::saveAssociated()`, `Model::saveMany()` + now take a new `counterCache` option. You can set it to false to avoid + updating counter cache values for the particular save operation. +- `Model::clear()` was added. + +### Datasource + +- The Mysql, Postgres, and Sqlserver datasources now support a 'settings' array in the + connection definition. This key =\> value pair will be issued as `SET` commands when the + connection is created. +- The MySQL driver now supports SSL options. + +## View + +### JsonView + +- JSONP support has been added to `JsonView`. +- The `_serialize` key now supports renaming serialized variables. +- When debug \> 0 JSON will be pretty printed. + +### XmlView + +- The `_serialize` key now supports renaming serialized variables. +- When debug \> 0 XML will be pretty printed. + +### HtmlHelper + +- The API for `HtmlHelper::css()` has been been simplified. You can + now provide an array of options as the second argument. When you do, the + `rel` attribute defaults to 'stylesheet'. +- New option `escapeTitle` added to `HtmlHelper::link()` to control + escaping of only link title and not attributes. + +### TextHelper + +- `TextHelper::autoParagraph()` has been added. It allows to + automatically convert text into HTML paragraphs. + +### PaginatorHelper + +- `PaginatorHelper::param()` has been added. +- The first page no longer contains `/page:1` or `?page=1` in the URL. This helps prevent + duplicate content issues where you would need to use canonical or noindex otherwise. + +### FormHelper + +- The `round` option was added to `FormHelper::dateTime()`. Can be set to `up` or `down` + to force rounding in either direction. Defaults to null which rounds half up according to `interval`. + +## Network + +### CakeRequest + +- `CakeRequest::param()` has been added. +- `CakeRequest::is()` has been modified to support an array of types and will return true if the request matches any type. +- `CakeRequest::isAll()` has been added to check that a request matches all the given types. + +### CakeResponse + +- `CakeResponse::location()` has been added to get or set the redirect location header. + +### CakeEmail + +- Logged email messages now have the scope of `email` by default. If you are + not seeing email contents in your logs, be sure to add the `email` scope to + your logging configuration. +- `CakeEmail::emailPattern()` was added. This method can be used to + relax email validation rules. This is useful when dealing with certain + Japanese hosts that allow non-compliant addresses to be used. +- `CakeEmail::attachments()` now allows you to provide the file + contents directly using the `data` key. +- Configuration data is now correctly merged with transport classes. + +### HttpSocket + +- `HttpSocket::patch()` has been added. + +## I18n + +### L10n + +- `ell` is now the default locale for Greek as specified by ISO 639-3 and `gre` its alias. + The locale folders have to be adjusted accordingly (from /Locale/gre/ to /Locale/ell/). +- `fas` is now the default locale for Farsi as specified by ISO 639-3 and `per` its alias. + The locale folders have to be adjusted accordingly (from /Locale/per/ to /Locale/fas/). +- `sme` is now the default locale for Sami as specified by ISO 639-3 and `smi` its alias. + The locale folders have to be adjusted accordingly (from /Locale/smi/ to /Locale/sme/). +- `mkd` replaces `mk` as default locale for Macedonian as specified by ISO 639-3. + The corresponding locale folders have to be adjusted, as well. +- Catalog code `in` has been dropped in favor of `id` (Indonesian), + `e` has been dropped in favor of `el` (Greek), + `n` has been dropped in favor of `nl` (Dutch), + `p` has been dropped in favor of `pl` (Polish), + `sz` has been dropped in favor of `se` (Sami). +- Kazakh has been added with `kaz` as locale and `kk` as catalog code. +- Kalaallisut has been added with `kal` as locale and `kl` as catalog code. +- The constant `DEFAULT_LANGUAGE` has been deprecated in favor of Configure value `Config.language`. + +## Logging + +- Log engines do not need the suffix `Log` anymore in their setup configuration. So for the + FileLog engine it suffices to define `'engine' => 'File'` now. This unifies the way engines + are named in configuration (see Cache engines for example). + Note: If you have a Log engine like `DatabaseLogger` that does not follow the convention to + use a suffix `Log` for your class name you have to adjust your class name to `DatabaseLog`. + You should also avoid class names like `SomeLogLog` which include the suffix twice at the end. + +### FileLog + +- Two new config options `size` and `rotate` have been added for [FileLog](../core-libraries/logging#file-log) engine. +- In debug mode missing directories will now be automatically created to avoid unnecessary errors thrown. + +### SyslogLog + +- The new logging engine [SyslogLog](../core-libraries/logging#syslog-log) was added to stream messages to syslog. + +## Cache + +### FileEngine + +- In debug mode missing directories will now be automatically created to avoid unnecessary errors thrown. + +## Utility + +### General + +- `pr()` no longer outputs HTML when running in CLI mode. + +### Sanitize + +- `Sanitize` class has been deprecated. + +### Validation + +- `Validation::date()` now supports the `y` and `ym` formats. +- The country code of `Validation::phone()` for Canada has been changed from `can` to + `ca` to unify the country codes for validation methods according to ISO 3166 (two letter codes). + +### CakeNumber + +- The currencies `AUD`, `CAD` and `JPY` have been added. +- The symbols for `GBP` and `EUR` are now UTF-8. If you upgrade a non-UTF-8 application, + make sure that you update the static `$_currencies` attribute with the appropriate + HTML entity symbols (`£` and `€`) before you use those currencies. +- The `fractionExponent` option was added to + `CakeNumber::currency()`. + +### CakeTime + +- `CakeTime::isPast()` and `CakeTime::isFuture()` were + added. +- `CakeTime::timeAgoInWords()` has two new options to customize the output strings: + `relativeString` (defaults to `%s ago`) and `absoluteString` (defaults to `on %s`). +- `CakeTime::timeAgoInWords()` uses fuzzy terms when time is below thresholds. + +### Xml + +- New option `pretty` has been added to `Xml::fromArray()` to return nicely formatted Xml + +## Error + +### ErrorHandler + +- New configuration option `skipLog` has been added, to allow skipping certain + Exception types to be logged. `Configure::write('Exception.skipLog', array('NotFoundException', 'ForbiddenException'));` + will avoid these exceptions and the ones extending them to be be logged when + `'Exception.log'` config is `true` + +## Routing + +### Router + +- `Router::fullBaseUrl()` was added together with `App.fullBaseUrl` Configure value. They replace + `FULL_BASE_URL` which is now deprecated. +- `Router::parse()` now parses query string arguments. diff --git a/docs/en/appendices/2-5-migration-guide.md b/docs/en/appendices/2-5-migration-guide.md new file mode 100644 index 0000000000..2f49b4fd6c --- /dev/null +++ b/docs/en/appendices/2-5-migration-guide.md @@ -0,0 +1,220 @@ +# 2.5 Migration Guide + +CakePHP 2.5 is a fully API compatible upgrade from 2.4. This page outlines +the changes and improvements made in 2.5. + +## Cache + +- A new adapter has been added for `Memcached`. This new adapter uses + ext/memcached instead of ext/memcache. It supports improved performance and + shared persistent connections. +- The `Memcache` adapter is now deprecated in favor of `Memcached`. +- `Cache::remember()` was added. +- `Cache::config()` now accepts `database` key when used with + `RedisEngine` in order to use non-default database number. + +## Console + +### SchemaShell + +- The `create` and `update` subcommands now have a `yes` option. The + `yes` option allows you to skip the various interactive questions forcing + a yes reply. + +### CompletionShell + +- The [CompletionShell](../console-and-shells/completion-shell) was added. + It aims to assist in the creation of autocompletion libraries for shell + environments like bash, or zsh. No shell scripts are included in CakePHP, but + the underlying tools are now available. + +## Controller + +### AuthComponent + +- `loggedIn()` is now deprecated and will be removed in 3.0. +- When using `ajaxLogin`, AuthComponent will now return a `403` status code + instead of a `200` when the user is un-authenticated. + +### CookieComponent + +- `CookieComponent` can use the new AES-256 encryption offered by + `Security`. You can enable this by calling + `CookieComponent::type()` with 'aes'. + +### RequestHandlerComponent + +- `RequestHandlerComponent::renderAs()` no longer sets `Controller::$ext`. + It caused problems when using a non default extension for views. + +### AclComponent + +- ACL node lookup failures are now logged directly. The call to + `trigger_error()` has been removed. + +### Scaffold + +- Dynamic Scaffold is now deprecated and will be removed in 3.0. + +## Core + +### App + +- `App::pluginPath()` has been deprecated. `CakePlugin::path()` should be used instead. + +### CakePlugin + +- `CakePlugin::loadAll()` now merges the defaults and plugin specific options as + intuitively expected. See the test cases for details. + +## Event + +### EventManager + +Events bound to the global manager are now fired in priority order with events +bound to a local manager. This can cause listeners to be fired in a different +order than they were in previous releases. Instead of all global listeners being triggered, +and then instance listeners being fired afterwards, the two sets of listeners +are combined into one list of listeners based on their priorities and then fired +as one set. Global listeners of a given priority are still fired before instance +listeners. + +## I18n + +- The `I18n` class has several new constants. These constants allow you + to replace hardcoded integers with readable values. e.g. + `I18n::LC_MESSAGES`. + +## Model + +- Unsigned integers are now supported by datasources that provide them (MySQL). + You can set the `unsigned` option to true in your schema/fixture files to + start using this feature. +- Joins included in queries are now added **after** joins from associations are + added. This makes it easier to join tables that depend on generated + associations. + +## Network + +### CakeEmail + +- Email addresses in CakeEmail are now validated with `filter_var` by default. + This relaxes the email address rules allowing internal email addresses like + `root@localhost` for example. +- You can now specify `layout` key in email config array without having to + specify `template` key. + +### CakeRequest + +- `CakeRequest::addDetector()` now supports `options` which + accepts an array of valid options when creating param based detectors. +- `CakeRequest::onlyAllow()` has been deprecated. As replacement a new method named + `CakeRequest::allowMethod()` has been added with identical functionality. + The new method name is more intuitive and better conveys what the method does. + +### CakeSession + +- Sessions will not be started if they are known to be empty. If the session + cookie cannot be found, a session will not be started until a write operation + is done. + +## Routing + +### Router + +- `Router::mapResources()` accepts `connectOptions` key in the + `$options` argument. See [Custom Rest Routing](../development/rest#custom-rest-routing) for more details. + +## Utility + +### Debugger + +- `Debugger::dump()` and `Debugger::log()` now support a `$depth` + parameter. This new parameter makes it easy to output more deeply nested + object structures. + +### Hash + +- `Hash::insert()` and `Hash::remove()` now support matcher + expressions in their path selectors. + +### File + +- `File::replaceText()` was added. This method allows you to easily + replace text in a file using `str_replace`. + +### Folder + +- `Folder::addPathElement()` now accepts an array for the `$element` + parameter. + +### Security + +- `Security::encrypt()` and `Security::decrypt()` were + added. These methods expose a very simple API to access AES-256 symmetric encryption. + They should be used in favour of the `cipher()` and `rijndael()` methods. + +### Validation + +- The third param for `Validation::inList()` and `Validation::multiple()` has been + modified from \$strict to \$caseInsensitive. \$strict has been dropped as it was working incorrectly + and could easily backfire. + You can now set this param to true for case insensitive comparison. The default is false and + will compare the value and list case sensitive as before. +- `$mimeTypes` parameter of `Validation::mimeType()` can also be a + regex string. Also now when `$mimeTypes` is an array it's values are lowercased. + +## Logging + +### FileLog + +- CakeLog does not auto-configure itself anymore. As a result log files will not be auto-created + anymore if no stream is listening. Please make sure you got at least one default engine set up + if you want to listen to all types and levels. + +## Error + +### ExceptionRenderer + +The ExceptionRenderer now populates the error templates with "code", "message" and "url" variables. +"name" has been deprecated but is still available. This unifies the variables across all error templates. + +## Testing + +- Fixture files can now be placed in sub-directories. You can use fixtures in + subdirectories by including the directory name after the `.`. For example, + app.my_dir/article will load `App/Test/Fixture/my_dir/ArticleFixture`. It + should be noted that the fixture directory will not be inflected or modified + in any way. +- Fixtures can now set `$canUseMemory` to false to disable the memory storage + engine being used in MySQL. + +## View + +### View + +- `$title_for_layout` is deprecated. Use `$this->fetch('title');` and + `$this->assign('title', 'your-page-title');` instead. +- `View::get()` now accepts a second argument to provide a default + value. + +### FormHelper + +- FormHelper will now generate file inputs for `binary` field types now. +- `FormHelper::end()` had a second parameter added. This parameter + lets you pass additional properties to the fields used for securing forms in + conjunction with SecurityComponent. +- `FormHelper::end()` and `FormHelper::secure()` allow you + to pass additional options that are turned into attributes on the generated + hidden inputs. This is useful when you want to use the HTML5 `form` attribute. +- `FormHelper::postLink()` now allows you to buffer the generated form + tag instead of returning it with the link. This helps avoiding nested form tags. + +### PaginationHelper + +- `PaginatorHelper::sort()` now has a `lock` option to create pagination sort links with + the default direction only. + +### ScaffoldView + +- Dynamic Scaffold is now deprecated and will be removed in 3.0. diff --git a/docs/en/appendices/2-6-migration-guide.md b/docs/en/appendices/2-6-migration-guide.md new file mode 100644 index 0000000000..cb018c51c4 --- /dev/null +++ b/docs/en/appendices/2-6-migration-guide.md @@ -0,0 +1,138 @@ +# 2.6 Migration Guide + +CakePHP 2.6 is a fully API compatible upgrade from 2.5. This page outlines +the changes and improvements made in 2.6. + +## Basics.php + +- `stackTrace()` has been added as a convenience wrapper function for `Debugger::trace()`. + It directly echos just as `debug()` does. But only if debug level is on. +- New i18n functions have been added. The new functions allow you to include + message context which allows you disambiguate possibly confusing message + strings. For example 'read' can mean multiple things in English depending on + the context. The new `__x`, `__xn`, `__dx`, `__dxn`, `__dxc`, + `__dxcn`, and `__xc` functions provide access to the new features. + +## Cache + +### RedisEngine + +- The `RedisEngine` now has a default prefix of `Inflector::slug(APP_DIR)`. + +## Console + +### ConsoleOptionParser + +- `ConsoleOptionParser::removeSubcommand()` was added. + +### Shell + +- `overwrite()` has been added to allow generating progress bars or to avoid outputting + too many lines by replacing text that has been already outputted to the screen. + +## Controller + +### AuthComponent + +- `AuthComponent` had the `userFields` option added. +- AuthComponent now triggers an `Auth.afterIdentify` event after a user has + been identified and logged in. The event will contain the logged in user as + data. + +## Behavior + +### AclBehavior + +- `Model::parentNode()` now gets the type (Aro, Aco) passed as first argument: `$model->parentNode($type)`. + +## Datasource + +### Mysql + +- The `RLIKE` wildcard operator has been added to allow regular expression pattern lookups this way. +- Schema migrations with MySQL now support an `after` key when adding + a column. This key allows you to specify which column the new one should be + added after. + +## Model + +### Model + +- `Model::save()` had the `atomic` option back-ported from 3.0. +- `Model::afterFind()` now always uses a consistent format for afterFind(). + When `$primary` is false, the results will always be located under + `$data[0]['ModelName']`. You can set the `useConsistentAfterFind` property + to false on your models to restore the original behavior. + +## Network + +### CakeRequest + +- `CakeRequest::param()` can now read values using [Hash Path Syntax](../core-utility-libraries/hash#hash-path-syntax) + like `data()`. +- `CakeRequest:setInput()` was added. + +### HttpSocket + +- `HttpSocket::head()` was added. +- You can now use the `protocol` option to override the specific protocol to + use when making a request. + +## I18n + +- Configure value `I18n.preferApp` can now be used to control the order of translations. + If set to true it will prefer the app translations over any plugins' ones. + +## Utility + +### CakeTime + +- `CakeTime::timeAgoInWords()` now supports `strftime()` compatible absolute + date formats. This helps make localizing formatted times easier. + +### Hash + +- `Hash::get()` now raises an exception when the path argument is invalid. +- `Hash::nest()` now raises an exception when the nesting operation results in + no data. + +### Validation + +- `Validation::between` has been deprecated, you should use + `Validation::lengthBetween` instead. +- `Validation::ssn` has been deprecated and can be provided as standalone/plugin solution. + +## View + +### JsonView + +- `JsonView` now supports the `_jsonOptions` view variable. + This allows you to configure the bit-mask options used when generating JSON. + +### XmlView + +- `XmlView` now supports the `_xmlOptions` view variable. + This allows you to configure the options used when generating XML. + +## Helper + +### HtmlHelper + +- `HtmlHelper::css()` had the `once` option added. It works the same + as the `once` option for `HtmlHelper::script()`. The default value is + `false` to maintain backwards compatibility. +- The `$confirmMessage` argument of `HtmlHelper::link()` has been + deprecated. You should instead use key `confirm` in `$options` to specify + the message. + +### FormHelper + +- The `$confirmMessage` argument of `FormHelper::postLink()` has been + deprecated. You should instead use key `confirm` in `$options` to specify + the message. +- The `maxlength` attribute will now also be applied to textareas, when the corresponding + DB field is of type varchar, as per HTML specs. + +### PaginatorHelper + +- `PaginatorHelper::meta()` has been added to output the meta-links (rel prev/next) for a paginated result set. diff --git a/docs/en/appendices/2-7-migration-guide.md b/docs/en/appendices/2-7-migration-guide.md new file mode 100644 index 0000000000..61577d71ab --- /dev/null +++ b/docs/en/appendices/2-7-migration-guide.md @@ -0,0 +1,97 @@ +# 2.7 Migration Guide + +CakePHP 2.7 is a fully API compatible upgrade from 2.6. This page outlines +the changes and improvements made in 2.7. + +## Requirements + +The PHP version requirement for CakePHP 2.7 has been bumped up to PHP 5.3.0. + +## Console + +- Plugin shells that share a name with their plugin can now be called without + the plugin prefix. For example `Console/cake MyPlugin.my_plugin` can now + be called with `Console/cake my_plugin`. +- `Shell::param()` was backported from 3.0 into 2.7. This method provides + a notice error free way to read CLI options. + +## Core + +### Configure + +- `Configure::consume()` has been added to read and delete from + Configure in a single step. + +## Datasource + +- SQL datasources will now cast `''` and `null` into `''` when columns are + not nullable and rows are being created or updated. + +### CakeSession + +- `CakeSession::consume()` has been added to read and delete from + session in a single step. +- Argument \$renew has been added to `CakeSession::clear()` to allow + emptying the session without forcing a new id and renewing the session. It + defaults to `true`. + +## Model + +### TreeBehavior + +- New setting level is now available. You can use it to specify field name in + which the depth of tree nodes will be stored. +- New method `TreeBehavior::getLevel()` has been added which fetches depth of + a node. +- The formatting of `TreeBehavior::generateTreeList()` has been extracted into + an own method `TreeBehavior::formatTreeList()`. + +## Network + +### CakeEmail + +- CakeEmail will now use the 'default' config set when creating instances that + do not specify a configuration set to use. For example `$email = new CakeEmail();` will now use the 'default' config set. + +## Utility + +### CakeText + +The class `String` has been renamed to `CakeText`. This resolves some +conflicts around HHVM compatibility as well as possibly PHP7+. There is +a `String` class provided as well for compatibility reasons. + +### Validation + +- `Validation::notEmpty()` has been renamed to `Validation::notBlank()`. + This aims to avoid confusion around the PHP notEmpty() function and that the + validation rule accepts `0` as valid input. + +## Controller + +### SessionComponent + +- `SessionComponent::consume()` has been added to read and delete + from session in a single step. +- `SessionComponent::setFlash()` has been deprecated. You should use + `FlashComponent` instead. + +### RequestHandlerComponent + +- The `text/plain` Accept header is no longer automatically mapped to the + `csv` response type. This is a backport from 3.0 + +## View + +### SessionHelper + +- `SessionHelper::consume()` has been added to read and delete from + session in a single step. +- `SessionHelper::flash()` has been deprecated. You should use + `FlashHelper` instead. + +## TestSuite + +### ControllerTestCase + +- `ControllerTestCase::testAction()` now supports an array as URL. diff --git a/docs/en/appendices/2-8-migration-guide.md b/docs/en/appendices/2-8-migration-guide.md new file mode 100644 index 0000000000..96461c9132 --- /dev/null +++ b/docs/en/appendices/2-8-migration-guide.md @@ -0,0 +1,79 @@ +# 2.8 Migration Guide + +CakePHP 2.8 is a fully API compatible upgrade from 2.7. This page outlines +the changes and improvements made in 2.8. + +## PHP7 Compatibility + +CakePHP 2.8 is compatible with, and tested against PHP7. + +## Deprecations + +- The `action` option in `FormHelper::create()` has been deprecated. This is + a backport from 3.x. + Note that this now makes the `action` key of an array URL consistently + respected for the generation of the DOM ID. + If you used the deprecated key you want to compare the generated ID for the + form before and after. + +## Error Handling + +- When handling fatal errors, CakePHP will now adjust the memory limit by 4MB to + ensure that the error can be logged correctly. You can disable this behavior + by setting `Error.extraFatalErrorMemory` to `0` in your + `Config/core.php`. + +## Cache + +- `Cache::add()` has been added. This method lets you add data to + a cache if the key did not already exist. This method will work atomically in + Memcached, Memcache, APC and Redis. Other cache backends will do non-atomic + operations. + +## CakeTime + +- `CakeTime::listTimezones()` has been changed to accept array in the last + argument. Valid values for the `$options` argument are: `group`, + `abbr`, `before`, and `after`. + +## Shell Helpers Added + +Console applications can now create helper classes that encapsulate re-usable +blocks of output logic. See the [Shell Helpers](../console-and-shells/helpers) section +for more information. + +## I18nShell + +- A new option `no-locations` has been added. When enabled, this option will + disable the generation of location references in your POT files. + +## Hash + +- `Hash::sort()` now supports case-insensitive sorting via the `ignoreCase` + option. + +## Model + +- Magic finders now support custom finder types. For example if your model + implements a `find('published')` finder, you can now use `findPublishedBy` + and `findPublishedByAuthorId` functions through the magic method interface. +- Find conditions can now use `IN` and `NOT IN` operator in conditions. This + allows find expressions to be more forwards compatible with 3.x. + +## Validation + +- `Validation::uploadedFile()` was backported from 3.x. + +## CakeSession + +- The `Session.cacheLimiter` configuration option was added. This option lets + you define the cache control headers used for the session cookie. The default + is `must-revalidate`. + +## View + +### FormHelper + +`'url' => false` is now supported for `FormHelper::create()` to allow form +tags to be created without HTML `action` attribute. This is a backport from +3.x. diff --git a/docs/en/appendices/2-9-migration-guide.md b/docs/en/appendices/2-9-migration-guide.md new file mode 100644 index 0000000000..7401fa5337 --- /dev/null +++ b/docs/en/appendices/2-9-migration-guide.md @@ -0,0 +1,26 @@ +# 2.9 Migration Guide + +CakePHP 2.9 is a fully API compatible upgrade from 2.8. This page outlines +the changes and improvements made in 2.9. + +## PHP7 Compatibility + +CakePHP 2.9 is compatible with, and tested against PHP7. + +## Deprecations + +- The `Object` class has been deprecated and renamed to `CakeObject` due to + `object` becoming a reserved keyword in one of the next PHP7 minors (see + \[RFC\]()). + +## New Features + +- `DboSource::flushQueryCache()` was added to allow more fine-grained control + of query result caching when enabled. +- The log messages created by `ErrorHandler` can now be more easily customized + in subclasses. +- Additional mime-types for 'jsonapi', and 'psd' were added. +- Time & Datetime inputs no longer set a `maxlength` attribute when rendered + as 'text' input types. +- `AuthComponent::user()` now makes the user data available when using + stateless authentication adapters. diff --git a/docs/en/appendices/glossary.md b/docs/en/appendices/glossary.md new file mode 100644 index 0000000000..b947aea119 --- /dev/null +++ b/docs/en/appendices/glossary.md @@ -0,0 +1,92 @@ +# Glossary + +
+ +routing array +An array of attributes that are passed to `Router::url()`. +They typically look like: + +``` text +array('controller' => 'posts', 'action' => 'view', 5) +``` + +Or a more complex example: + +``` text +array( + 'subdomain' => 'dev', + 'plugin' => 'account', + 'prefix' => 'admin', + 'controller' => 'profiles', + 'action' => 'edit', + 10257 + '#' => 'email', + '?' => array( + 'reset' => true, + ), + 'full_base' => true, +) +``` + +HTML attributes +An array of key =\> values that are composed into HTML attributes. For example: + +``` text +// Given +array('class' => 'my-class', 'target' => '_blank') + +// Would generate +class="my-class" target="_blank" +``` + +If an option can be minimized or accepts it's name as the value, then `true` +can be used: + +``` text +// Given +array('checked' => true) + +// Would generate +checked="checked" +``` + +plugin syntax +Plugin syntax refers to the dot separated class name indicating classes +are part of a plugin. E.g. `DebugKit.Toolbar` The plugin is DebugKit, +and the class name is Toolbar. + +dot notation +Dot notation defines an array path, by separating nested levels with `.` +For example: + + Asset.filter.css + +Would point to the following value: + +``` text +array( + 'Asset' => array( + 'filter' => array( + 'css' => 'got me' + ) + ) +) +``` + +CSRF +Cross Site Request Forgery. Prevents replay attacks, double +submissions and forged requests from other domains. + +routes.php +A file in APP/Config that contains routing configuration. +This file is included before each request is processed. +It should connect all the routes your application needs so +requests can be routed to the correct controller + action. + +DRY +Don't repeat yourself. Is a principle of software development aimed at +reducing repetition of information of all kinds. In CakePHP DRY is used +to allow you to code things once and re-use them across your +application. + +
diff --git a/docs/en/appendices/migrating-from-cakephp-1-2-to-1-3.md b/docs/en/appendices/migrating-from-cakephp-1-2-to-1-3.md new file mode 100644 index 0000000000..54a7d4eb70 --- /dev/null +++ b/docs/en/appendices/migrating-from-cakephp-1-2-to-1-3.md @@ -0,0 +1,729 @@ +# Migrating from CakePHP 1.2 to 1.3 + +This guide summarizes many of the changes necessary when migrating +from a 1.2 to 1.3 CakePHP core. Each section contains relevant +information for the modifications made to existing methods as well +as any methods that have been removed/renamed. + +**App File Replacements (important)** + +- webroot/index.php: Must be replaced due to changes in + bootstrapping process. +- config/core.php: Additional settings have been put in place + which are required for PHP 5.3. +- webroot/test.php: Replace if you want to run unit tests. + +## Removed Constants + +The following constants have been removed from CakePHP. If your +application depends on them you must define them in +`app/config/bootstrap.php` + +- `CIPHER_SEED` - It has been replaced with Configure class var + `Security.cipherSeed` which should be changed in + `app/config/core.php` +- `PEAR` +- `INFLECTIONS` +- `VALID_NOT_EMPTY` +- `VALID_EMAIL` +- `VALID_NUMBER` +- `VALID_YEAR` + +## Configuration and application bootstrapping + +**Bootstrapping Additional Paths.** + +In your app/config/bootstrap.php you may have variables like +`$pluginPaths` or `$controllerPaths`. +There is a new way to add those paths. As of 1.3 RC1 the +`$pluginPaths` variables will no longer work. You must use +`App::build()` to modify paths. + +``` php +App::build(array( + 'plugins' => array( + '/full/path/to/plugins/', + '/next/full/path/to/plugins/' + ), + 'models' => array( + '/full/path/to/models/', + '/next/full/path/to/models/' + ), + 'views' => array( + '/full/path/to/views/', + '/next/full/path/to/views/' + ), + 'controllers' => array( + '/full/path/to/controllers/', + '/next/full/path/to/controllers/' + ), + 'datasources' => array( + '/full/path/to/datasources/', + '/next/full/path/to/datasources/' + ), + 'behaviors' => array( + '/full/path/to/behaviors/', + '/next/full/path/to/behaviors/' + ), + 'components' => array( + '/full/path/to/components/', + '/next/full/path/to/components/' + ), + 'helpers' => array( + '/full/path/to/helpers/', + '/next/full/path/to/helpers/' + ), + 'vendors' => array( + '/full/path/to/vendors/', + '/next/full/path/to/vendors/' + ), + 'shells' => array( + '/full/path/to/shells/', + '/next/full/path/to/shells/' + ), + 'locales' => array( + '/full/path/to/locale/', + '/next/full/path/to/locale/' + ), + 'libs' => array( + '/full/path/to/libs/', + '/next/full/path/to/libs/' + ) +)); +``` + +Also changed is the order in which bootstrapping occurs. In the +past `app/config/core.php` was loaded **after** +`app/config/bootstrap.php`. This caused any `App::import()` in +an application bootstrap to be un-cached and considerably slower +than a cached include. In 1.3 core.php is loaded and the core cache +configs are created **before** bootstrap.php is loaded. + +**Loading custom inflections** + +`inflections.php` has been removed, it was an unnecessary file +hit, and the related features have been refactored into a method to +increase their flexibility. You now use `Inflector::rules()` to +load custom inflections: + +``` php +Inflector::rules('singular', array( + 'rules' => array( + '/^(bil)er$/i' => '\1', + '/^(inflec|contribu)tors$/i' => '\1ta' + ), + 'uninflected' => array('singulars'), + 'irregular' => array('spins' => 'spinor') +)); +``` + +Will merge the supplied rules into the infection sets, with the +added rules taking precedence over the core rules. + +## File renames and internal changes + +**Library Renames** + +Core libraries of libs/session.php, libs/socket.php, +libs/model/schema.php and libs/model/behavior.php have been renamed +so that there is a better mapping between filenames and main +classes contained within (as well as dealing with some name-spacing +issues): + +- session.php -\> cake_session.php + - App::import('Core', 'Session') -\> App::import('Core', + 'CakeSession') +- socket.php -\> cake_socket.php + - App::import('Core', 'Socket') -\> App::import('Core', + 'CakeSocket') +- schema.php -\> cake_schema.php + - App::import('Model', 'Schema') -\> App::import('Model', + 'CakeSchema') +- behavior.php -\> model_behavior.php + - App::import('Core', 'Behavior') -\> App::import('Core', + 'ModelBehavior') + +In most cases, the above renaming will not affect userland code. + +**Inheritance from Object** + +The following classes no longer extend Object: + +- Router +- Set +- Inflector +- Cache +- CacheEngine + +If you were using Object methods from these classes, you will need +to not use those methods. + +## Controller & Components + +**Controller** + +- `Controller::set()` no longer changes variables from + `$var_name` to `$varName`. Variables always appear in the view + exactly as you set them. +- `Controller::set('title', $var)` no longer sets + `$title_for_layout` when rendering the layout. + `$title_for_layout` is still populated by default. But if you + want to customize it, use + `$this->set('title_for_layout', $var)`. +- `Controller::$pageTitle` has been removed. Use + `$this->set('title_for_layout', $var);` instead. +- Controller has two new methods `startupProcess` and + `shutdownProcess`. These methods are responsible for handling the + controller startup and shutdown processes. + +**Component** + +- `Component::triggerCallback` has been added. It is a generic + hook into the component callback process. It supplants + `Component::startup()`, `Component::shutdown()` and + `Component::beforeRender()` as the preferred way to trigger + callbacks. + +**CookieComponent** + +- `del` is deprecated use `delete` + +**AclComponent + DbAcl** + +Node reference checks done with paths are now less greedy and will +no longer consume intermediary nodes when doing searches. In the +past given the structure: + + ROOT/ + Users/ + Users/ + edit + +The path `ROOT/Users` would match the last Users node instead of +the first. In 1.3, if you were expecting to get the last node you +would need to use the path `ROOT/Users/Users` + +**RequestHandlerComponent** + +- `getReferrer` is deprecated use `getReferer` + +**SessionComponent & SessionHelper** + +- `del` is deprecated use `delete` + +`SessionComponent::setFlash()` second param used to be used for +setting the layout and accordingly rendered a layout file. This has +been modified to use an element. If you specified custom session +flash layouts in your applications you will need to make the +following changes. + +1. Move the required layout files into app/views/elements +2. Rename the \$content_for_layout variable to \$message +3. Make sure you have `echo $session->flash();` in your layout + +`SessionComponent` and `SessionHelper` are not automatically +loaded. +Both `SessionComponent` and `SessionHelper` are no longer +automatically included without you asking for them. SessionHelper +and SessionComponent now act like every other component and must be +declared like any other helper/component. You should update +`AppController::$components` and `AppController::$helpers` to +include these classes to retain existing behavior: + +``` php +var $components = array('Session', 'Auth', ...); +var $helpers = array('Session', 'Html', 'Form' ...); +``` + +These change were done to make CakePHP more explicit and +declarative in what classes you the application developer want to +use. In the past there was no way to avoid loading the Session +classes without modifying core files. Which is something we want +you to be able to avoid. In addition Session classes were the only +magical component and helper. This change helps unify and normalize +behavior amongst all classes. + +## Library Classes + +**CakeSession** + +- `del` is deprecated use `delete` + +**SessionComponent** + +- `SessionComponent::setFlash()` now uses an *element* instead + of a *layout* as its second parameter. Be sure to move any flash + layouts from app/views/layouts to app/views/elements and change + instances of \$content_for_layout to \$message. + +**Folder** + +- `mkdir` is deprecated use `create` +- `mv` is deprecated use `move` +- `ls` is deprecated use `read` +- `cp` is deprecated use `copy` +- `rm` is deprecated use `delete` + +**Set** + +- `isEqual` is deprecated. Use == or ===. + +**String** + +- `getInstance` is deprecated, call String methods statically. + +**Router** + +`Routing.admin` is deprecated. It provided an inconsistent +behavior with other prefix style routes in that it was treated +differently. Instead you should use `Routing.prefixes`. Prefix +routes in 1.3 do not require additional routes to be declared +manually. All prefix routes will be generated automatically. To +update simply change your core.php: + +``` php +//from: +Configure::write('Routing.admin', 'admin'); + +//to: +Configure::write('Routing.prefixes', array('admin')); +``` + +See the New features guide for more information on using prefix +routes. A small change has also been done to routing params. Routed +params should now only consist of alphanumeric chars, - and \_ or +`/[A-Z0-9-_+]+/`: + +``` php +Router::connect('/:$%@#param/:action/*', array(...)); // BAD +Router::connect('/:can/:anybody/:see/:m-3/*', array(...)); //Acceptable +``` + +For 1.3 the internals of the Router were heavily refactored to +increase performance and reduce code clutter. The side effect of +this is two seldom used features were removed, as they were +problematic and buggy even with the existing code base. First path +segments using full regular expressions was removed. You can no +longer create routes like: + +``` php +Router::connect( + '/([0-9]+)-p-(.*)/', + array('controller' => 'products', 'action' => 'show') +); +``` + +These routes complicated route compilation and impossible to +reverse route. If you need routes like this, it is recommended that +you use route parameters with capture patterns. Next mid-route +greedy star support has been removed. It was previously possible to +use a greedy star in the middle of a route: + +``` php +Router::connect( + '/pages/*/:event', + array('controller' => 'pages', 'action' => 'display'), + array('event' => '[a-z0-9_-]+') +); +``` + +This is no longer supported as mid-route greedy stars behaved +erratically, and complicated route compiling. Outside of these two +edge-case features and the above changes the router behaves exactly +as it did in 1.2 + +Also, people using the 'id' key in array-form URLs will notice that +Router::url() now treats this as a named parameter. If you +previously used this approach for passing the ID parameter to +actions, you will need to rewrite all your \$html-\>link() and +\$this-\>redirect() calls to reflect this change. + +``` php +// old format: +$url = array('controller' => 'posts', 'action' => 'view', 'id' => $id); +// use cases: +Router::url($url); +$html->link($url); +$this->redirect($url); +// 1.2 result: +/posts/view/123 +// 1.3 result: +/posts/view/id:123 +// correct format: +$url = array('controller' => 'posts', 'action' => 'view', $id); +``` + +**Dispatcher** + +`Dispatcher` is no longer capable of setting a controller's +layout/viewPath with request parameters. Control of these +properties should be handled by the Controller, not the Dispatcher. +This feature was also undocumented, and untested. + +**Debugger** + +- `Debugger::checkSessionKey()` has been renamed to + `Debugger::checkSecurityKeys()` +- Calling `Debugger::output("text")` no longer works. Use + `Debugger::output("txt")`. + +**Object** + +- `Object::$_log` has been removed. `CakeLog::write` is now + called statically. See [Logging](../core-libraries/logging) + for more information on changes made to logging. + +**Sanitize** + +- `Sanitize::html()` now actually always returns escaped + strings. In the past using the `$remove` parameter would skip + entity encoding, returning possibly dangerous content. +- `Sanitize::clean()` now has a `remove_html` option. This + will trigger the `strip_tags` feature of `Sanitize::html()`, + and must be used in conjunction with the `encode` parameter. + +**Configure and App** + +- Configure::listObjects() replaced by App::objects() +- Configure::corePaths() replaced by App::core() +- Configure::buildPaths() replaced by App::build() +- Configure no longer manages paths. +- Configure::write('modelPaths', array...) replaced by + App::build(array('models' =\> array...)) +- Configure::read('modelPaths') replaced by App::path('models') +- There is no longer a debug = 3. The controller dumps generated + by this setting often caused memory consumption issues making it an + impractical and unusable setting. The `$cakeDebug` variable has + also been removed from `View::renderLayout` You should remove + this variable reference to avoid errors. +- `Configure::load()` can now load configuration files from + plugins. Use `Configure::load('plugin.file');` to load + configuration files from plugins. Any configuration files in your + application that use `.` in the name should be updated to use + `_` + +**Cache** + +In addition to being able to load CacheEngines from app/libs or +plugins, Cache underwent some refactoring for CakePHP1.3. These +refactorings focused around reducing the number and frequency of +method calls. The end result was a significant performance +improvement with only a few minor API changes which are detailed +below. + +The changes in Cache removed the singletons used for each Engine +type, and instead an engine instance is made for each unique key +created with `Cache::config()`. Since engines are not singletons +anymore, `Cache::engine()` was not needed and was removed. In +addition `Cache::isInitialized()` now checks cache +*configuration names*, not cache *engine names*. You can still use +`Cache::set()` or `Cache::engine()` to modify cache +configurations. Also checkout the +[New features in CakePHP 1.3](../appendices/new-features-in-cakephp-1-3) for +more information on the additional methods added to `Cache`. + +It should be noted that using an app/libs or plugin cache engine +for the default cache config can cause performance issues as the +import that loads these classes will always be uncached. It is +recommended that you either use one of the core cache engines for +your `default` configuration, or manually include the cache +engine class before configuring it. Furthermore any non-core cache +engine configurations should be done in +`app/config/bootstrap.php` for the same reasons detailed above. + +## Model Databases and Datasources + +**Model** + +- `Model::del()` and `Model::remove()` have been removed in + favor of `Model::delete()`, which is now the canonical delete + method. +- `Model::findAll`, findCount, findNeighbours, removed. +- Dynamic calling of setTablePrefix() has been removed. + tableprefix should be with the `$tablePrefix` property, and any + other custom construction behavior should be done in an overridden + `Model::__construct()`. +- `DboSource::query()` now throws warnings for un-handled model + methods, instead of trying to run them as queries. This means, + people starting transactions improperly via the + `$this->Model->begin()` syntax will need to update their code so + that it accesses the model's DataSource object directly. +- Missing validation methods will now trigger errors in + development mode. +- Missing behaviors will now trigger a cakeError. +- `Model::find(first)` will no longer use the id property for + default conditions if no conditions are supplied and id is not + empty. Instead no conditions will be used +- For Model::saveAll() the default value for option 'validate' is + now 'first' instead of true + +**Datasources** + +- DataSource::exists() has been refactored to be more consistent + with non-database backed datasources. Previously, if you set + `var $useTable = false; var $useDbConfig = 'custom';`, it was + impossible for `Model::exists()` to return anything but false. + This prevented custom datasources from using `create()` or + `update()` correctly without some ugly hacks. If you have custom + datasources that implement `create()`, `update()`, and + `read()` (since `Model::exists()` will make a call to + `Model::find('count')`, which is passed to + `DataSource::read()`), make sure to re-run your unit tests on + 1.3. + +**Databases** + +Most database configurations no longer support the 'connect' key +(which has been deprecated since pre-1.2). Instead, set +`'persistent' => true` or false to determine whether or not a +persistent database connection should be used + +**SQL log dumping** + +A commonly asked question is how can one disable or remove the SQL +log dump at the bottom of the page?. In previous versions the HTML +SQL log generation was buried inside DboSource. For 1.3 there is a +new core element called `sql_dump`. `DboSource` no longer +automatically outputs SQL logs. If you want to output SQL logs in +1.3, do the following: + +``` php +echo $this->element('sql_dump'); +``` + +You can place this element anywhere in your layout or view. The +`sql_dump` element will only generate output when +`Configure::read('debug')` is equal to 2. You can of course +customize or override this element in your app by creating +`app/views/elements/sql_dump.ctp`. + +## View and Helpers + +**View** + +- `View::renderElement` removed. Use `View::element()` + instead. +- Automagic support for `.thtml` view file extension has been + removed either declare `$this->ext = 'thtml';` in your + controllers, or rename your views to use `.ctp` +- `View::set('title', $var)` no longer sets + `$title_for_layout` when rendering the layout. + `$title_for_layout` is still populated by default. But if you + want to customize it, use `$this->set('title_for_layout', $var)`. +- `View::$pageTitle` has been removed. Use + `$this->set('title_for_layout', $var);` instead. +- The `$cakeDebug` layout variable associated with debug = 3 has + been removed. Remove it from your layouts as it will cause errors. + Also see the notes related to SQL log dumping and Configure for + more information. + +All core helpers no longer use `Helper::output()`. The method was +inconsistently used and caused output issues with many of +FormHelper's methods. If you previously overrode +`AppHelper::output()` to force helpers to auto-echo you will need +to update your view files to manually echo helper output. + +**TextHelper** + +- `TextHelper::trim()` is deprecated, used `truncate()` + instead. +- `TextHelper::highlight()` no longer has: +- an `$highlighter` parameter. Use `$options['format']` + instead. +- an `$considerHtml`parameter. Use `$options['html']` instead. +- `TextHelper::truncate()` no longer has: +- an `$ending` parameter. Use `$options['ending']` instead. +- an `$exact` parameter. Use `$options['exact']` instead. +- an `$considerHtml`parameter. Use `$options['html']` + instead. + +**PaginatorHelper** + +PaginatorHelper has had a number of enhancements applied to make +styling easier. +`prev()`, `next()`, `first()` and `last()` + +The disabled state of these methods now defaults to `` tags +instead of `
` tags. + +passedArgs are now auto merged with URL options in paginator. + +`sort()`, `prev()`, `next()` now add additional class names +to the generated html. `prev()` adds a class of prev. `next()` +adds a class of next. `sort()` will add the direction currently +being sorted, either asc or desc. + +**FormHelper** + +- `FormHelper::dateTime()` no longer has a `$showEmpty` + parameter. Use `$attributes['empty']` instead. +- `FormHelper::year()` no longer has a `$showEmpty` parameter. + Use `$attributes['empty']` instead. +- `FormHelper::month()` no longer has a `$showEmpty` + parameter. Use `$attributes['empty']` instead. +- `FormHelper::day()` no longer has a `$showEmpty` parameter. + Use `$attributes['empty']` instead. +- `FormHelper::minute()` no longer has a `$showEmpty` + parameter. Use `$attributes['empty']` instead. +- `FormHelper::meridian()` no longer has a `$showEmpty` + parameter. Use `$attributes['empty']` instead. +- `FormHelper::select()` no longer has a `$showEmpty` + parameter. Use `$attributes['empty']` instead. +- Default URLs generated by form helper no longer contain 'id' + parameter. This makes default URLs more consistent with documented + userland routes. Also enables reverse routing to work in a more + intuitive fashion with default FormHelper URLs. +- `FormHelper::submit()` Can now create other types of inputs + other than type=submit. Use the type option to control the type of + input generated. +- `FormHelper::button()` Now creates `