diff --git a/Makefile b/Makefile
index a137eae166..3e6174f0b8 100644
--- a/Makefile
+++ b/Makefile
@@ -11,7 +11,7 @@ ES_HOST =
LANGS = en es fr ja pt ru ro sr
# pdflatex does not like ja or ru for some reason.
-PDF_LANGS = en es fr pt ro sr
+PDF_LANGS = en es fr pt ro
DEST = website
diff --git a/README.mdown b/README.mdown
index b29e4a2a81..f6e2b1ab4e 100644
--- a/README.mdown
+++ b/README.mdown
@@ -23,10 +23,10 @@ You can install the phpdomain using:
*To run the easy_install command, the setuptools package must be previously installed.*
-Building the documentation
+Building the Documentation
--------------------------
-After installing the required packages, you can build the documentation using `Make`.
+After installing the required packages, you can build the documentation using `make`.
# Create all the HTML docs. Including all the languages.
make html
@@ -43,16 +43,16 @@ After installing the required packages, you can build the documentation using `M
# 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.
+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.
+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`
+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`.
@@ -68,9 +68,9 @@ There are currently a number of outstanding issues that need to be addressed. W
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.
+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.
+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
------------
@@ -78,17 +78,17 @@ 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
+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
+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
+Making Search Work Locally
--------------------------
* Install elasticsearch. This varies based on your platform, but most
diff --git a/config/all.py b/config/all.py
index cdc1a08bcf..800bf9ac0a 100644
--- a/config/all.py
+++ b/config/all.py
@@ -116,7 +116,7 @@
# 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'
+html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
diff --git a/en/appendices.rst b/en/appendices.rst
index fa818df38c..a2d173a4aa 100644
--- a/en/appendices.rst
+++ b/en/appendices.rst
@@ -4,6 +4,15 @@ Appendices
Appendices contain information regarding the new features
introduced in 2.x, and the migration path from 1.3 to 2.0.
+2.5 Migration Guide
+===================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/2-5-migration-guide
+
+
2.4 Migration Guide
===================
diff --git a/en/appendices/2-5-migration-guide.rst b/en/appendices/2-5-migration-guide.rst
new file mode 100644
index 0000000000..69be2f1051
--- /dev/null
+++ b/en/appendices/2-5-migration-guide.rst
@@ -0,0 +1,260 @@
+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``.
+- :php:meth:`Cache::remember()` was added.
+- :php:meth:`Cache::config()` now accepts ``database`` key when used with
+ :php:class:`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 :doc:`CompletionShell ` 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
+---------------
+
+- :php:class:`CookieComponent` can use the new AES-256 encryption offered by
+ :php:class:`Security`. You can enable this by calling
+ :php:meth:`CookieComponent::type()` with 'aes'.
+
+RequestHandlerComponent
+-----------------------
+
+- :php:meth:`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
+====
+
+CakePlugin
+----------
+
+- :php:meth:`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 :php:class:`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
+-----------
+
+- :php:meth:`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
+ :php:meth:`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
+------
+
+- :php:meth:`Router::mapResources()` accepts ``connectOptions`` key in the
+ ``$options`` argument. See :ref:`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
+----
+
+- :php:meth:`Hash::insert()` and :php:meth:`Hash::remove()` now support matcher
+ expressions in their path selectors.
+
+File
+----
+
+- :php:meth:`File::replaceText()` was added. This method allows you to easily
+ replace text in a file using ``str_replace``.
+
+
+Folder
+------
+
+- :php:meth:`Folder::addPathElement()` now accepts an array for the ``$element``
+ parameter.
+
+Security
+--------
+
+- :php:meth:`Security::encrypt()` and :php:meth:`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 :php:meth:`Validation::inList()` and :php:meth:`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 :php:meth:`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.
+- :php:meth:`View::get()` now accepts a second argument to provide a default
+ value.
+
+FormHelper
+----------
+
+- FormHelper will now generate file inputs for ``binary`` field types now.
+- :php:meth:`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.
+- :php:meth:`FormHelper::end()` and :php:meth:`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.
+
+PaginationHelper
+----------------
+
+- :php:meth:`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/en/cakephp-overview/understanding-model-view-controller.rst b/en/cakephp-overview/understanding-model-view-controller.rst
index 4df9a09871..0175e75040 100644
--- a/en/cakephp-overview/understanding-model-view-controller.rst
+++ b/en/cakephp-overview/understanding-model-view-controller.rst
@@ -20,9 +20,9 @@ But in general they stand for the major concepts around which you
implement your application.
In the case of a social network, the Model layer would take care of
-tasks such as saving the user data, saving friends associations, storing
-and retrieving user photos, finding new friends for suggestions, etc.
-While the model objects can be thought as "Friend", "User", "Comment", or
+tasks such as saving the user data, saving friends' associations, storing
+and retrieving user photos, finding suggestions for new friends, etc.
+The model objects can be thought as "Friend", "User", "Comment", or
"Photo".
The View layer
@@ -33,25 +33,25 @@ Model objects, it is responsible for using the information it has available
to produce any presentational interface your application might need.
For example, as the Model layer returns a set of data, the view would use it
-to render a HTML page containing it. Or a XML formatted result for others to
+to render a HTML page containing it, or a XML formatted result for others to
consume.
-The View layer is not only limited to HTML or text representation of the data,
-it can be used to deliver a wide variety of formats depending on your needs,
+The View layer is not only limited to HTML or text representation of the data.
+It can be used to deliver a wide variety of formats depending on your needs,
such as videos, music, documents and any other format you can think of.
The Controller layer
====================
-The Controller layer handles requests from users. It's responsible for rendering
-back a response with the aid of both the Model and the View Layer.
+The Controller layer handles requests from users. It is responsible for rendering
+a response with the aid of both the Model and the View layer.
-Controllers can be seen as managers taking care that all needed resources for
+A controller can be seen as a manager that ensures that all resources needed for
completing a task are delegated to the correct workers. It waits for petitions
from clients, checks their validity according to authentication or authorization rules,
-delegates data fetching or processing to the model, and selects the correct
-type of presentational data that the client is accepting, to finally delegate
-this rendering process to the View layer.
+delegates data fetching or processing to the model, selects the
+type of presentational data that the clients are accepting, and finally delegates
+the rendering process to the View layer.
CakePHP request cycle
@@ -66,12 +66,12 @@ resource in your application. This request is first processed by a dispatcher
which will select the correct controller object to handle it.
Once the request arrives at the controller, it will communicate with the Model layer
-to process any data fetching or saving operation that might be needed.
-After this communication is over, the controller will proceed at delegating to the
-correct view object the task of generating an output resulting from the data
+to process any data-fetching or -saving operation that might be needed.
+After this communication is over, the controller will proceed to delegate to the
+correct view object the task of generating output resulting from the data
provided by the model.
-Finally, when this output is generated, it is immediately rendered to the user
+Finally, when this output is generated, it is immediately rendered to the user.
Almost every request to your application will follow this basic
pattern. We'll add some details later on which are specific to
diff --git a/en/cakephp-overview/what-is-cakephp-why-use-it.rst b/en/cakephp-overview/what-is-cakephp-why-use-it.rst
index d8a6b5045d..01e3900e85 100644
--- a/en/cakephp-overview/what-is-cakephp-why-use-it.rst
+++ b/en/cakephp-overview/what-is-cakephp-why-use-it.rst
@@ -30,31 +30,31 @@ Here's a quick list of features you'll enjoy when using CakePHP:
- Active, friendly :ref:`cakephp-official-communities`
- Flexible `licensing `_
-- Compatible with versions PHP 5.2.8 and greater.
+- Compatible with versions PHP 5.2.8 and greater
- Integrated
`CRUD `_
- for database interaction.
+ for database interaction
- Application
- `scaffolding `_.
-- Code generation.
+ `scaffolding `_
+- Code generation
- `MVC `_
- architecture.
-- Request dispatcher with clean, custom URLs and routes.
+ architecture
+- Request dispatcher with clean, custom URLs and routes
- Built-in
- `validation `_.
+ `validation `_
- Fast and flexible
`templating `_
- (PHP syntax, with helpers).
-- View Helpers for AJAX, JavaScript, HTML Forms and more.
-- Email, Cookie, Security, Session, and Request Handling
- Components.
+ (PHP syntax, with helpers)
+- View helpers for AJAX, JavaScript, HTML forms and more
+- Email, cookie, security, session, and request handling
+ Components
- Flexible
- `ACL `_.
-- Data Sanitization.
-- Flexible `Caching `_.
-- Localization.
+ `ACL `_
+- Data sanitization
+- Flexible `caching `_
+- Localization
- Works from any web site directory, with little to no
- `Apache `_ configuration involved.
+ `Apache `_ configuration involved
.. meta::
diff --git a/en/console-and-shells.rst b/en/console-and-shells.rst
index e99b210769..1ba04b59f7 100644
--- a/en/console-and-shells.rst
+++ b/en/console-and-shells.rst
@@ -995,6 +995,7 @@ More topics
:maxdepth: 1
console-and-shells/cron-jobs
+ console-and-shells/completion-shell
console-and-shells/code-generation-with-bake
console-and-shells/schema-management-and-migrations
console-and-shells/i18n-shell
diff --git a/en/console-and-shells/code-generation-with-bake.rst b/en/console-and-shells/code-generation-with-bake.rst
index 39f6b16d5e..c1defc8dd1 100644
--- a/en/console-and-shells/code-generation-with-bake.rst
+++ b/en/console-and-shells/code-generation-with-bake.rst
@@ -56,6 +56,10 @@ command line::
$ cake bake all
+.. versionchanged:: 2.5
+ Test files produced by ``bake test`` include calls to `PHPunit's markTestIncomplete() `_ to draw attention to empty test methods. Before 2.5, empty tests pass silently.
+
+
Modify default HTML produced by "baked" templates
=================================================
diff --git a/en/console-and-shells/completion-shell.rst b/en/console-and-shells/completion-shell.rst
new file mode 100644
index 0000000000..69ec2eb588
--- /dev/null
+++ b/en/console-and-shells/completion-shell.rst
@@ -0,0 +1,115 @@
+Completion Shell
+################
+
+.. versionadded:: 2.5
+
+Working with the console gives the developer a lot of possibilities but having
+to completely know and write those commands can be tedious. Especially when
+developing new shells where the commands differ per minute iteration. The
+Completion Shells aids in this matter by providing an API to write completion
+scripts for shells like bash, zsh, fish etc.
+
+Sub Commands
+============
+
+The Completion Shell consists of a number of sub commands to assist the
+developer creating it's completion script. Each for a different step in the
+autocompletion process.
+
+commands
+--------
+
+For the first step commands outputs the available Shell Commands, including
+plugin name when applicable. (All returned possibilities, for this and the other
+sub commands, are separated by a space.) For example::
+
+ ./Console/cake Completion commands
+
+Returns::
+
+ acl api bake command_list completion console i18n schema server test testsuite upgrade
+
+Your completion script can select the relevant commands from that list to
+continue with. (For this and the following sub commands.)
+
+subCommands
+-----------
+
+Once the preferred command has been chosen subCommands comes in as the second
+step and outputs the possible sub command for the given shell command. For
+example::
+
+ ./Console/cake Completion subcommands bake
+
+Returns::
+
+ controller db_config fixture model plugin project test view
+
+options
+--------
+
+As the third and final options outputs options for the given (sub) command as
+set in getOptionParser. (Including the default options inherited from Shell.)
+For example::
+
+ ./Console/cake Completion options bake
+
+Returns::
+
+ --help -h --verbose -v --quiet -q --connection -c --theme -t
+
+Bash Example
+============
+
+The following bash example comes from the original author::
+
+ # bash completion for CakePHP console
+
+ _cake()
+ {
+ local cur prev opts cake
+ COMPREPLY=()
+ cake="${COMP_WORDS[0]}"
+ cur="${COMP_WORDS[COMP_CWORD]}"
+ prev="${COMP_WORDS[COMP_CWORD-1]}"
+
+ if [[ "$cur" == -* ]] ; then
+ if [[ ${COMP_CWORD} = 1 ]] ; then
+ opts=$(${cake} Completion options)
+ elif [[ ${COMP_CWORD} = 2 ]] ; then
+ opts=$(${cake} Completion options "${COMP_WORDS[1]}")
+ else
+ opts=$(${cake} Completion options "${COMP_WORDS[1]}" "${COMP_WORDS[2]}")
+ fi
+
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ return 0
+ fi
+
+ if [[ ${COMP_CWORD} = 1 ]] ; then
+ opts=$(${cake} Completion commands)
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ return 0
+ fi
+
+ if [[ ${COMP_CWORD} = 2 ]] ; then
+ opts=$(${cake} Completion subcommands $prev)
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ if [[ $COMPREPLY = "" ]] ; then
+ COMPREPLY=( $(compgen -df -- ${cur}) )
+ return 0
+ fi
+ return 0
+ fi
+
+
+ opts=$(${cake} Completion fuzzy "${COMP_WORDS[@]:1}")
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ if [[ $COMPREPLY = "" ]] ; then
+ COMPREPLY=( $(compgen -df -- ${cur}) )
+ return 0
+ fi
+ return 0;
+ }
+
+ complete -F _cake cake Console/cake
diff --git a/en/contributing/cakephp-coding-conventions.rst b/en/contributing/cakephp-coding-conventions.rst
index 1a6c3e225f..4d0824ce3b 100644
--- a/en/contributing/cakephp-coding-conventions.rst
+++ b/en/contributing/cakephp-coding-conventions.rst
@@ -10,7 +10,7 @@ You can use the `CakePHP Code Sniffer
`_ to check that your code
follows required standards.
-Adding new features
+Adding New Features
===================
No new features should be added, without having their own tests – which
@@ -109,7 +109,7 @@ clarity::
$variable = isset($options['variable']) ? isset($options['othervar']) ? true : false : false;
-View files
+View Files
----------
In view files (.ctp files) developers should use keyword control structures.
@@ -164,12 +164,12 @@ function call::
As you can see above there should be one space on both sides of equals
sign (=).
-Method definition
+Method Definition
=================
-Example of a function definition::
+Example of a method definition::
- function someFunction($arg1, $arg2 = '') {
+ public function someFunction($arg1, $arg2 = '') {
if (expr) {
statement;
}
@@ -177,8 +177,8 @@ Example of a function definition::
}
Parameters with a default value, should be placed last in function
-definition. Try to make your functions return something, at least true
-or false = so it can be determined whether the function call was
+definition. Try to make your functions return something, at least ``true``
+or ``false``, so it can be determined whether the function call was
successful::
public function connection($dns, $persistent = false) {
@@ -196,7 +196,47 @@ successful::
There are spaces on both side of the equals sign.
-Commenting code
+Typehinting
+-----------
+
+Arguments that expect objects or arrays can be typehinted.
+We only typehint public methods, though, as typehinting is not cost-free::
+
+ /**
+ * Some method description.
+ *
+ * @param Model $Model The model to use.
+ * @param array $array Some array value.
+ * @param boolean $boolean Some boolean value.
+ */
+ public function foo(Model $Model, array $array, $boolean) {
+ }
+
+Here ``$Model`` must be an instance of ``Model`` and ``$array`` must be an ``array``.
+
+Note that if you want to allow ``$array`` to be also an instance of ``ArrayObject``
+you should not typehint as ``array`` accepts only the primitive type::
+
+ /**
+ * Some method description.
+ *
+ * @param array|ArrayObject $array Some array value.
+ */
+ public function foo($array) {
+ }
+
+Method Chaining
+===============
+
+Method chaining should have multiple methods spread across separate lines, and
+indented with one tab::
+
+ $email->from('foo@example.com')
+ ->to('bar@example.com')
+ ->subject('A great message')
+ ->send();
+
+Commenting Code
===============
All comments should be written in English, and should in a clear way
@@ -205,7 +245,6 @@ describe the commented block of code.
Comments can include the following `phpDocumentor `_
tags:
-* `@access `_
* `@author `_
* `@copyright `_
* `@deprecated `_
@@ -223,6 +262,7 @@ processed if they are the first thing in a DocBlock line, for example::
/**
* Tag example.
+ *
* @author this tag is parsed, but this @version is ignored
* @version 1.0 this tag is also parsed
*/
@@ -233,12 +273,16 @@ processed if they are the first thing in a DocBlock line, for example::
* Example of inline phpDoc tags.
*
* This function works hard with foo() to rule the world.
+ *
+ * @return void
*/
function bar() {
}
/**
- * Foo function
+ * Foo function.
+ *
+ * @return void
*/
function foo() {
}
@@ -246,7 +290,7 @@ processed if they are the first thing in a DocBlock line, for example::
Comment blocks, with the exception of the first block in a file, should
always be preceded by a newline.
-Including files
+Including Files
===============
``include``, ``require``, ``include_once`` and ``require_once`` do not have parentheses::
@@ -262,12 +306,12 @@ Including files
When including files with classes or libraries, use only and always the
`require\_once `_ function.
-PHP tags
+PHP Tags
========
-Always use long tags (````) Instead of short tags ( ?>).
+Always use long tags (````) Instead of short tags (`` ?>``).
-Naming convention
+Naming Convention
=================
Functions
@@ -292,7 +336,7 @@ Variables
Variable names should be as descriptive as possible, but also as short
as possible. Normal variables should start with a lowercase letter, and
should be written in camelBack in case of multiple words. Variables
-containing objects should start with a capital letter, and in some way
+referencing objects should start with a capital letter, and in some way
associate to the class the variable is an object of. Example::
$user = 'John';
@@ -300,11 +344,11 @@ associate to the class the variable is an object of. Example::
$Dispatcher = new Dispatcher();
-Member visibility
+Member Visibility
-----------------
Use PHP5's private and protected keywords for methods and variables. Additionally,
-protected method or variable names start with a single underscore ("\_"). Example::
+protected method or variable names start with a single underscore (``_``). Example::
class A {
protected $_iAmAProtectedVariable;
@@ -314,7 +358,7 @@ protected method or variable names start with a single underscore ("\_"). Exampl
}
}
-Private methods or variable names start with double underscore ("\_\_"). Example::
+Private methods or variable names start with double underscore (``__``). Example::
class A {
private $__iAmAPrivateVariable;
@@ -328,18 +372,7 @@ Try to avoid private methods or variables, though, in favor of protected ones.
The latter can be accessed or modified by subclasses, whereas private ones
prevent extension or re-use. Private visibility also makes testing much more difficult.
-Method Chaining
----------------
-
-Method chaining should have multiple methods spread across separate lines, and
-indented with one tab::
-
- $email->from('foo@example.com')
- ->to('bar@example.com')
- ->subject('A great message')
- ->send();
-
-Example addresses
+Example Addresses
-----------------
For all example URL and mail addresses use "example.com", "example.org"
@@ -349,20 +382,18 @@ and "example.net", for example:
* WWW: `http://www.example.com `_
* FTP: `ftp://ftp.example.com `_
-The ``example.com`` domain name has been reserved for this (see :rfc:`2606`) and is recommended
+The "example.com" domain name has been reserved for this (see :rfc:`2606`) and is recommended
for use in documentation or as examples.
Files
-----
File names which do not contain classes should be lowercased and underscored, for
-example:
-
-::
+example::
long_file_name.php
-Variable types
+Variable Types
--------------
Variable types for use in DocBlocks:
@@ -371,22 +402,32 @@ Type
Description
mixed
A variable with undefined (or multiple) type.
-integer
+int
Integer type variable (whole number).
float
Float type (point number).
-boolean
+bool
Logical type (true or false).
string
String type (any value in " " or ' ').
+null
+ Null type. Usually used in conjunction with another type.
array
Array type.
object
- Object type.
+ Object type. A specific class name should be used if possible.
resource
Resource type (returned by for example mysql\_connect()).
Remember that when you specify the type as mixed, you should indicate
whether it is unknown, or what the possible types are.
+callable
+ Callable function.
+
+You can also combine types using the pipe char::
+
+ int|bool
+
+For more than two types it is usually best to just use ``mixed``.
Casting
-------
@@ -411,16 +452,12 @@ Type
Constants
---------
-Constants should be defined in capital letters:
-
-::
+Constants should be defined in capital letters::
define('CONSTANT', 1);
If a constant name consists of multiple words, they should be separated
-by an underscore character, for example:
-
-::
+by an underscore character, for example::
define('LONG_NAMED_CONSTANT', 2);
diff --git a/en/controllers.rst b/en/controllers.rst
index 984cddbca4..37159423ef 100644
--- a/en/controllers.rst
+++ b/en/controllers.rst
@@ -9,21 +9,21 @@ thought of as middle man between the Model and View. You want to keep your
controllers thin, and your models fat. This will help you more easily reuse
your code and makes your code easier to test.
-Commonly, controllers are used to manage the logic around a single model. For
+Commonly, a controller is used to manage the logic around a single model. For
example, if you were building a site for an online bakery, you might have a
-RecipesController and an IngredientsController managing your recipes and their
-ingredients. In CakePHP, controllers are named after the primary model they
-handle. It's totally possible to have controllers work with more than one model as
-well.
+RecipesController managing your recipes and an IngredientsController managing your
+ingredients. However, it's also possible to have controllers work with more than
+one model. In CakePHP, a controller is named after the primary model it
+handles.
Your application's controllers extend the ``AppController`` class, which in turn
extends the core :php:class:`Controller` class. The ``AppController``
class can be defined in ``/app/Controller/AppController.php`` and it should
contain methods that are shared between all of your application's controllers.
-Controllers provide a number of methods which are called *actions*. Actions are
-methods in a controller that handle requests. By default all public methods in
-a controller are an action, and accessible from a URL. Actions are responsible
+Controllers provide a number of methods that handle requests. These are called
+*actions*. By default, each public method in
+a controller is an action, and is accessible from a URL. An action is responsible
for interpreting the request and creating the response. Usually responses are
in the form of a rendered view, but there are other ways to create responses as
well.
@@ -37,39 +37,38 @@ The App Controller
As stated in the introduction, the ``AppController`` class is the
parent class to all of your application's controllers.
``AppController`` itself extends the :php:class:`Controller` class included in the
-CakePHP core library. As such, ``AppController`` is defined in
-``/app/Controller/AppController.php`` like so::
+CakePHP core library. ``AppController`` is defined in
+``/app/Controller/AppController.php`` as follows::
class AppController extends Controller {
}
Controller attributes and methods created in your ``AppController``
-will be available to all of your application's controllers. It is
-the ideal place to create code that is common to all of your
-controllers. Components (which you'll learn about later) are best
+will be available to all of your application's controllers. Components
+(which you'll learn about later) are best
used for code that is used in many (but not necessarily all)
controllers.
While normal object-oriented inheritance rules apply, CakePHP
does a bit of extra work when it comes to special controller
-attributes. The list of components and helpers used by a
+attributes. The components and helpers used by a
controller are treated specially. In these cases, ``AppController``
value arrays are merged with child controller class arrays. The values in the
child class will always override those in ``AppController.``
.. note::
- CakePHP merges the following variables from the ``AppController`` to
+ CakePHP merges the following variables from the ``AppController`` into
your application's controllers:
- :php:attr:`~Controller::$components`
- :php:attr:`~Controller::$helpers`
- :php:attr:`~Controller::$uses`
-Remember to add the default Html and Form helpers, if you define
+Remember to add the default Html and Form helpers if you define
the :php:attr:`~Controller::$helpers` property in your ``AppController``.
-Please, also remember to call ``AppController``'s callbacks within child
+Also remember to call ``AppController``'s callbacks within child
controller callbacks for best results::
public function beforeFilter() {
@@ -81,7 +80,7 @@ Request parameters
When a request is made to a CakePHP application, CakePHP's :php:class:`Router` and
:php:class:`Dispatcher` classes use :ref:`routes-configuration` to find and
-create the correct controller. The request data is encapsulated into a request
+create the correct controller. The request data is encapsulated in a request
object. CakePHP puts all of the important request information into the
``$this->request`` property. See the section on
:ref:`cake-request` for more information on the CakePHP request object.
@@ -91,10 +90,10 @@ Controller actions
Controller actions are responsible for converting the request parameters into a
response for the browser/user making the request. CakePHP uses conventions to
-automate this process and remove some boiler-plate code you would otherwise need
+automate this process and remove some boilerplate code you would otherwise need
to write.
-By convention CakePHP renders a view with an inflected version of the action
+By convention, CakePHP renders a view with an inflected version of the action
name. Returning to our online bakery example, our RecipesController might contain the
``view()``, ``share()``, and ``search()`` actions. The controller would be found
in ``/app/Controller/RecipesController.php`` and contain::
@@ -123,20 +122,20 @@ action name.
Controller actions generally use :php:meth:`~Controller::set()` to create a
context that :php:class:`View` uses to render the view. Because of the
conventions that CakePHP uses, you don't need to create and render the view
-manually. Instead once a controller action has completed, CakePHP will handle
+manually. Instead, once a controller action has completed, CakePHP will handle
rendering and delivering the View.
-If for some reason you'd like to skip the default behavior. Both of the
-following techniques will by-pass the default view rendering behavior.
+If for some reason you'd like to skip the default behavior, both of the
+following techniques will bypass the default view rendering behavior.
* If you return a string, or an object that can be converted to a string from
your controller action, it will be used as the response body.
* You can return a :php:class:`CakeResponse` object with the completely created
response.
-When controller methods are used with :php:meth:`~Controller::requestAction()`
+When you use controller methods with :php:meth:`~Controller::requestAction()`,
you will often want to return data that isn't a string. If you have controller
-methods that are used for normal web requests + requestAction you should check
+methods that are used for normal web requests + requestAction, you should check
the request type before returning::
class RecipesController extends AppController {
@@ -150,7 +149,7 @@ the request type before returning::
}
The above controller action is an example of how a method can be used with
-:php:meth:`~Controller::requestAction()` and normal requests. Returning an array data to a
+:php:meth:`~Controller::requestAction()` and normal requests. Returning array data to a
non-requestAction request will cause errors and should be avoided. See the
section on :php:meth:`~Controller::requestAction()` for more tips on using
:php:meth:`~Controller::requestAction()`
@@ -204,7 +203,7 @@ visit the `CakePHP API `_.
Interacting with Views
----------------------
-Controllers interact with the view in a number of ways. First they
+Controllers interact with views in a number of ways. First, they
are able to pass data to the views, using :php:meth:`~Controller::set()`. You can also
decide which view class to use, and which view file should be
rendered from the controller.
@@ -226,14 +225,7 @@ rendered from the controller.
The :php:meth:`~Controller::set()` method also takes an associative array as its first
parameter. This can often be a quick way to assign a set of
- information to the view.
-
- .. versionchanged:: 1.3
- Array keys will no longer be inflected before they are assigned
- to the view ('underscored\_key' does not become 'underscoredKey'
- anymore, etc.):
-
- ::
+ information to the view::
$data = array(
'color' => 'pink',
@@ -247,7 +239,7 @@ rendered from the controller.
$this->set($data);
- The attribute ``$pageTitle`` no longer exists, use :php:meth:`~Controller::set()` to set
+ The attribute ``$pageTitle`` no longer exists. Use :php:meth:`~Controller::set()` to set
the title::
$this->set('title_for_layout', 'This is the page title');
@@ -257,8 +249,8 @@ rendered from the controller.
The :php:meth:`~Controller::render()` method is automatically called at the end of each
requested controller action. This method performs all the view
- logic (using the data you've given in using the :php:meth:`~Controller::set()` method),
- places the view inside its :php:attr:`~View::$layout` and serves it back to the end
+ logic (using the data you've submitted using the :php:meth:`~Controller::set()` method),
+ places the view inside its :php:attr:`~View::$layout`, and serves it back to the end
user.
The default view file used by render is determined by convention.
@@ -274,12 +266,12 @@ rendered from the controller.
// ...
}
- Although CakePHP will automatically call it (unless you've set
- ``$this->autoRender`` to false) after every action's logic, you can
+ Although CakePHP will automatically call it after every action's logic
+ (unless you've set ``$this->autoRender`` to false), you can
use it to specify an alternate view file by specifying an action
name in the controller using ``$action``.
- If ``$view`` starts with '/' it is assumed to be a view or
+ If ``$view`` starts with '/', it is assumed to be a view or
element file relative to the ``/app/View`` folder. This allows
direct rendering of elements, very useful in AJAX calls.
::
@@ -287,15 +279,15 @@ rendered from the controller.
// Render the element in /View/Elements/ajaxreturn.ctp
$this->render('/Elements/ajaxreturn');
- The :php:attr:`~View::$layout` parameter allows you to specify the layout the
- view is rendered in.
+ The :php:attr:`~View::$layout` parameter allows you to specify the layout
+ with which the view is rendered.
Rendering a specific view
~~~~~~~~~~~~~~~~~~~~~~~~~
-In your controller you may want to render a different view than
-what would conventionally be done. You can do this by calling
-:php:meth:`~Controller::render()` directly. Once you have called :php:meth:`~Controller::render()` CakePHP
+In your controller, you may want to render a different view than
+the conventional one. You can do this by calling
+:php:meth:`~Controller::render()` directly. Once you have called :php:meth:`~Controller::render()`, CakePHP
will not try to re-render the view::
class PostsController extends AppController {
@@ -363,7 +355,7 @@ Flow Control
$this->redirect($this->referer());
- The method also supports name based parameters. If you want to redirect
+ The method also supports name-based parameters. If you want to redirect
to a URL like: ``http://www.example.com/orders/confirm/product:pizza/quantity:5``
you can use::
@@ -392,9 +384,9 @@ Flow Control
.. php:method:: flash(string $message, string|array $url, integer $pause, string $layout)
- Like :php:meth:`~Controller::redirect()`, the :php:meth:`~Controller::flash()`
- method is used to direct a user to a new page after an operation. The
- :php:meth:`~Controller::flash()` method is different in that it shows a
+ Like :php:meth:`~Controller::redirect()`, the :php:meth:`~Controller::flash()`
+ method is used to direct a user to a new page after an operation. The
+ :php:meth:`~Controller::flash()` method is different in that it shows a
message before passing the user on to another URL.
The first parameter should hold the message to be displayed, and
@@ -705,7 +697,7 @@ $components, $helpers and $uses
-------------------------------
The next most often used controller attributes tell CakePHP what
-:php:attr:`~Controller::$helpers`, :php:attr:`~Controller::$components`,
+:php:attr:`~Controller::$helpers`, :php:attr:`~Controller::$components`,
and ``models`` you'll be using in conjunction with
the current controller. Using these attributes make MVC classes
given by :php:attr:`~Controller::$components` and :php:attr:`~Controller::$uses` available to the controller
@@ -763,10 +755,10 @@ given by :php:attr:`~Controller::$helpers` to the view as an object reference va
.. php:attr:: components
The components array allows you to set which :doc:`/controllers/components`
- a controller will use. Like :php:attr:`~Controller::$helpers` and
- :php:attr:`~Controller::$uses` components in your controllers are
+ a controller will use. Like :php:attr:`~Controller::$helpers` and
+ :php:attr:`~Controller::$uses` components in your controllers are
merged with those in ``AppController``. As with
- :php:attr:`~Controller::$helpers` you can pass settings
+ :php:attr:`~Controller::$helpers` you can pass settings
into :php:attr:`~Controller::$components`. See :ref:`configuring-components` for more information.
Other Attributes
diff --git a/en/controllers/components.rst b/en/controllers/components.rst
index fa5603371e..e4b705e435 100644
--- a/en/controllers/components.rst
+++ b/en/controllers/components.rst
@@ -1,21 +1,16 @@
Components
##########
-Components are packages of logic that are shared between
-controllers. If you find yourself wanting to copy and paste things
-between controllers, you might consider wrapping some functionality
-in a component.
+Components are packages of logic that are shared between controllers.
+CakePHP comes with a fantastic set of core components you can use to aid in
+various common tasks. You can also create you own components. If you find
+yourself wanting to copy and paste things between controllers, you should
+consider creating your own component to contain the functionality. Creating
+components keeps controller code clean and allows you to reuse code between projects.
-CakePHP also comes with a fantastic set of core components you can
-use to aid in:
-
-.. include:: /core-libraries/toc-components.rst
- :start-line: 7
-
-Each of these core components is detailed in its own chapter.
-For now, we'll show you how to create your own components. Creating
-components keeps controller code clean and allows you to reuse code
-between projects.
+Each of the core components is detailed in its own chapter. See :doc:`/core-libraries/toc-components`.
+This section describes how to configure and use components, and how to create
+your own components.
.. _configuring-components:
@@ -150,6 +145,8 @@ Components also offer a few request life-cycle callbacks that allow them
to augment the request cycle. See the base :ref:`component-api` for
more information on the callbacks components offer.
+.. _creating-a-component:
+
Creating a Component
====================
diff --git a/en/controllers/request-response.rst b/en/controllers/request-response.rst
index 2b5de7adaa..62a29b8ed7 100644
--- a/en/controllers/request-response.rst
+++ b/en/controllers/request-response.rst
@@ -1,7 +1,7 @@
Request and Response objects
############################
-New in CakePHP 2.0 are request and response objects. In previous versions these
+New in CakePHP 2.0 are request and response objects. In previous versions, these
objects were represented through arrays, and the related methods were spread
across :php:class:`RequestHandlerComponent`, :php:class:`Router`,
:php:class:`Dispatcher` and :php:class:`Controller`. There was no authoritative
@@ -17,8 +17,8 @@ CakeRequest
:php:class:`CakeRequest` is the default request object used in CakePHP. It centralizes
a number of features for interrogating and interacting with request data.
-On each request one :php:class:`CakeRequest` is created and then passed by reference to the various
-layers of an application that use request data. By default :php:class:`CakeRequest` is assigned to
+On each request, one :php:class:`CakeRequest` is created and then passed by reference to the various
+layers of an application that use request data. By default, :php:class:`CakeRequest` is assigned to
``$this->request``, and is available in Controllers, Views and Helpers. You can
also access it in Components by using the controller reference. Some of the duties
:php:class:`CakeRequest` performs include:
@@ -34,18 +34,18 @@ also access it in Components by using the controller reference. Some of the duti
Accessing request parameters
============================
-:php:class:`CakeRequest` exposes several interfaces for accessing request parameters. The first is as object
-properties, the second is array indexes, and the third is through ``$this->request->params``::
+:php:class:`CakeRequest` exposes several interfaces for accessing request parameters. The first uses object
+properties, the second uses array indexes, and the third uses ``$this->request->params``::
$this->request->controller;
$this->request['controller'];
$this->request->params['controller'];
-All of the above will both access the same value. Multiple ways of accessing the
-parameters was done to ease migration for existing applications. All
+All of the above will access the same value. Multiple ways of accessing the
+parameters have been provided to ease migration for existing applications. All
:ref:`route-elements` are accessed through this interface.
-In addition to :ref:`route-elements` you also often need access to
+In addition to :ref:`route-elements`, you also often need access to
:ref:`passed-arguments` and :ref:`named-parameters`. These are both available
on the request object as well::
@@ -60,10 +60,10 @@ on the request object as well::
$this->request->params['named'];
All of these will provide you access to the passed arguments and named parameters. There
-are several important/useful parameters that CakePHP uses internally, these
+are several important/useful parameters that CakePHP uses internally. These
are also all found in the request parameters:
-* ``plugin`` The plugin handling the request, will be null for no plugin.
+* ``plugin`` The plugin handling the request. Will be null when there is no plugin.
* ``controller`` The controller handling the current request.
* ``action`` The action handling the current request.
* ``prefix`` The prefix for the current action. See :ref:`prefix-routing` for
@@ -76,17 +76,17 @@ are also all found in the request parameters:
Accessing Querystring parameters
================================
-Querystring parameters can be read from using :php:attr:`CakeRequest::$query`::
+Querystring parameters can be read using :php:attr:`CakeRequest::$query`::
// URL is /posts/index?page=1&sort=title
$this->request->query['page'];
- // You can also access it via array access
+ // You can also access it via an array
// Note: BC accessor, will be deprecated in future versions
$this->request['url']['page'];
You can either directly access the :php:attr:`~CakeRequest::$query` property, or you can use
-:php:meth:`CakeRequest::query()` to read the URL query array in an error free manner.
+:php:meth:`CakeRequest::query()` to read the URL query array in an error-free manner.
Any keys that do not exist will return ``null``::
$foo = $this->request->query('value_that_does_not_exist');
@@ -96,14 +96,14 @@ Accessing POST data
===================
All POST data can be accessed using :php:attr:`CakeRequest::$data`. Any form data
-that contains a ``data`` prefix, will have that data prefix removed. For example::
+that contains a ``data`` prefix will have that data prefix removed. For example::
// An input with a name attribute equal to 'data[MyModel][title]'
// is accessible at
$this->request->data['MyModel']['title'];
You can either directly access the :php:attr:`~CakeRequest::$data` property, or you can use
-:php:meth:`CakeRequest::data()` to read the data array in an error free manner.
+:php:meth:`CakeRequest::data()` to read the data array in an error-free manner.
Any keys that do not exist will return ``null``::
$foo = $this->request->data('Value.that.does.not.exist');
@@ -114,8 +114,8 @@ Accessing PUT or POST data
.. versionadded:: 2.2
-When building REST services you often accept request data on ``PUT`` and
-``DELETE`` requests. As of 2.2 any ``application/x-www-form-urlencoded``
+When building REST services, you often accept request data on ``PUT`` and
+``DELETE`` requests. As of 2.2, any ``application/x-www-form-urlencoded``
request body data will automatically be parsed and set to ``$this->data`` for
``PUT`` and ``DELETE`` requests. If you are accepting JSON or XML data, see
below for how you can access those request bodies.
@@ -123,16 +123,16 @@ below for how you can access those request bodies.
Accessing XML or JSON data
==========================
-Applications employing :doc:`/development/rest` often exchange data in non
-URL encoded post bodies. You can read input data in any format using
-:php:meth:`CakeRequest::input()`. By providing a decoding function you can
+Applications employing :doc:`/development/rest` often exchange data in non-URL-encoded
+post bodies. You can read input data in any format using
+:php:meth:`CakeRequest::input()`. By providing a decoding function, you can
receive the content in a deserialized format::
// Get JSON encoded data submitted to a PUT/POST action
$data = $this->request->input('json_decode');
-Since some deserializing methods require additional parameters when being called,
-such as the 'as array' parameter on ``json_decode`` or if you want XML converted
+Some deserializing methods require additional parameters when called,
+such as the 'as array' parameter on ``json_decode``. If you want XML converted
into a DOMDocument object, :php:meth:`CakeRequest::input()` supports passing
in additional parameters as well::
@@ -154,22 +154,22 @@ Inspecting the request
Detecting various request conditions used to require using
:php:class:`RequestHandlerComponent`. These methods have been moved to
-:php:class:`CakeRequest`, and offer a new interface alongside a more backwards compatible
+:php:class:`CakeRequest`, and offer a new interface alongside a more backwards-compatible
usage::
$this->request->is('post');
$this->request->isPost(); // deprecated
-Both method calls will return the same value. For the time being the methods
+Both method calls will return the same value. For the time being, the methods
are still available on :php:class:`RequestHandlerComponent`, but are deprecated and still might be
removed before the final release. You can also easily extend the request
-detectors that are available, by using :php:meth:`CakeRequest::addDetector()`
+detectors that are available by using :php:meth:`CakeRequest::addDetector()`
to create new kinds of detectors. There are four different types of detectors
that you can create:
-* Environment value comparison - An environment value comparison, compares a
- value fetched from :php:func:`env()` to a known value the environment value is
- equality checked against the provided value.
+* Environment value comparison - Compares a
+ value fetched from :php:func:`env()` for equality
+ with the provided value.
* Pattern value comparison - Pattern value comparison allows you to compare a
value fetched from :php:func:`env()` to a regular expression.
* Option based comparison - Option based comparisons use a list of options to
@@ -193,7 +193,7 @@ Some examples would be::
array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i')
);
- // Add an option detector
+ // Add an option detector.
$this->request->addDetector('internalIp', array(
'env' => 'CLIENT_IP',
'options' => array('192.168.0.101', '192.168.0.100')
@@ -210,21 +210,21 @@ Some examples would be::
:php:class:`CakeRequest` also includes methods like :php:meth:`CakeRequest::domain()`,
:php:meth:`CakeRequest::subdomains()` and :php:meth:`CakeRequest::host()` to
-help applications with subdomains, have a slightly easier life.
+help applications with subdomains.
There are several built-in detectors that you can use:
-* ``is('get')`` Check to see if the current request is a GET.
-* ``is('put')`` Check to see if the current request is a PUT.
-* ``is('post')`` Check to see if the current request is a POST.
-* ``is('delete')`` Check to see if the current request is a DELETE.
-* ``is('head')`` Check to see if the current request is HEAD.
-* ``is('options')`` Check to see if the current request is OPTIONS.
-* ``is('ajax')`` Check to see of the current request came with
+* ``is('get')`` Check to see whether the current request is a GET.
+* ``is('put')`` Check to see whether the current request is a PUT.
+* ``is('post')`` Check to see whether the current request is a POST.
+* ``is('delete')`` Check to see whether the current request is a DELETE.
+* ``is('head')`` Check to see whether the current request is HEAD.
+* ``is('options')`` Check to see whether the current request is OPTIONS.
+* ``is('ajax')`` Check to see whether the current request came with
X-Requested-with = XmlHttpRequest.
-* ``is('ssl')`` Check to see if the request is via SSL
-* ``is('flash')`` Check to see if the request has a User-Agent of Flash
-* ``is('mobile')`` Check to see if the request came from a common list
+* ``is('ssl')`` Check to see whether the request is via SSL
+* ``is('flash')`` Check to see whether the request has a User-Agent of Flash
+* ``is('mobile')`` Check to see whether the request came from a common list
of mobile agents.
@@ -232,13 +232,13 @@ CakeRequest and RequestHandlerComponent
=======================================
Since many of the features :php:class:`CakeRequest` offers used to be the realm of
-:php:class:`RequestHandlerComponent` some rethinking was required to figure out how it
+:php:class:`RequestHandlerComponent`, some rethinking was required to figure out how it
still fits into the picture. For 2.0, :php:class:`RequestHandlerComponent`
-acts as a sugar daddy providing a layer of sugar on top of the utility
-:php:class:`CakeRequest` affords. Sugar like switching layout and views based on content
-types or AJAX is the domain of :php:class:`RequestHandlerComponent`.
+provides a layer of sugar, such as switching layout
+and views based on content, on top of the utility that
+:php:class:`CakeRequest` affords.
This separation of utility and sugar between the two classes lets you
-more easily pick and choose what you want and what you need.
+more easily choose what you want.
Interacting with other aspects of the request
=============================================
@@ -249,7 +249,7 @@ properties and methods.
* ``$this->request->webroot`` contains the webroot directory.
* ``$this->request->base`` contains the base path.
-* ``$this->request->here`` contains the full address to the current request
+* ``$this->request->here`` contains the full address to the current request.
* ``$this->request->query`` contains the query string parameters.
@@ -258,7 +258,7 @@ CakeRequest API
.. php:class:: CakeRequest
- CakeRequest encapsulates request parameter handling, and introspection.
+ CakeRequest encapsulates request parameter handling and introspection.
.. php:method:: domain($tldLength = 1)
@@ -278,11 +278,21 @@ CakeRequest API
.. php:method:: onlyAllow($methods)
- Set allowed HTTP methods, if not matched will throw MethodNotAllowedException
+ Set allowed HTTP methods. If not matched, will throw MethodNotAllowedException.
The 405 response will include the required ``Allow`` header with the passed methods
.. versionadded:: 2.3
+ .. deprecated:: 2.5
+ Use :php:meth:`CakeRequest::allowMethod()` instead.
+
+.. php:method:: allowMethod($methods)
+
+ Set allowed HTTP methods. If not matched will throw MethodNotAllowedException.
+ The 405 response will include the required ``Allow`` header with the passed methods
+
+ .. versionadded:: 2.5
+
.. php:method:: referer($local = false)
Returns the referring address for the request.
@@ -294,11 +304,11 @@ CakeRequest API
.. php:method:: header($name)
Allows you to access any of the ``HTTP_*`` headers that were used
- for the request::
+ for the request. For example::
$this->request->header('User-Agent');
- Would return the user agent used for the request.
+ would return the user agent used for the request.
.. php:method:: input($callback, [$options])
@@ -311,8 +321,8 @@ CakeRequest API
.. php:method:: data($name)
- Provides dot notation access to request data. Allows for reading and
- modification of request data, calls can be chained together as well::
+ Provides dot notation access to request data. Allows request data to be read and
+ modified. Calls can be chained together as well::
// Modify some request data, so you can prepopulate some form fields.
$this->request->data('Post.title', 'New post')
@@ -332,7 +342,7 @@ CakeRequest API
.. php:method:: is($type)
- Check whether or not a Request matches a certain criteria. Uses
+ Check whether or not a Request matches a certain criterion. Uses
the built-in detection rules as well as any additional rules defined
with :php:meth:`CakeRequest::addDetector()`.
@@ -343,7 +353,7 @@ CakeRequest API
.. php:method:: accepts($type = null)
- Find out which content types the client accepts or check if they accept a
+ Find out which content types the client accepts, or check whether it accepts a
particular type of content.
Get all types::
@@ -356,14 +366,14 @@ CakeRequest API
.. php:staticmethod:: acceptLanguage($language = null)
- Get either all the languages accepted by the client,
- or check if a specific language is accepted.
+ Get all the languages accepted by the client,
+ or check whether a specific language is accepted.
Get the list of accepted languages::
CakeRequest::acceptLanguage();
- Check if a specific language is accepted::
+ Check whether a specific language is accepted::
CakeRequest::acceptLanguage('es-es');
@@ -415,7 +425,7 @@ of methods previously found on :php:class:`Controller`,
:php:class:`RequestHandlerComponent` and :php:class:`Dispatcher`. The old
methods are deprecated in favour of using :php:class:`CakeResponse`.
-:php:class:`CakeResponse` provides an interface to wrap the common response related
+:php:class:`CakeResponse` provides an interface to wrap the common response-related
tasks such as:
* Sending headers for redirects.
@@ -427,10 +437,8 @@ Changing the response class
===========================
CakePHP uses :php:class:`CakeResponse` by default. :php:class:`CakeResponse` is a flexible and
-transparent to use class. If you need to replace it with an application
-specific class, you can override and replace :php:class:`CakeResponse` with
-your own class by replacing :php:class:`CakeResponse` in ``app/webroot/index.php``.
-
+transparent class. If you need to override it with your own application-specific class,
+you can replace :php:class:`CakeResponse` in ``app/webroot/index.php``.
This will make all the controllers in your application use ``CustomResponse``
instead of :php:class:`CakeResponse`. You can also replace the response
instance by setting ``$this->response`` in your controllers. Overriding the
@@ -441,9 +449,9 @@ out the methods that interact with :php:meth:`~CakeResponse::header()`. See the
Dealing with content types
==========================
-You can control the Content-Type of your application's responses with using
+You can control the Content-Type of your application's responses with
:php:meth:`CakeResponse::type()`. If your application needs to deal with
-content types that are not built into :php:class:`CakeResponse`, you can map those types
+content types that are not built into :php:class:`CakeResponse`, you can map them
with :php:meth:`CakeResponse::type()` as well::
// Add a vCard type
@@ -452,7 +460,7 @@ with :php:meth:`CakeResponse::type()` as well::
// Set the response Content-Type to vcard.
$this->response->type('vcf');
-Usually you'll want to map additional content types in your controller's
+Usually, you'll want to map additional content types in your controller's
:php:meth:`~Controller::beforeFilter()` callback, so you can leverage the automatic view switching
features of :php:class:`RequestHandlerComponent` if you are using it.
@@ -462,8 +470,8 @@ Sending files
=============
There are times when you want to send files as responses for your requests.
-Prior to version 2.3 you could use :php:class:`MediaView` to accomplish that.
-As of 2.3 :php:class:`MediaView` is deprecated and you can use :php:meth:`CakeResponse::file()`
+Prior to version 2.3, you could use :php:class:`MediaView`.
+As of 2.3, :php:class:`MediaView` is deprecated and you can use :php:meth:`CakeResponse::file()`
to send a file as response::
public function sendFile($id) {
@@ -474,12 +482,12 @@ to send a file as response::
return $this->response;
}
-As shown in the above example, you have to pass the file path to the method.
-CakePHP will send proper content type header if it's a known file type listed in
-:php:attr:`CakeReponse::$_mimeTypes`. You can add new types prior to calling :php:meth:`CakeResponse::file()`
+As shown in the above example, you must pass the file path to the method.
+CakePHP will send a proper content type header if it's a known file type listed in
+:php:attr:`CakeResponse::$_mimeTypes`. You can add new types prior to calling :php:meth:`CakeResponse::file()`
by using the :php:meth:`CakeResponse::type()` method.
-If you want you can also force a file to be downloaded instead of being displayed in
+If you want, you can also force a file to be downloaded instead of displayed in
the browser by specifying the options::
$this->response->file(
@@ -490,8 +498,8 @@ the browser by specifying the options::
Sending a string as file
========================
-You can respond with a file that does not exist on the disk, for instance with
-a pdf or an ics generated on the fly, and serve the generated string as a file by using::
+You can respond with a file that does not exist on the disk, such as
+a pdf or an ics generated on the fly from a string::
public function sendIcs() {
$icsString = $this->Calendar->generateIcs();
@@ -527,7 +535,7 @@ can be called with a few different parameter configurations::
));
Setting the same :php:meth:`~CakeResponse::header()` multiple times will result in overwriting the previous
-values, just like regular header calls. Headers are not sent when
+values, just as regular header calls do. Headers are not sent when
:php:meth:`CakeResponse::header()` is called; instead they are buffered
until the response is actually sent.
@@ -572,17 +580,17 @@ Cache-Control's ``public`` directive is set as well.
Fine tuning HTTP cache
======================
-One of the best and easiest ways of speeding up your application is using HTTP
-cache. Under this caching model you are only required to help clients decide if
+One of the best and easiest ways of speeding up your application is to use HTTP
+cache. Under this caching model, you are only required to help clients decide if
they should use a cached copy of the response by setting a few headers such as
-modified time, response entity tag and others.
+modified time and response entity tag.
-Opposed to having to code the logic for caching and for invalidating (refreshing)
+Rather than forcing you to code the logic for caching and for invalidating (refreshing)
it once the data has changed, HTTP uses two models, expiration and validation,
-which usually are a lot simpler than having to manage the cache yourself.
+which usually are much simpler to use.
-Apart from using :php:meth:`CakeResponse::cache()` you can also use many other
-methods to fine tune HTTP cache headers to take advantage of browser or reverse
+Apart from using :php:meth:`CakeResponse::cache()`, you can also use many other
+methods to fine-tune HTTP cache headers to take advantage of browser or reverse
proxy caching.
The Cache Control header
@@ -597,15 +605,15 @@ that can change the way browsers or proxies use the cached content. A
Cache-Control: private, max-age=3600, must-revalidate
:php:class:`CakeResponse` class helps you set this header with some utility methods that
-will produce a final valid ``Cache-Control`` header. First of them is :php:meth:`CakeResponse::sharable()`
-method, which indicates whether a response in to be considered sharable across
-different users or clients or users. This method actually controls the ``public``
+will produce a final valid ``Cache-Control`` header. The first is the :php:meth:`CakeResponse::sharable()`
+method, which indicates whether a response is to be considered sharable across
+different users or clients. This method actually controls the ``public``
or ``private`` part of this header. Setting a response as private indicates that
all or part of it is intended for a single user. To take advantage of shared
-caches it is needed to set the control directive as public
+caches, the control directive must be set as public.
-Second parameter of this method is used to specify a ``max-age`` for the cache,
-which is the number of seconds, after which the response is no longer considered
+The second parameter of this method is used to specify a ``max-age`` for the cache,
+which is the number of seconds after which the response is no longer considered
fresh::
public function view() {
@@ -652,12 +660,12 @@ whether the resource has changed, instead of using it directly.
This is commonly used with static resources such as images and other assets.
The :php:meth:`~CakeResponse::etag()` method (called entity tag) is a string that uniquely identifies the
-requested resource. It is very much like a checksum of a file; caching
-will compare checksums to tell whether they match or not.
+requested resource, as a checksum does for a file, in order to determine whether
+it matches a cached resource.
-To take advantage of this header you have to either call the
-:php:meth:`CakeResponse::checkNotModified()` method manually or to have the
-:php:class:`RequestHandlerComponent` included in your controller::
+To take advantage of this header, you must either call the
+:php:meth:`CakeResponse::checkNotModified()` method manually or include the
+:php:class:`RequestHandlerComponent` in your controller::
public function index() {
$articles = $this->Article->find('all');
@@ -673,14 +681,14 @@ The Last Modified header
.. versionadded:: 2.1
-Also, under the HTTP cache validation model, you can set the ``Last-Modified``
+Under the HTTP cache validation model, you can also set the ``Last-Modified``
header to indicate the date and time at which the resource was modified for the
-last time. Setting this header helps CakePHP to tell caching clients whether
-the response was modified or not based on the their cache.
+last time. Setting this header helps CakePHP tell caching clients whether
+the response was modified or not based on their cache.
-To actually get advantage of using this header you have to either call manually
-:php:meth:`CakeResponse::checkNotModified()` method or have the
-:php:class:`RequestHandlerComponent` included in your controller::
+To take advantage of this header, you must either call the
+:php:meth:`CakeResponse::checkNotModified()` method manually or include the
+:php:class:`RequestHandlerComponent` in your controller::
public function view() {
$article = $this->Article->find('first');
@@ -694,7 +702,7 @@ To actually get advantage of using this header you have to either call manually
The Vary header
---------------
-In some cases you might want to serve different content using the same URL.
+In some cases, you might want to serve different content using the same URL.
This is often the case if you have a multilingual page or respond with different
HTML depending on the browser. Under such circumstances you can use the ``Vary`` header::
@@ -710,7 +718,7 @@ CakeResponse and testing
Probably one of the biggest wins from :php:class:`CakeResponse` comes from how it makes
testing controllers and components easier. Instead of having methods spread across
several objects, you only have to mock a single object, since controllers and
-components delegate to :php:class:`CakeResponse`. This helps you to get closer to a 'unit'
+components delegate to :php:class:`CakeResponse`. This helps you to get closer to a unit
test and makes testing controllers easier::
public function testSomething() {
@@ -720,7 +728,7 @@ test and makes testing controllers easier::
}
Additionally, you can run tests from the command line more easily, as you can use
-mocks to avoid the 'headers sent' errors, which can come up from trying to set
+mocks to avoid the 'headers sent' errors that can occur when trying to set
headers in CLI.
@@ -774,7 +782,7 @@ CakeResponse API
.. php:method:: expires($time = null)
- Allows to set the ``Expires`` header to a specific date.
+ Allows the ``Expires`` header to be set to a specific date.
.. versionadded:: 2.1
@@ -794,7 +802,7 @@ CakeResponse API
.. php:method:: checkNotModified(CakeRequest $request)
Compares the cache headers for the request object with the cache header from
- the response and determines if it can still be considered fresh. If so,
+ the response and determines whether it can still be considered fresh. If so,
deletes the response content, and sends the `304 Not Modified` header.
.. versionadded:: 2.1
@@ -813,13 +821,13 @@ CakeResponse API
.. php:method:: body($content = null)
- Set the content body of the response.
+ Sets the content body of the response.
.. php:method:: send()
Once you are done creating a response, calling :php:meth:`~CakeResponse::send()` will send all
the set headers as well as the body. This is done automatically at the
- end of each request by :php:class:`Dispatcher`
+ end of each request by :php:class:`Dispatcher`.
.. php:method:: file($path, $options = array())
@@ -829,4 +837,4 @@ CakeResponse API
.. meta::
:title lang=en: Request and Response objects
- :keywords lang=en: request controller,request parameters,array indexes,purpose index,response objects,domain information,request object,request data,interrogating,params,previous versions,introspection,dispatcher,rout,data structures,arrays,ip address,migration,indexes,cakephp
\ No newline at end of file
+ :keywords lang=en: request controller,request parameters,array indexes,purpose index,response objects,domain information,request object,request data,interrogating,params,previous versions,introspection,dispatcher,rout,data structures,arrays,ip address,migration,indexes,cakephp
diff --git a/en/controllers/scaffolding.rst b/en/controllers/scaffolding.rst
index 99cc24d875..7c3a5a913c 100644
--- a/en/controllers/scaffolding.rst
+++ b/en/controllers/scaffolding.rst
@@ -1,6 +1,9 @@
Scaffolding
###########
+.. deprecated:: 2.5
+ Dynamic scaffolding will be removed and replaced in 3.0
+
Application scaffolding is a technique that allows a developer to
define and create a basic application that can create, retrieve,
update and delete objects. Scaffolding in CakePHP also allows
@@ -136,4 +139,4 @@ Custom scaffolding views for all controllers should be placed like so::
.. meta::
:title lang=en: Scaffolding
- :keywords lang=en: database schemas,loose structure,scaffolding,scaffold,php class,database tables,web developer,downside,web application,logic,developers,cakephp,running,current,delete,database application
\ No newline at end of file
+ :keywords lang=en: database schemas,loose structure,scaffolding,scaffold,php class,database tables,web developer,downside,web application,logic,developers,cakephp,running,current,delete,database application
diff --git a/en/core-libraries/behaviors/containable.rst b/en/core-libraries/behaviors/containable.rst
index 1a0d33ddff..f3bc1cf966 100644
--- a/en/core-libraries/behaviors/containable.rst
+++ b/en/core-libraries/behaviors/containable.rst
@@ -252,7 +252,7 @@ by Daniel::
There is an important caveat to using Containable when filtering on a deeper association. In the previous example,
assume you had 3 posts in your database and Daniel had commented on 2 of those posts. The operation
$this->Post->find('all', array('contain' => 'Comment.author = "Daniel"')); would return ALL 3 posts, not
-just the 3 posts that Daniel had commented on. It won't return all comments however, just comments by Daniel.::
+just the 2 posts that Daniel had commented on. It won't return all comments however, just comments by Daniel.::
[0] => Array
(
diff --git a/en/core-libraries/caching.rst b/en/core-libraries/caching.rst
index 1e73921548..497e10d98d 100644
--- a/en/core-libraries/caching.rst
+++ b/en/core-libraries/caching.rst
@@ -31,6 +31,8 @@ to implement your own caching systems. The built-in caching engines are:
* ``MemcacheEngine`` Uses the `Memcache `_
extension. Memcache provides a very fast cache system that can be
distributed across many servers, and provides atomic operations.
+* ``MemcachedEngine`` Uses the `Memcached `_
+ extension. It also interfaces with memcache but provides better performance.
* ``RedisEngine`` Uses the `phpredis `_
extension. Redis provides a fast and persistent cache system similar to
memcached, also provides atomic operations.
@@ -40,6 +42,9 @@ to implement your own caching systems. The built-in caching engines are:
had difficulty setting up and deploying APC correctly both in cli + web.
Using files should make setting up CakePHP simpler for new developers.
+.. versionchanged:: 2.5
+ The Memcached engine was added. And the Memcache engine was deprecated.
+
Regardless of the CacheEngine you choose to use, your application interacts with
:php:class:`Cache` in a consistent manner. This means you can easily swap cache engines
as your application grows. In addition to the :php:class:`Cache` class, the
@@ -208,6 +213,21 @@ You could improve the above code by moving the cache reading logic into
a behavior, that read from the cache, or ran the associated model method.
That is an exercise you can do though.
+As of 2.5 you can accomplish the above much more simply using
+:php:meth:`Cache::remember()`. Using the new method the above would look like::
+
+ class Post extends AppModel {
+
+ public function newest() {
+ $model = $this;
+ return Cache::remember('newest_posts', function() use ($model){
+ return $model->find('all', array(
+ 'order' => 'Post.updated DESC',
+ 'limit' => 10
+ ));
+ }, 'longterm');
+ }
+ }
Using Cache to store counters
=============================
@@ -233,7 +253,7 @@ After setting an integer value, you can manipulate it using
.. note::
Incrementing and decrementing do not work with FileEngine. You should use
- APC, Redis or Memcache instead.
+ APC, Redis or Memcached instead.
Using groups
@@ -414,6 +434,27 @@ Cache API
Retrieve group names to config mapping.
+.. php:staticmethod:: remember($key, $callable, $config = 'default')
+
+ Provides an easy way to do read-through caching. If the cache key exists
+ it will be returned. If the key does not exist, the callable will be invoked
+ and the results stored in the cache at the provided key.
+
+ For example, you often want to cache query results. You could use
+ ``remember()`` to make this simple. Assuming you were using PHP5.3 or more::
+
+ class Articles extends AppModel {
+ function all() {
+ $model = $this;
+ return Cache::remember('all_articles', function() use ($model){
+ return $model->find('all');
+ });
+ }
+ }
+
+ .. versionadded:: 2.5
+ remember() was added in 2.5.
+
.. meta::
:title lang=en: Caching
:keywords lang=en: uniform api,xcache,cache engine,cache system,atomic operations,php class,disk storage,static methods,php extension,consistent manner,similar features,apc,memcache,queries,cakephp,elements,servers,memory
diff --git a/en/core-libraries/components/access-control-lists.rst b/en/core-libraries/components/access-control-lists.rst
index 8529cb9ca7..282d67a79d 100644
--- a/en/core-libraries/components/access-control-lists.rst
+++ b/en/core-libraries/components/access-control-lists.rst
@@ -3,15 +3,6 @@ Access Control Lists
.. php:class:: AclComponent(ComponentCollection $collection, array $settings = array())
-CakePHP's access control list functionality is one of the most
-oft-discussed, most likely because it is the most sought after, but
-also because it can be the most confusing. If you're looking for a
-good way to get started with ACLs in general, read on.
-
-Be brave and stick with it, even if the going gets rough. Once you
-get the hang of it, it's an extremely powerful tool to have on hand
-when developing your application.
-
Understanding How ACL Works
===========================
@@ -21,32 +12,32 @@ maintainable and manageable way.
Access control lists, or ACL, handle two main things: things that
want stuff, and things that are wanted. In ACL lingo, things (most
-often users) that want to use stuff are called access request
+often users) that want to use stuff are represented by access request
objects, or AROs. Things in the system that are wanted (most often
-actions or data) are called access control objects, or ACOs. The
+actions or data) are represented by access control objects, or ACOs. The
entities are called 'objects' because sometimes the requesting
-object isn't a person - sometimes you might want to limit the
-access certain CakePHP controllers have to initiate logic in other
+object isn't a person. Sometimes you might want to limit the
+ability of certain CakePHP controllers to initiate logic in other
parts of your application. ACOs could be anything you want to
-control, from a controller action, to a web service, to a line on
+control, from a controller action, to a web service, to a line in
your grandma's online diary.
To review:
-- ACO - Access Control Object - Something that is wanted
-- ARO - Access Request Object - Something that wants something
+- ACO - Access Control Object - Represents something that is wanted
+- ARO - Access Request Object - Represents something that wants something else
-Essentially, ACL is what is used to decide when an ARO can have
+Essentially, ACLs are used to decide when an ARO can have
access to an ACO.
In order to help you understand how everything works together,
let's use a semi-practical example. Imagine, for a moment, a
-computer system used by a familiar group of fantasy novel
-adventurers from the *Lord of the Rings*. The leader of the group,
+computer system used by a familiar group of adventurers
+from the fantasy novel *Lord of the Rings*. The leader of the group,
Gandalf, wants to manage the party's assets while maintaining a
healthy amount of privacy and security for the other members of the
party. The first thing he needs to do is create a list of the AROs
-involved:
+(requesters) involved:
- Gandalf
@@ -68,7 +59,7 @@ involved:
they can do (ACL).
The next thing Gandalf needs to do is make an initial list of
-things, or ACOs, the system will handle. His list might look
+ACOs (resources) the system will handle. His list might look
something like:
@@ -78,10 +69,9 @@ something like:
- Diplomacy
- Ale
-Traditionally, systems were managed using a sort of matrix, that
+Traditionally, systems were managed using a sort of matrix that
showed a basic set of users and permissions relating to objects. If
-this information were stored in a table, it might look like the
-following table:
+this information were stored in a table, it might look like this:
======== ======== ========= ============ ========== =======
x Weapons The Ring Salted Pork Diplomacy Ale
@@ -108,26 +98,26 @@ Merry Allow Allow
At first glance, it seems that this sort of system could work
rather well. Assignments can be made to protect security (only
Frodo can access the ring) and protect against accidents (keeping
-the hobbits out of the salted pork and weapons). It seems fine
-grained enough, and easy enough to read, right?
+the hobbits out of the salted pork and weapons). It seems sufficiently
+fine-grained and easy to read, right?
For a small system like this, maybe a matrix setup would work. But
-for a growing system, or a system with a large amount of resources
-(ACOs) and users (AROs), a table can become unwieldy rather
-quickly. Imagine trying to control access to the hundreds of war
+for a growing system, or a system with a large number of resources
+(ACOs) and users (AROs), a table can quickly become unwieldy.
+Imagine trying to control access to the hundreds of war
encampments and trying to manage them by unit. Another drawback to
-matrices is that you can't really logically group sections of users
+matrices is that you can't create logical groups of users
or make cascading permissions changes to groups of users based on
those logical groupings. For example, it would sure be nice to
automatically allow the hobbits access to the ale and pork once the
-battle is over: Doing it on an individual user basis would be
+battle is over. Doing it on an individual user basis would be
tedious and error prone. Making a cascading permissions change to
-all 'hobbits' would be easy.
+all members of the 'hobbit' group at once would be easy.
-ACL is most usually implemented in a tree structure. There is
-usually a tree of AROs and a tree of ACOs. By organizing your
-objects in trees, permissions can still be dealt out in a granular
-fashion, while still maintaining a good grip on the big picture.
+ACL is most usually implemented in a tree structure, with
+a tree of AROs and a tree of ACOs. By organizing your
+objects in trees, you can deal out permissions in a granular
+fashion while maintaining a good grip on the big picture.
Being the wise leader he is, Gandalf elects to use ACL in his new
system, and organizes his objects along the following lines:
@@ -192,8 +182,8 @@ our ARO tree, Gandalf can tack on a few group-based permissions:
-If we wanted to use ACL to see if the Pippin was allowed to access
-the ale, we'd first get his path in the tree, which is
+If we wanted to use ACL to see whether Pippin was allowed to access
+the ale, we'd first consult the tree to retrieve his path through it, which is
Fellowship->Hobbits->Pippin. Then we see the different permissions
that reside at each of those points, and use the most specific
permission relating to Pippin and the Ale.
@@ -215,7 +205,7 @@ Pippin -- Still allowing ale!
that ACO.
The tree also allows us to make finer adjustments for more granular
-control - while still keeping the ability to make sweeping changes
+control, while still keeping the ability to make sweeping changes
to groups of AROs:
@@ -253,11 +243,11 @@ to groups of AROs:
-This approach allows us both the ability to make wide-reaching
-permissions changes, but also fine-grained adjustments. This allows
+This approach allows us the ability to make both wide-reaching
+permissions changes and fine-grained adjustments. This allows
us to say that all hobbits can have access to ale, with one
-exception—Merry. To see if Merry can access the Ale, we'd find his
-path in the tree: Fellowship->Hobbits->Merry and work our way down,
+exception: Merry. To see whether Merry can access the Ale, we'd find his
+path in the tree: Fellowship->Hobbits->Merry. Then we'd work our way down,
keeping track of ale-related permissions:
======================= ================ =======================
@@ -278,7 +268,7 @@ the CakePHP installation. While it's useful and stable, we recommend
that you use the database backed ACL solution, mostly because of
its ability to create new ACOs and AROs on the fly. We meant it for
usage in simple applications - and especially for those folks who
-might not be using a database for some reason.
+for some reason might not be using a database.
By default, CakePHP's ACL is database-driven. To enable INI-based
ACL, you'll need to tell CakePHP what system you're using by
@@ -290,7 +280,7 @@ updating the following lines in app/Config/core.php
Configure::write('Acl.classname', 'DbAcl');
Configure::write('Acl.database', 'default');
- // To look like this:
+ // to look like this:
Configure::write('Acl.classname', 'IniAcl');
//Configure::write('Acl.database', 'default');
@@ -299,15 +289,15 @@ The basic idea is that AROs are specified in an INI section that
has three properties: groups, allow, and deny.
-- groups: names of ARO groups this ARO is a member of.
-- allow: names of ACOs this ARO has access to
-- deny: names of ACOs this ARO should be denied access to
+- groups: names of ARO groups of which this ARO is a member
+- allow: names of ACOs to which this ARO has access
+- deny: names of ACOs to which this ARO should be denied access
ACOs are specified in INI sections that only include the allow and
deny properties.
As an example, let's see how the Fellowship ARO structure we've
-been crafting would look like in INI syntax:
+been crafting would look in INI syntax:
::
@@ -359,9 +349,10 @@ been crafting would look like in INI syntax:
[visitors]
allow = salted_pork
-Now that you've got your permissions defined, you can skip along to
-:ref:`the section on checking permissions `
-using the ACL component.
+Now that you've got your permissions defined via the INI mechanism,
+you can skip to :ref:`the section on checking permissions `
+using the ACL component. Alternatively, you can keep reading to see how
+you would define the same permissions using a database ACL.
Defining Permissions: CakePHP's Database ACL
@@ -373,8 +364,8 @@ the (more commonly used) database ACL.
Getting Started
---------------
-The default ACL permissions implementation is database powered.
-CakePHP's database ACL consists of a set of core models, and a console
+The default ACL permissions implementation is powered by a database.
+CakePHP's database ACL consists of a set of core models and a console
application that comes with your CakePHP installation. The models are
used by CakePHP to interact with your database in order to store and
retrieve nodes in tree format. The console application is used to
@@ -451,16 +442,16 @@ trees.
Creating Access Request Objects (AROs) and Access Control Objects (ACOs)
------------------------------------------------------------------------
-In creating new ACL objects (ACOs and AROs), realize that there are
+When creating new ACL objects (ACOs and AROs), realize that there are
two main ways to name and access nodes. The *first* method is to
link an ACL object directly to a record in your database by
-specifying a model name and foreign key value. The *second* method
+specifying a model name and foreign key value. The *second*
can be used when an object has no direct relation to a record in
your database - you can provide a textual alias for the object.
.. note::
- In general, when you're creating a group or higher level object,
+ In general, when you're creating a group or higher-level object,
use an alias. If you're managing access to a specific item or
record in the database, use the model/foreign key method.
@@ -469,8 +460,8 @@ doing so, there are a number of fields you'll want to use when
saving data: ``model``, ``foreign_key``, ``alias``, and
``parent_id``.
-The ``model`` and ``foreign_key`` fields for an ACL object allows
-you to link up the object to its corresponding model record (if
+The ``model`` and ``foreign_key`` fields for an ACL object allow
+you to link the object to its corresponding model record (if
there is one). For example, many AROs will have corresponding User
records in the database. Setting an ARO's ``foreign_key`` to the
User's ID will allow you to link up ARO and User information with a
@@ -479,9 +470,9 @@ associations. Conversely, if you want to manage edit operation on a
specific blog post or recipe listing, you may choose to link an ACO
to that specific model record.
-The ``alias`` for an ACL object is just a human-readable label you
+An ``alias`` is just a human-readable label you
can use to identify an ACL object that has no direct model record
-correlation. Aliases are usually useful in naming user groups or
+correlation. Aliases are generally useful in naming user groups or
ACO collections.
The ``parent_id`` for an ACL object allows you to fill out the tree
@@ -496,24 +487,21 @@ ACL Component in your controller's $components array:
public $components = array('Acl');
-Once we've got that done, let's see what some examples of creating
-these objects might look like. The following code could be placed
-in a controller action somewhere:
+Once we've got that done, let's see some examples of creating
+these objects. The following code could be placed
+in a controller action:
.. note::
While the examples here focus on ARO creation, the same techniques
can be used to create an ACO tree.
-Keeping with our Fellowship setup, let's first create our ARO
-groups. Because our groups won't really have specific records tied
-to them, we'll use aliases to create these ACL objects. What we're
-doing here is from the perspective of a controller action, but
-could be done elsewhere. What we'll cover here is a bit of an
-artificial approach, but you should feel comfortable using these
-techniques to build AROs and ACOs on the fly.
+Remaining with our Fellowship example, let's first create our ARO
+groups. Because they won't have specific records tied
+to them, we'll use aliases to create the ACL objects. Here, we create them
+via a controller action, but we could do it elsewhere.
-This shouldn't be anything drastically new - we're just using
+Our approach shouldn't be drastically new - we're just using
models to save data like we always do:
::
@@ -549,7 +537,7 @@ models to save data like we always do:
// Other action logic goes here...
}
-Once we've got them in there, we can use the ACL console
+Once we've got the groups, we can use the ACL console
application to verify the tree structure.
::
@@ -568,9 +556,9 @@ application to verify the tree structure.
---------------------------------------------------------------
-I suppose it's not much of a tree at this point, but at least we've
+The tree is still simple at this point, but at least we've
got some verification that we've got four top-level nodes. Let's
-add some children to those ARO nodes by adding our specific user
+add some children to those ARO nodes by putting our specific user
AROs under these groups. Every good citizen of Middle Earth has an
account in our new system, so we'll tie these ARO records to
specific model records in our database.
@@ -585,8 +573,8 @@ specific model records in our database.
public function any_action() {
$aro = new Aro();
- // Here are our user records, ready to be linked up to new ARO records
- // This data could come from a model and modified, but we're using static
+ // Here are our user records, ready to be linked to new ARO records.
+ // This data could come from a model and be modified, but we're using static
// arrays here for demonstration purposes.
$users = array(
@@ -703,16 +691,16 @@ little more interesting. Let's give it a try:
Now that we've got our ARO tree setup properly, let's discuss a
possible approach for structuring an ACO tree. While we can
-structure more of an abstract representation of our ACO's, it's
+put together a more abstract representation of our ACO's, it's
often more practical to model an ACO tree after CakePHP's
Controller/Action setup. We've got five main objects we're handling
-in this Fellowship scenario, and the natural setup for that in a
-CakePHP application is a group of models, and ultimately the
-controllers that manipulate them. Past the controllers themselves,
+in this Fellowship scenario. The natural setup for this in a
+CakePHP application consists of a group of models, and ultimately the
+controllers that manipulate them. Beyond the controllers themselves,
we'll want to control access to specific actions in those
controllers.
-Based on that idea, let's set up an ACO tree that will mimic a CakePHP
+Let's set up an ACO tree that will mimic a CakePHP
app setup. Since we have five ACOs, we'll create an ACO tree that
should end up looking something like the following:
@@ -738,7 +726,7 @@ Assigning Permissions
After creating our ACOs and AROs, we can finally assign permissions
between the two groups. This is done using CakePHP's core Acl
-component. Let's continue on with our example.
+component. Let's continue with our example.
Here we'll work with Acl permisions in the context of a controller
action. Let's set up some basic permissions using the AclComponent in
@@ -761,8 +749,19 @@ an action inside our controller.
$this->Acl->deny('warriors/Legolas', 'Weapons', 'delete');
$this->Acl->deny('warriors/Gimli', 'Weapons', 'delete');
- die(print_r('done', 1));
- }
+::
+
+ public function index() {
+ // Allow warriors complete access to weapons
+ // Both these examples use the alias syntax
+ $this->Acl->allow('warriors', 'Weapons');
+
+ // However, the King does not want to let everyone
+ // have unfettered access
+ $this->Acl->deny('warriors/Legolas', 'Weapons', 'delete');
+ $this->Acl->deny('warriors/Gimli', 'Weapons', 'delete');
+
+ die(print_r('done', 1));
}
The first call we make to the AclComponent allows any user under
@@ -780,7 +779,7 @@ it alongside the defaults.
The second set of calls is an attempt to make a more fine-grained
permission decision. We want Aragorn to keep his full-access
-privileges, but deny other warriors in the group the ability to
+privileges, but we want to deny other warriors in the group the ability to
delete Weapons records. We're using the alias syntax to address the
AROs above, but you might want to use the model/foreign key syntax
yourself. What we have above is equivalent to this:
@@ -850,9 +849,9 @@ Let's give it a try inside a controller action:
$result = $this->Acl->check('warriors/Gimli', 'Weapons', 'delete');
}
-The usage here is demonstrational, but hopefully you can see how
-checking like this can be used to decide whether or not to allow
-something to happen, show an error message, or redirect the user to
+The usage here is for demonstration, but this type of checking
+can be used to decide whether to allow an action,
+show an error message, or redirect the user to
a login.
diff --git a/en/core-libraries/components/authentication.rst b/en/core-libraries/components/authentication.rst
index e6a8d92509..13e4f93e83 100644
--- a/en/core-libraries/components/authentication.rst
+++ b/en/core-libraries/components/authentication.rst
@@ -374,7 +374,7 @@ callback of your model using appropriate password hasher class::
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data['User']['password'])) {
- $passwordHasher = new SimplePasswordHasher();
+ $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data['User']['password'] = $passwordHasher->hash(
$this->data['User']['password']
);
diff --git a/en/core-libraries/components/cookie.rst b/en/core-libraries/components/cookie.rst
index 1c6af2ed9e..7813e30c8f 100644
--- a/en/core-libraries/components/cookie.rst
+++ b/en/core-libraries/components/cookie.rst
@@ -7,7 +7,7 @@ The CookieComponent is a wrapper around the native PHP ``setcookie``
method. It also includes a host of delicious icing to make coding
cookies in your controllers very convenient. Before attempting to
use the CookieComponent, you must make sure that 'Cookie' is listed
-in your controllers' $components array.
+in your controller's $components array.
Controller Setup
@@ -25,18 +25,18 @@ allows you to define how the CookieComponent works.
+-----------------+--------------+------------------------------------------------------+
| string $key | null | This string is used to encrypt |
| | | the value written to the cookie. |
-| | | This string should be random and difficult to guess. |
+| | | The string should be random and difficult to guess. |
| | | |
-| | | When using rijndael encryption this value |
+| | | When using rijndael or aes encryption, this value |
| | | must be longer than 32 bytes. |
+-----------------+--------------+------------------------------------------------------+
-| string $domain | '' | The domain name allowed to access the cookie. e.g. |
-| | | Use '.yourdomain.com' to allow access from all your |
-| | | subdomains. |
+| string $domain | '' | The domain name allowed to access the cookie. For |
+| | | example, use '.yourdomain.com' to allow access from |
+| | | all your subdomains. |
+-----------------+--------------+------------------------------------------------------+
| int or string | '5 Days' | The time when your cookie will expire. Integers are |
-| $time | | Interpreted as seconds and a value of 0 is equivalent|
-| | | to a 'session cookie': i.e. the cookie expires when |
+| $time | | interpreted as seconds. A value of 0 is equivalent |
+| | | to a 'session cookie': i.e., the cookie expires when |
| | | the browser is closed. If a string is set, this will |
| | | be interpreted with PHP function strtotime(). You can|
| | | set this directly within the write() method. |
@@ -44,7 +44,7 @@ allows you to define how the CookieComponent works.
| string $path | '/' | The server path on which the cookie will be applied. |
| | | If $path is set to '/foo/', the cookie will |
| | | only be available within the /foo/ directory and all |
-| | | sub-directories such as /foo/bar/ of your domain. The|
+| | | sub-directories of your domain, such as /foo/bar. The|
| | | default value is the entire domain. You can set this |
| | | directly within the write() method. |
+-----------------+--------------+------------------------------------------------------+
@@ -65,6 +65,7 @@ a secure connection, is available on the path
'/bakers/preferences/', expires in one hour and is HTTP only::
public $components = array('Cookie');
+
public function beforeFilter() {
parent::beforeFilter();
$this->Cookie->name = 'baker_id';
@@ -74,6 +75,7 @@ a secure connection, is available on the path
$this->Cookie->secure = true; // i.e. only sent if using secure HTTPS
$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
$this->Cookie->httpOnly = true;
+ $this->Cookie->type('aes');
}
Next, let's look at how to use the different methods of the Cookie
@@ -86,13 +88,13 @@ The CookieComponent offers a number of methods for working with Cookies.
.. php:method:: write(mixed $key, mixed $value = null, boolean $encrypt = true, mixed $expires = null)
- The write() method is the heart of cookie component, $key is the
+ The write() method is the heart of the cookie component. $key is the
cookie variable name you want, and the $value is the information to
be stored::
$this->Cookie->write('name', 'Larry');
- You can also group your variables by supplying dot notation in the
+ You can also group your variables by using dot notation in the
key parameter::
$this->Cookie->write('User.name', 'Larry');
@@ -106,18 +108,15 @@ The CookieComponent offers a number of methods for working with Cookies.
);
All values in the cookie are encrypted by default. If you want to
- store the values as plain-text, set the third parameter of the
- write() method to false. The encryption performed on cookie values
- is fairly uncomplicated encryption system. It uses
- ``Security.salt`` and a predefined Configure class var
- ``Security.cipherSeed`` to encrypt values. To make your cookies
- more secure you should change ``Security.cipherSeed`` in
- app/Config/core.php to ensure a better encryption.::
+ store the values as plain text, set the third parameter of the
+ write() method to false. You should remember to set
+ the encryption mode to 'aes' to ensure that values are securely
+ encrypted::
$this->Cookie->write('name', 'Larry', false);
The last parameter to write is $expires – the number of seconds
- before your cookie will expire. For convenience, this parameter can
+ until your cookie will expire. For convenience, this parameter can
also be passed as a string that the php strtotime() function
understands::
@@ -137,7 +136,7 @@ The CookieComponent offers a number of methods for working with Cookies.
echo $this->Cookie->read('User.name');
// To get the variables which you had grouped
- // using the dot notation as an array use something like
+ // using the dot notation as an array use the following
$this->Cookie->read('User');
// this outputs something like array('name' => 'Larry', 'role' => 'Lead')
@@ -146,7 +145,7 @@ The CookieComponent offers a number of methods for working with Cookies.
:param string $key: The key to check.
- Used to check if a key/path exists and has not-null value.
+ Used to check whether a key/path exists and has a non-null value.
.. versionadded:: 2.3
``CookieComponent::check()`` was added in 2.3
@@ -159,7 +158,7 @@ The CookieComponent offers a number of methods for working with Cookies.
// Delete a variable
$this->Cookie->delete('bar');
- // Delete the cookie variable bar, but not all under foo
+ // Delete the cookie variable bar, but not everything under foo
$this->Cookie->delete('foo.bar');
.. php:method:: destroy()
@@ -168,13 +167,16 @@ The CookieComponent offers a number of methods for working with Cookies.
.. php:method:: type($type)
- Allows you to change the encryption scheme. By default the 'cipher' scheme
- is used. However, you should use the 'rijndael' scheme for improved
- security.
+ Allows you to change the encryption scheme. By default the 'cipher' scheme is used for
+ backwards compatibility. However, you should always use either the 'rijndael' or
+ 'aes' schemes.
.. versionchanged:: 2.2
The 'rijndael' type was added.
+ .. versionadded:: 2.5
+ The 'aes' type was added.
+
.. meta::
:title lang=en: Cookie
diff --git a/en/core-libraries/components/security-component.rst b/en/core-libraries/components/security-component.rst
index 3e0eb1ac44..44aad98499 100644
--- a/en/core-libraries/components/security-component.rst
+++ b/en/core-libraries/components/security-component.rst
@@ -329,12 +329,13 @@ some reason. If you do want to disable this feature, you can set
components array. By default CSRF protection is enabled, and configured to use
one-use tokens.
-Disabling Security Component For Specific Actions
-=================================================
+Disabling CSRF and Post Data Validation For Specific Actions
+============================================================
There may be cases where you want to disable all security checks for an action (ex. AJAX requests).
You may "unlock" these actions by listing them in ``$this->Security->unlockedActions`` in your
-``beforeFilter``.
+``beforeFilter``. The ``unlockedActions`` property will **not** effect other
+features of ``SecurityComponent``.
.. versionadded:: 2.3
diff --git a/en/core-libraries/components/sessions.rst b/en/core-libraries/components/sessions.rst
index 0dd3633ee1..fbbed0db9d 100644
--- a/en/core-libraries/components/sessions.rst
+++ b/en/core-libraries/components/sessions.rst
@@ -107,9 +107,9 @@ Creating notification messages
You can use the additional parameters of ``setFlash()`` to create
- different kinds of flash messages. For example, error and positive
- notifications may look differently. CakePHP gives you a way to do that.
- Using the ``$key`` parameter you can store multiple messages, which can be
+ different kinds of flash messages. For example, you may want error and positive
+ notifications to look different from each other. CakePHP gives you a way to do that.
+ Using the ``$key`` parameter, you can store multiple messages, which can be
output separately::
// set a bad message.
@@ -124,9 +124,9 @@ Creating notification messages
echo $this->Session->flash('good');
echo $this->Session->flash('bad');
- The ``$element`` parameter allows you to control which element
- (located in ``/app/View/Elements``) should be used to render the
- message in. In the element the message is available as ``$message``.
+ The ``$element`` parameter allows you to control the element
+ (located in ``/app/View/Elements``) in which the message should be
+ rendered. Within the element, the message is available as ``$message``.
First we set the flash in our controller::
$this->Session->setFlash('Something custom!', 'flash_custom');
@@ -137,9 +137,9 @@ Creating notification messages
``$params`` allows you to pass additional view variables to the
- rendered layout. Parameters can be passed affecting the rendered div, for
- example adding "class" in the $params array will apply a class to the
- ``div`` output using ``$this->Session->flash()`` in your layout or view.::
+ rendered layout. Parameters can be passed affecting the rendered div. For
+ example, adding "class" in the $params array will apply a class to the
+ ``div`` output using ``$this->Session->flash()`` in your layout or view::
$this->Session->setFlash(
'Example message text',
@@ -163,8 +163,8 @@ Creating notification messages
);
.. note::
- By default CakePHP does not HTML escape flash messages. If you are using
- any request or user data in your flash messages you should escape it
+ By default CakePHP does not escape the HTML in flash messages. If you are using
+ any request or user data in your flash messages, you should escape it
with :php:func:`h` when formatting your messages.
.. meta::
diff --git a/en/core-libraries/events.rst b/en/core-libraries/events.rst
index 3e74bfcddb..de99bd6e9d 100644
--- a/en/core-libraries/events.rst
+++ b/en/core-libraries/events.rst
@@ -92,11 +92,9 @@ In addition to instance level event managers, CakePHP provides a global event
manager that allows you to listen to any event fired in an application. This
is useful when attaching listeners to a specific instance might be cumbersome or
difficult. The global manager is a singleton instance of
-:php:class:`CakeEventManager` that receives every event **before** the instance
-managers do. In addition to receiving events first, the global manager also
-maintains a separate priority stack for listeners. Once an event has been
-dispatched to the global manager, it will be dispatched to the instance level
-manager. You can access the global manager using a static method::
+:php:class:`CakeEventManager`. When an event is
+dispatched, it will be dispatched to the both the global and instance level
+listeners in priority order. You can access the global manager using a static method::
// In any configuration file or piece of code that executes before the event
App::uses('CakeEventManager', 'Event');
@@ -112,6 +110,12 @@ order to prevent some bugs. Remember that with the flexibility of using the
global manager, some additional complexity is incurred.
+.. versionchanged:: 2.5
+
+ Prior to 2.5, listeners on the global manager were kept in a separate list
+ and fired **before** instance listeners are.
+
+
Dispatching events
==================
diff --git a/en/core-libraries/global-constants-and-functions.rst b/en/core-libraries/global-constants-and-functions.rst
index f4d26f98d3..ef05f20c88 100644
--- a/en/core-libraries/global-constants-and-functions.rst
+++ b/en/core-libraries/global-constants-and-functions.rst
@@ -38,16 +38,16 @@ such as debugging and translating content.
.. php:function:: __c(string $msg, integer $category, mixed $args = null)
- Note that the category must be specified with a numeric value, instead of
- the constant name. The values are:
+ Note that the category must be specified with an I18n class constant, instead of
+ only the constant name. The values are:
- - 0 - LC_ALL
- - 1 - LC_COLLATE
- - 2 - LC_CTYPE
- - 3 - LC_MONETARY
- - 4 - LC_NUMERIC
- - 5 - LC_TIME
- - 6 - LC_MESSAGES
+ - I18n::LC_ALL - LC_ALL
+ - I18n::LC_COLLATE - LC_COLLATE
+ - I18n::LC_CTYPE - LC_CTYPE
+ - I18n::LC_MONETARY - LC_MONETARY
+ - I18n::LC_NUMERIC - LC_NUMERIC
+ - I18n::LC_TIME - LC_TIME
+ - I18n::LC_MESSAGES - LC_MESSAGES
.. php:function:: __d(string $domain, string $msg, mixed $args = null)
@@ -61,16 +61,16 @@ such as debugging and translating content.
Allows you to override the current domain for a single message lookup. It
also allows you to specify a category.
- Note that the category must be specified with a numeric value, instead of
- the constant name. The values are:
+ Note that the category must be specified with an I18n class constant, instead of
+ only the constant name. The values are:
- - 0 - LC_ALL
- - 1 - LC_COLLATE
- - 2 - LC_CTYPE
- - 3 - LC_MONETARY
- - 4 - LC_NUMERIC
- - 5 - LC_TIME
- - 6 - LC_MESSAGES
+ - I18n::LC_ALL - LC_ALL
+ - I18n::LC_COLLATE - LC_COLLATE
+ - I18n::LC_CTYPE - LC_CTYPE
+ - I18n::LC_MONETARY - LC_MONETARY
+ - I18n::LC_NUMERIC - LC_NUMERIC
+ - I18n::LC_TIME - LC_TIME
+ - I18n::LC_MESSAGES - LC_MESSAGES
.. php:function:: __dcn(string $domain, string $singular, string $plural, integer $count, integer $category, mixed $args = null)
@@ -79,16 +79,16 @@ such as debugging and translating content.
form of message identified by $singular and $plural for count $count from
domain $domain.
- Note that the category must be specified with a numeric value, instead of
- the constant name. The values are:
+ Note that the category must be specified with an I18n class constant, instead of
+ only the constant name. The values are:
- - 0 - LC_ALL
- - 1 - LC_COLLATE
- - 2 - LC_CTYPE
- - 3 - LC_MONETARY
- - 4 - LC_NUMERIC
- - 5 - LC_TIME
- - 6 - LC_MESSAGES
+ - I18n::LC_ALL - LC_ALL
+ - I18n::LC_COLLATE - LC_COLLATE
+ - I18n::LC_CTYPE - LC_CTYPE
+ - I18n::LC_MONETARY - LC_MONETARY
+ - I18n::LC_NUMERIC - LC_NUMERIC
+ - I18n::LC_TIME - LC_TIME
+ - I18n::LC_MESSAGES - LC_MESSAGES
.. php:function:: __dn(string $domain, string $singular, string $plural, integer $count, mixed $args = null)
diff --git a/en/core-libraries/helpers/form.rst b/en/core-libraries/helpers/form.rst
index 7d64e3c5bc..ba2a074a50 100644
--- a/en/core-libraries/helpers/form.rst
+++ b/en/core-libraries/helpers/form.rst
@@ -224,7 +224,7 @@ There are a number of options for create():
Closing the Form
================
-.. php:method:: end($options = null)
+.. php:method:: end($options = null, $secureAttributes = array())
The FormHelper includes an ``end()`` method that completes the
form. Often, ``end()`` only outputs a closing form tag, but
@@ -278,6 +278,9 @@ Closing the Form
If you are using :php:class:`SecurityComponent` in your application you
should always end your forms with ``end()``.
+ .. versionchanged:: 2.5
+ The ``$secureAttributes`` parameter was added in 2.5.
+
.. _automagic-form-elements:
Creating form elements
@@ -319,6 +322,8 @@ field. Internally ``input()`` delegates to other methods in FormHelper.
day, month, year, hour, minute, and meridian selects
time
hour, minute, and meridian selects
+ binary
+ file
The ``$options`` parameter allows you to customize how ``input()`` works,
and finely control what is generated.
@@ -329,6 +334,9 @@ field. Internally ``input()`` delegates to other methods in FormHelper.
been loaded during this request. Or be directly associated to the
model supplied to :php:meth:`~FormHelper::create()`.
+ .. versionadded:: 2.5
+ The binary type now maps to a file input.
+
.. versionadded:: 2.3
.. _html5-required:
@@ -407,10 +415,10 @@ field. Internally ``input()`` delegates to other methods in FormHelper.
Try to avoid using `FormHelper::input()` to generate submit buttons. Use
:php:meth:`FormHelper::submit()` instead.
-.. php:method:: inputs(mixed $fields = null, array $blacklist = null)
+.. php:method:: inputs(mixed $fields = null, array $blacklist = null, $options = array())
- Generate a set of inputs for ``$fields``. If $fields is null the current model
- will be used.
+ Generate a set of inputs for ``$fields``. If ``$fields`` is null all fields,
+ except of those defined in ``$blacklist``, of the current model will be used.
In addition to controller fields output, ``$fields`` can be used to control
legend and fieldset rendering with the ``fieldset`` and ``legend`` keys.
@@ -1153,7 +1161,7 @@ Ex: name=data[User][username], id=UserUsername
* ``$attributes['disabled']`` Setting this to ``true`` or ``'disabled'``
will disable all of the generated radio buttons.
- * ``$attributes['legend']`` Radio elements are wrapped with a label and
+ * ``$attributes['legend']`` Radio elements are wrapped with a legend and
fieldset by default. Set ``$attributes['legend']`` to false to remove
them.::
diff --git a/en/core-libraries/helpers/html.rst b/en/core-libraries/helpers/html.rst
index 6a676f9991..781ef426ef 100644
--- a/en/core-libraries/helpers/html.rst
+++ b/en/core-libraries/helpers/html.rst
@@ -1076,7 +1076,7 @@ Creating breadcrumb trails with HtmlHelper
breadcrumb trails on each of the pages::
$this->Html->addCrumb('Users', '/users');
- $this->Html->addCrumb('Add User', '/users/add');
+ $this->Html->addCrumb('Add User', array('controller' => 'users', 'action' => 'add'));
This will add the output of "**Home > Users > Add User**" in your
layout where getCrumbs was added.
@@ -1085,7 +1085,7 @@ Creating breadcrumb trails with HtmlHelper
:param array $options: An array of :term:`html attributes` for the
containing ``
`` element. Can also contain the 'separator',
- 'firstClass' and 'lastClass' options.
+ 'firstClass', 'lastClass' and 'escape' options.
:param string|array $startText: The text or element that precedes the ul.
Returns breadcrumbs as a (x)html list.
@@ -1102,6 +1102,9 @@ Creating breadcrumb trails with HtmlHelper
.. versionchanged:: 2.3
The 'separator', 'firstClass' and 'lastClass' options were added.
+
+ .. versionchanged:: 2.5
+ The 'escape' option was added.
.. meta::
diff --git a/en/core-libraries/helpers/js.rst b/en/core-libraries/helpers/js.rst
index 167fb22839..5fd274f38f 100644
--- a/en/core-libraries/helpers/js.rst
+++ b/en/core-libraries/helpers/js.rst
@@ -833,7 +833,7 @@ indicator effects yourself:
-
+ fetch('content'); ?>
Html->image(
diff --git a/en/core-libraries/helpers/paginator.rst b/en/core-libraries/helpers/paginator.rst
index 6f916c01ae..1843dd1c32 100644
--- a/en/core-libraries/helpers/paginator.rst
+++ b/en/core-libraries/helpers/paginator.rst
@@ -31,6 +31,12 @@ Accepted keys for ``$options``:
* ``escape`` Whether you want the contents HTML entity encoded, defaults to
true.
* ``model`` The model to use, defaults to :php:meth:`PaginatorHelper::defaultModel()`.
+* ``direction`` The default direction to use when this link isn't active.
+* ``lock`` Lock direction. Will only use the default direction then, defaults to false.
+
+ .. versionadded:: 2.5
+ You can now set the lock option to true in order to lock the sorting direction into the
+ specified direction.
Assuming you are paginating some posts, and are on page one::
@@ -79,6 +85,10 @@ Output:
User Id
+The lock option can be used to lock sorting into the specified direction::
+
+ echo $this->Paginator->sort('user_id', null, array('direction' => 'asc', 'lock' => true));
+
.. php:method:: sortDir(string $model = null, mixed $options = array())
Gets the current direction the recordset is sorted.
diff --git a/en/core-libraries/helpers/rss.rst b/en/core-libraries/helpers/rss.rst
index 8189855457..cfefb5477b 100644
--- a/en/core-libraries/helpers/rss.rst
+++ b/en/core-libraries/helpers/rss.rst
@@ -90,9 +90,9 @@ An Rss layout is very simple, put the following contents in
$channelData = array();
}
if (!isset($channelData['title'])) {
- $channelData['title'] = $title_for_layout;
+ $channelData['title'] = $this->fetch('title');
}
- $channel = $this->Rss->channel(array(), $channelData, $content_for_layout);
+ $channel = $this->Rss->channel(array(), $channelData, $this->fetch('content'));
echo $this->Rss->document($documentData, $channel);
It doesn't look like much but thanks to the power in the ``RssHelper``
diff --git a/en/core-libraries/helpers/session.rst b/en/core-libraries/helpers/session.rst
index 103a709f25..295d0d175b 100644
--- a/en/core-libraries/helpers/session.rst
+++ b/en/core-libraries/helpers/session.rst
@@ -4,7 +4,7 @@ SessionHelper
.. php:class:: SessionHelper(View $view, array $settings = array())
As a natural counterpart to the Session Component, the Session
-Helper replicates most of the components functionality and makes it
+Helper replicates most of the component's functionality and makes it
available in your view.
The major difference between the Session Helper and the Session
@@ -34,7 +34,7 @@ used.
:rtype: boolean
- Check to see if a key is in the Session. Returns a boolean on the
+ Check to see whether a key is in the Session. Returns a boolean representing the
key's existence.
.. php:method:: error()
@@ -47,7 +47,7 @@ used.
:rtype: boolean
- Used to check is a session is valid in a view.
+ Used to check whether a session is valid in a view.
Displaying notifications or flash messages
==========================================
@@ -56,15 +56,15 @@ Displaying notifications or flash messages
:rtype: string
- As explained in :ref:`creating-notification-messages` you can
+ As explained in :ref:`creating-notification-messages`, you can
create one-time notifications for feedback. After creating messages
- with :php:meth:`SessionComponent::setFlash()` you will want to
+ with :php:meth:`SessionComponent::setFlash()`, you will want to
display them. Once a message is displayed, it will be removed and
not displayed again::
echo $this->Session->flash();
- The above will output a simple message, with the following HTML:
+ The above will output a simple message with the following HTML:
.. code-block:: html
@@ -72,15 +72,15 @@ Displaying notifications or flash messages
Your stuff has been saved.
- As with the component method you can set additional properties
- and customize which element is used. In the controller you might
+ As with the component method, you can set additional properties
+ and customize which element is used. In the controller, you might
have code like::
// in a controller
$this->Session->setFlash('The user could not be deleted.');
When outputting this message, you can choose the element used to display
- this message::
+ the message::
// in a layout.
echo $this->Session->flash('flash', array('element' => 'failure'));
@@ -88,8 +88,7 @@ Displaying notifications or flash messages
This would use ``View/Elements/failure.ctp`` to render the message. The
message text would be available as ``$message`` in the element.
- Inside the failure element file would be something like
- this:
+ The failure element would contain something like this:
.. code-block:: php
@@ -98,7 +97,7 @@ Displaying notifications or flash messages
You can also pass additional parameters into the ``flash()`` method, which
- allow you to generate customized messages::
+ allows you to generate customized messages::
// In the controller
$this->Session->setFlash('Thanks for your payment.');
@@ -115,11 +114,11 @@ Displaying notifications or flash messages
.. note::
- By default CakePHP does not HTML escape flash messages. If you are using
- any request or user data in your flash messages you should escape it
+ By default, CakePHP does not escape the HTML in flash messages. If you are using
+ any request or user data in your flash messages, you should escape it
with :php:func:`h` when formatting your messages.
.. meta::
:title lang=en: SessionHelper
- :description lang=en: As a natural counterpart to the Session Component, the Session Helper replicates most of the components functionality and makes it available in your view.
+ :description lang=en: As a natural counterpart to the Session Component, the Session Helper replicates most of the component's functionality and makes it available in your view.
:keywords lang=en: session helper,flash messages,session flash,session read,session check
diff --git a/en/core-libraries/internationalization-and-localization.rst b/en/core-libraries/internationalization-and-localization.rst
index 07018b5949..045cf5c25e 100644
--- a/en/core-libraries/internationalization-and-localization.rst
+++ b/en/core-libraries/internationalization-and-localization.rst
@@ -90,7 +90,7 @@ should consider implementing a different solution. e.g.::
// App Controller Code.
public function beforeFilter() {
$locale = Configure::read('Config.language');
- if ($locale && file_exists(VIEWS . $locale . DS . $this->viewPath)) {
+ if ($locale && file_exists(APP . 'View' . DS . $locale . DS . $this->viewPath)) {
// e.g. use /app/View/fra/Pages/tos.ctp instead of /app/View/Pages/tos.ctp
$this->viewPath = $locale . DS . $this->viewPath;
}
diff --git a/en/core-libraries/logging.rst b/en/core-libraries/logging.rst
index a8e41a562d..72c9c4687c 100644
--- a/en/core-libraries/logging.rst
+++ b/en/core-libraries/logging.rst
@@ -50,10 +50,11 @@ When configuring a log stream the ``engine`` parameter is used to
locate and load the log handler. All of the other configuration
properties are passed to the log stream's constructor as an array.::
- App::uses('CakeLogInterface', 'Log');
+ App::uses('BaseLog', 'Log/Engine');
- class DatabaseLog implements CakeLogInterface {
+ class DatabaseLog extends BaseLog {
public function __construct($options = array()) {
+ parent::__construct($options);
// ...
}
@@ -62,12 +63,18 @@ properties are passed to the log stream's constructor as an array.::
}
}
-CakePHP has no requirements for Log streams other than that they
-must implement a ``write`` method. This write method must take two
-parameters ``$type, $message`` in that order. ``$type`` is the
-string type of the logged message, core values are ``error``,
-``warning``, ``info`` and ``debug``. In addition you can define
-your own types by using them when you call ``CakeLog::write``.
+While CakePHP has no requirements for Log streams other than that they
+must implement a ``write`` method, extending the ``BaseLog`` class has a few
+benefits:
+
+- It automatically handles the scope and type argument casting.
+- It implements the ``config()`` method which is required to make scoped logging
+ work.
+
+Each logger's write method must take two parameters ``$type, $message`` in that
+order. ``$type`` is the string type of the logged message, core values are
+``error``, ``warning``, ``info`` and ``debug``. In addition you can define your
+own types by using them when you call ``CakeLog::write``.
.. _file-log:
@@ -76,9 +83,9 @@ your own types by using them when you call ``CakeLog::write``.
As of 2.4 ``FileLog`` engine takes a few new options:
* ``size`` Used to implement basic log file rotation. If log file size
- reaches specified size the existing file is renamed by appending timestamp
- to filename and new log file is created. Can be integer bytes value or
- human reabable string values like '10MB', '100KB' etc. Defaults to 10MB.
+ reaches specified size the existing file is renamed by appending timestamp
+ to filename and new log file is created. Can be integer bytes value or
+ human reabable string values like '10MB', '100KB' etc. Defaults to 10MB.
* ``rotate`` Log files are rotated specified times before being removed.
If value is 0, old versions are removed rather then rotated. Defaults to 10.
* ``mask`` Set the file permissions for created files. If left empty the default
@@ -86,7 +93,7 @@ As of 2.4 ``FileLog`` engine takes a few new options:
.. warning::
- Prior to 2.4 you had to include the suffix ``Log``` in your configuration
+ Prior to 2.4 you had to include the suffix ``Log`` in your configuration
(``LoggingPack.DatabaseLog``). This is now not necessary anymore.
If you have been using 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
@@ -181,9 +188,7 @@ a completely different storage for your logs.
Using syslog is pretty much like using the default FileLog engine, you just need
to specify `Syslog` as the engine to be used for logging. The following
configuration snippet will replace the default logger with syslog, this should
-be done in the `bootstrap.php` file.
-
-::
+be done in the `bootstrap.php` file::
CakeLog::config('default', array(
'engine' => 'Syslog'
@@ -223,11 +228,19 @@ CakeLog::write()::
$this->log("Something did not work!", 'debug');
All configured log streams are written to sequentially each time
-:php:meth:`CakeLog::write()` is called. You do not need to configure a
-stream in order to use logging. If no streams are configured when
-the log is written to, a ``default`` stream using the core
-``FileLog`` class will be configured to output into
-``app/tmp/logs/`` just as CakeLog did in previous versions.
+:php:meth:`CakeLog::write()` is called.
+
+.. versionchanged:: 2.5
+
+CakeLog does not auto-configure itself anymore. As a result log files will not be
+auto-created anymore if no stream is listening.
+Make sure you got at least one ``default`` stream set up if you want to
+listen to all types and levels. Usually, you can just set the core ``FileLog`` class
+to output into ``app/tmp/logs/``::
+
+ CakeLog::config('default', array(
+ 'engine' => 'File'
+ ));
.. _logging-scopes:
@@ -268,8 +281,11 @@ message. For example::
CakeLog::warning('This gets written to both shops and payments streams', 'payments');
CakeLog::warning('This gets written to both shops and payments streams', 'unknown');
-In order for scopes to work correctly, you **must** define the accepted
-``types`` on all loggers you want to use scopes with.
+In order for scopes to work, you **must** do a few things:
+
+#. Define the accepted ``types`` on loggers that use scopes.
+#. Loggers using scopes must implement a ``config()`` method. Extending the
+ ``BaseLog`` class is the easiest way to get a compatible method.
CakeLog API
===========
diff --git a/en/core-utility-libraries/file-folder.rst b/en/core-utility-libraries/file-folder.rst
index 42616d2dbd..e5039986de 100644
--- a/en/core-utility-libraries/file-folder.rst
+++ b/en/core-utility-libraries/file-folder.rst
@@ -68,10 +68,18 @@ Folder API
Returns $path with $element added, with correct slash in-between::
- copy(array(
- 'from' => '/path/to/copy/from', // will cause a cd() to occur
'to' => '/path/to/new/folder',
+ 'from' => '/path/to/copy/from', // will cause a cd() to occur
'mode' => 0755,
'skip' => array('skip-me.php', '.git'),
- 'scheme' => Folder::SKIP // Skip directories/files that already exist
+ 'scheme' => Folder::SKIP // Skip directories/files that already exist.
));
There are 3 supported schemes:
@@ -558,6 +566,20 @@ File API
Get the file's mimetype, returns false on failure.
+
+.. php:method:: replaceText( $search, $replace )
+
+ :rtype: boolean
+
+ Replaces text in a file. Returns false on failure and true on success.
+
+ .. versionadded::
+ 2.5 ``File::replaceText()``
+
+.. todo::
+
+ Better explain how to use each method with both classes.
+
.. meta::
:title lang=en: Folder & File
:description lang=en: The Folder and File utilities are convenience classes to help you read, write, and append to files; list files within a folder and other common directory related tasks.
diff --git a/en/core-utility-libraries/hash.rst b/en/core-utility-libraries/hash.rst
index fdcfc0ba11..c58d732813 100644
--- a/en/core-utility-libraries/hash.rst
+++ b/en/core-utility-libraries/hash.rst
@@ -41,9 +41,9 @@ Expression Types
+--------------------------------+--------------------------------------------+
All expression elements are supported by all methods. In addition to expression
-elements, you can use attribute matching with certain methods. They are ``extract()``,
-``combine()``, ``format()``, ``check()``, ``map()``, ``reduce()``,
-``apply()``, ``sort()`` and ``nest()``.
+elements, you can use attribute matching with certain methods. They are ``extract()``,
+``combine()``, ``format()``, ``check()``, ``map()``, ``reduce()``,
+``apply()``, ``sort()``, ``insert()``, ``remove()`` and ``nest()``.
Attribute Matching Types
------------------------
@@ -71,6 +71,9 @@ Attribute Matching Types
| | the regular expression inside ``...``. |
+--------------------------------+--------------------------------------------+
+.. versionchanged:: 2.5
+ Matcher support was added to ``insert()`` and ``remove()``.
+
.. php:staticmethod:: get(array $data, $path)
:rtype: mixed
@@ -99,8 +102,7 @@ Attribute Matching Types
:rtype: array
- Inserts $values into an array as defined by $path. This method **only** supports
- the expression types of :ref:`hash-path-syntax`::
+ Inserts $data into an array as defined by ``$path``::
$a = array(
'pages' => array('name' => 'page')
@@ -125,12 +127,15 @@ Attribute Matching Types
$users = $this->User->find('all');
$users = Hash::insert($users, '{n}.User.new', 'value');
+ .. versionchanged:: 2.5
+ As of 2.5.0 attribute matching expressions work with insert().
+
+
.. php:staticmethod:: remove(array $data, $path = null)
:rtype: array
- Removes all elements from an array that match $path. This method **only** supports
- the expression types of :ref:`hash-path-syntax`::
+ Removes all elements from an array that match $path.::
$a = array(
'pages' => array('name' => 'page'),
@@ -150,6 +155,9 @@ Attribute Matching Types
Using ``{n}`` and ``{s}`` will allow you to remove multiple values at once.
+ .. versionchanged:: 2.5
+ As of 2.5.0 attribute matching expressions work with remove()
+
.. php:staticmethod:: combine(array $data, $keyPath = null, $valuePath = null, $groupPath = null)
:rtype: array
@@ -615,7 +623,15 @@ Attribute Matching Types
Creates a new array, by extracting $path, and mapping $function
across the results. You can use both expression and matching elements with
- this method.
+ this method::
+
+ //call the noop function $this->noop() on every element of $data
+ $result = Hash::map($data, "{n}", array($this, 'noop'));
+
+ function noop($array) {
+ //do stuff to array and return the result
+ return $array;
+ }
.. php:staticmethod:: reduce(array $data, $path, $function)
diff --git a/en/core-utility-libraries/httpsocket.rst b/en/core-utility-libraries/httpsocket.rst
index 427ac55a22..d0711703f1 100644
--- a/en/core-utility-libraries/httpsocket.rst
+++ b/en/core-utility-libraries/httpsocket.rst
@@ -63,7 +63,7 @@ HTTP methods.
.. php:method:: delete($uri, $query, $request)
- The put method makes a simple HTTP PUT request returning the
+ The delete method makes a simple HTTP DELETE request returning the
results.
The parameters for the ``delete`` method is the same as the
diff --git a/en/core-utility-libraries/number.rst b/en/core-utility-libraries/number.rst
index 6500bb27af..47ae7d45e2 100644
--- a/en/core-utility-libraries/number.rst
+++ b/en/core-utility-libraries/number.rst
@@ -136,34 +136,35 @@ automatically echo the output into the view.
currency formats easier::
// called as NumberHelper
- $this->Number->addFormat('BRR', array('before' => 'R$ '));
+ $this->Number->addFormat('BRL', array('before' => 'R$', 'thousands' => '.', 'decimals' => ','));
// called as CakeNumber
App::uses('CakeNumber', 'Utility');
- CakeNumber::addFormat('BRR', array('before' => 'R$ '));
+ CakeNumber::addFormat('BRL', array('before' => 'R$', 'thousands' => '.', 'decimals' => ','));
- You can now use `BRR` as a short form when formatting currency amounts::
+ You can now use `BRL` as a short form when formatting currency amounts::
// called as NumberHelper
- echo $this->Number->currency($value, 'BRR');
+ echo $this->Number->currency($value, 'BRL');
// called as CakeNumber
App::uses('CakeNumber', 'Utility');
- echo CakeNumber::currency($value, 'BRR');
+ echo CakeNumber::currency($value, 'BRL');
Added formats are merged with the following defaults::
array(
'wholeSymbol' => '',
'wholePosition' => 'before',
- 'fractionSymbol' => '',
+ 'fractionSymbol' => false,
'fractionPosition' => 'after',
'zero' => 0,
'places' => 2,
'thousands' => ',',
'decimals' => '.',
'negative' => '()',
- 'escape' => true
+ 'escape' => true,
+ 'fractionExponent' => 2
)
.. php:method:: precision(mixed $number, int $precision = 3)
diff --git a/en/core-utility-libraries/security.rst b/en/core-utility-libraries/security.rst
index b5e4194b06..7125df66e9 100644
--- a/en/core-utility-libraries/security.rst
+++ b/en/core-utility-libraries/security.rst
@@ -22,8 +22,10 @@ Security API
// Later decrypt your text
$nosecret = Security::cipher($secret, 'my_key');
- ``cipher()`` uses a **weak** XOR cipher and should **not** be used for
- important or sensitive data.
+ .. warning::
+
+ ``cipher()`` uses a **weak** XOR cipher and should **not** be used.
+ It is only included for backwards compatibility.
.. php:staticmethod:: rijndael($text, $key, $mode)
@@ -49,6 +51,51 @@ Security API
.. versionadded:: 2.2
``Security::rijndael()`` was added in 2.2.
+.. php:staticmethod:: encrypt($text, $key, $hmacSalt = null)
+
+ :param string $plain: The value to encrypt.
+ :param string $key: The 256 bit/32 byte key to use as a cipher key.
+ :param string $hmacSalt: The salt to use for the HMAC process. Leave null to use Security.salt.
+
+ Encrypt ``$text`` using AES-256. The ``$key`` should be a value with a
+ lots of variance in the data much like a good password. The returned result
+ will be the encrypted value with an HMAC checksum.
+
+ This method should **never** be used to store passwords. Instead you should
+ use the one way hashing methods provided by :php:meth:`~Security::hash()`.
+ An example use would be::
+
+ // Assuming key is stored somewhere it can be re-used for
+ // decryption later.
+ $key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
+ $result = Security::encrypt($value, $key);
+
+ Encrypted values can be decrypted using :php:meth:`Security::decrypt()`.
+
+ .. versionadded:: 2.5
+
+.. php:staticmethod:: decrypt($cipher, $key, $hmacSalt = null)
+
+ :param string $cipher: The ciphertext to decrypt.
+ :param string $key: The 256 bit/32 byte key to use as a cipher key.
+ :param string $hmacSalt: The salt to use for the HMAC process. Leave null to use Security.salt.
+
+ Decrypt a previously encrypted value. The ``$key`` and ``$hmacSalt``
+ parameters must match the values used to encrypt or decryption will fail. An
+ example use would be::
+
+ // Assuming key is stored somewhere it can be re-used for
+ // decryption later.
+ $key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
+
+ $cipher = $user['User']['secrets'];
+ $result = Security::decrypt($cipher, $key);
+
+ If the value cannot be decrypted due to changes in the key or HMAC salt
+ ``false`` will be returned.
+
+ .. versionadded:: 2.5
+
.. php:staticmethod:: generateAuthKey( )
:rtype: string
@@ -101,16 +148,6 @@ Security API
.. versionchanged:: 2.3
Support for bcrypt was added in 2.3
-
-.. php:staticmethod:: inactiveMins( )
-
- :rtype: integer
-
- Get allowed minutes of inactivity based on security level.::
-
- $mins = Security::inactiveMins();
- // If your config Security.level is set to 'medium' then $mins will equal 100
-
.. php:staticmethod:: setHash( $hash )
:rtype: void
diff --git a/en/core-utility-libraries/set.rst b/en/core-utility-libraries/set.rst
index 3a14a8c80b..5ff721ca7b 100644
--- a/en/core-utility-libraries/set.rst
+++ b/en/core-utility-libraries/set.rst
@@ -115,7 +115,7 @@ available.
.. php:staticmethod:: classicExtract($data, $path = null)
- :rtype: array
+ :rtype: mixed
Gets a value from an array or object that is contained in a given
path using an array path syntax, i.e.:
@@ -705,7 +705,7 @@ available.
.. php:staticmethod:: extract($path, $data = null, $options = array())
- :rtype: array
+ :rtype: mixed
Set::extract uses basic XPath 2.0 syntax to return subsets of your
data from a find or a find all. This function allows you to
@@ -763,7 +763,7 @@ available.
in ``/lib/Cake/Test/Case/Utility/SetTest.php``.
-.. php:staticmethod:: filter($var, $isArray = null)
+.. php:staticmethod:: filter($var)
:rtype: array
diff --git a/en/core-utility-libraries/xml.rst b/en/core-utility-libraries/xml.rst
index 327fd33bb5..9ce2f253ae 100644
--- a/en/core-utility-libraries/xml.rst
+++ b/en/core-utility-libraries/xml.rst
@@ -19,6 +19,9 @@ constructor of Xml class to import data. In CakePHP 2.0 you can do it using
SimpleXMLElement or DOMDocument object (depending of your options parameter -
default is SimpleXMLElement). Below the samples how to import data from URL::
+ //First Load the Utility Class
+ App::uses('Xml', 'Utility');
+
// Old method:
$xml = new Xml('http://bakery.cakephp.org/articles.rss');
diff --git a/en/development/debugging.rst b/en/development/debugging.rst
index be0e485a7a..0dd6c2a9f9 100644
--- a/en/development/debugging.rst
+++ b/en/development/debugging.rst
@@ -60,7 +60,7 @@ Using the Debugger Class
To use the debugger, first ensure that Configure::read('debug') is
set to a value greater than 0.
-.. php:staticmethod:: Debugger::dump($var)
+.. php:staticmethod:: Debugger::dump($var, $depth = 3)
Dump prints out the contents of a variable. It will print out all
properties and methods (if any) of the supplied variable::
@@ -95,7 +95,10 @@ set to a value greater than 0.
In 2.1 forward the output was updated for readability. See
:php:func:`Debugger::exportVar()`
-.. php:staticmethod:: Debugger::log($var, $level = 7)
+ .. versionchanged:: 2.5.0
+ The ``depth`` parameter was added.
+
+.. php:staticmethod:: Debugger::log($var, $level = 7, $depth = 3)
Creates a detailed stack trace log at the time of invocation. The
log() method prints out data similar to that done by
@@ -103,6 +106,9 @@ set to a value greater than 0.
buffer. Note your app/tmp directory (and its contents) must be
writable by the web server for log() to work correctly.
+ .. versionchanged:: 2.5.0
+ The ``depth`` parameter was added.
+
.. php:staticmethod:: Debugger::trace($options)
Returns the current stack trace. Each line of the trace includes
diff --git a/en/development/dispatch-filters.rst b/en/development/dispatch-filters.rst
index 02cf756e53..bb0ac0f698 100644
--- a/en/development/dispatch-filters.rst
+++ b/en/development/dispatch-filters.rst
@@ -104,6 +104,21 @@ Feel free to remove the default attached filters if you choose to use a more
advanced/faster way of serving theme and plugin assets or if you do not wish to
use built-in full page caching, or just implement your own.
+If you need to pass constructor parameters or settings to you dispatch filter
+classes you can do that by providing an array of settings::
+
+ Configure::write('Dispatcher.filters', array(
+ 'MyAssetFilter' => array('service' => 'google.com')
+ ));
+
+When the filter key is a valid classname, the value can be an array of
+parameters that are passed to the dispatch filter. By default the base class
+will assign these settings to the ``$settings`` property after merging them with
+the defaults in the class.
+
+.. versionchanged:: 2.5
+ You can now provide constructor settings to dispatch filters in 2.5.
+
Filter Classes
==============
diff --git a/en/development/rest.rst b/en/development/rest.rst
index fb5ea7afe6..840a0f7e34 100644
--- a/en/development/rest.rst
+++ b/en/development/rest.rst
@@ -200,6 +200,7 @@ this method you need to set *all* the defaults you want to use::
By overwriting the default resource map, future calls to ``mapResources()`` will
use the new values.
+.. _custom-rest-routing:
Custom REST Routing
===================
@@ -209,6 +210,18 @@ for you, use the :php:meth:`Router::connect()` method to define a custom set of
REST routes. The ``connect()`` method allows you to define a number of different
options for a given URL. See the section on :ref:`route-conditions` for more information.
+.. versionadded:: 2.5
+
+You can provide ``connectOptions`` key in the ``$options`` array for
+:php:meth:`Router::mapResources()` to provide custom setting used by
+:php:meth:`Router::connect()`::
+
+ Router::mapResources('books', array(
+ 'connectOptions' => array(
+ 'routeClass' => 'ApiRoute',
+ )
+ ));
+
.. meta::
:title lang=en: REST
:keywords lang=en: application programmers,default routes,core functionality,result format,mashups,recipe database,request method,easy access,config,soap,recipes,logic,audience,cakephp,running,api
diff --git a/en/development/testing.rst b/en/development/testing.rst
index b36d8e9e1a..61c83de2c2 100644
--- a/en/development/testing.rst
+++ b/en/development/testing.rst
@@ -18,10 +18,12 @@ following::
pear upgrade PEAR
pear config-set auto_discover 1
- pear install pear.phpunit.de/PHPUnit
+ pear install pear.phpunit.de/PHPUnit-3.7.32
.. note::
+ PHPUnit 4 is not compatible with CakePHP's Unit Testing.
+
Depending on your system's configuration, you may need to run the previous
commands with ``sudo``
@@ -333,10 +335,11 @@ test case:
Creating fixtures
-----------------
-When creating a fixture you will mainly define two things: how the table is created (which fields are part of the table), and which records will be initially populated to the table. Let's
-create our first fixture, that will be used to test our own Article
-model. Create a file named ``ArticleFixture.php`` in your
-``app/Test/Fixture`` directory, with the following content::
+When creating a fixture you will mainly define two things: how the table is
+created (which fields are part of the table), and which records will be
+initially populated to the table. Let's create our first fixture, that will be
+used to test our own Article model. Create a file named ``ArticleFixture.php``
+in your ``app/Test/Fixture`` directory, with the following content::
class ArticleFixture extends CakeTestFixture {
@@ -592,6 +595,21 @@ You can control when your fixtures are loaded by setting
}
}
+As of 2.5.0, you can load fixtures in subdirectories. Using multiple directories
+can make it easier to organize your fixtures if you have a larger application.
+To load fixtures in subdirectories, simply include the subdirectory name in the
+fixture name::
+
+ class ArticleTest extends CakeTestCase {
+ public $fixtures = array('app.blog/article', 'app.blog/comment');
+ }
+
+In the above example, both fixtures would be loaded from
+``App/Test/Fixture/blog/``.
+
+.. versionchanged:: 2.5
+ As of 2.5.0 you can load fixtures in subdirectories.
+
Testing Models
==============
@@ -711,6 +729,8 @@ test methods like :php:meth:`~Controller::redirect()`.
Say you have a typical Articles controller, and its corresponding
model. The controller code looks like::
+ App::uses('AppController', 'Controller');
+
class ArticlesController extends AppController {
public $helpers = array('Form', 'Html');
@@ -794,6 +814,8 @@ this, is that ``redirect()`` is mocked in testing, and does not exit like
normal. And instead of your code exiting, it will continue to run code following
the redirect. For example::
+ App::uses('AppController', 'Controller');
+
class ArticlesController extends AppController {
public function add() {
if ($this->request->is('post')) {
@@ -808,6 +830,8 @@ the redirect. For example::
When testing the above code, you will still run ``// more code`` even when the
redirect is reached. Instead, you should write the code like::
+ App::uses('AppController', 'Controller');
+
class ArticlesController extends AppController {
public function add() {
if ($this->request->is('post')) {
@@ -1067,7 +1091,7 @@ set correctly by the ``adjust`` method in our component. We create the file
App::uses('PagematronComponent', 'Controller/Component');
// A fake controller to test against
- class TestPagematronController extends Controller {
+ class PagematronControllerTest extends Controller {
public $paginate = null;
}
@@ -1082,7 +1106,7 @@ set correctly by the ``adjust`` method in our component. We create the file
$this->PagematronComponent = new PagematronComponent($Collection);
$CakeRequest = new CakeRequest();
$CakeResponse = new CakeResponse();
- $this->Controller = new TestPagematronController($CakeRequest, $CakeResponse);
+ $this->Controller = new PagematronControllerTest($CakeRequest, $CakeResponse);
$this->PagematronComponent->startup($this->Controller);
}
diff --git a/en/getting-started/a-typical-cakephp-request.rst b/en/getting-started/a-typical-cakephp-request.rst
index 5cfec653b2..b8270b73c4 100644
--- a/en/getting-started/a-typical-cakephp-request.rst
+++ b/en/getting-started/a-typical-cakephp-request.rst
@@ -45,7 +45,7 @@ Black = required element, Gray = optional element, Blue = callback
controller's set() method. Controller callbacks may be applied
before the data is sent. The view logic is performed, which may
include the use of elements and/or helpers. By default, the view is
- rendered inside of a layout.
+ rendered inside a layout.
#. Additional controller callbacks (like :php:meth:`~Controller::afterFilter`) may be
applied. The complete, rendered view code is sent to Ricardo's
browser.
diff --git a/en/getting-started/cakephp-conventions.rst b/en/getting-started/cakephp-conventions.rst
index a14818db24..e2bb3aa404 100644
--- a/en/getting-started/cakephp-conventions.rst
+++ b/en/getting-started/cakephp-conventions.rst
@@ -8,7 +8,7 @@ you free yourself from the maintenance nightmare of tracking config
files. Convention also makes for a very uniform system development,
allowing other developers to jump in and help more easily.
-CakePHP's conventions have been distilled out of years of web
+CakePHP's conventions have been distilled from years of web
development experience and best practices. While we suggest you use
these conventions while developing with CakePHP, we should mention
that many of these tenets are easily overridden – something that is
@@ -124,32 +124,32 @@ singular/plural of words. See the
:doc:`/core-utility-libraries/inflector` for more
information.
-Field names with two or more words are underscored like,
+Field names with two or more words are underscored:
first\_name.
Foreign keys in hasMany, belongsTo or hasOne relationships are
recognized by default as the (singular) name of the related table
followed by \_id. So if a Baker hasMany Cake, the cakes table will
refer to the bakers table via a baker\_id foreign key. For a
-multiple worded table like category\_types, the foreign key would
-be category\_type\_id.
+table like category\_types whose name contains multiple words,
+the foreign key would be category\_type\_id.
Join tables, used in hasAndBelongsToMany (HABTM) relationships
-between models should be named after the model tables they will
-join in alphabetical order (apples\_zebras rather than
+between models, should be named after the model tables they will
+join, arranged in alphabetical order (apples\_zebras rather than
zebras\_apples).
All tables with which CakePHP models interact (with the exception
-of join tables), require a singular primary key to uniquely
-identify each row. If you wish to model a table which does not have
+of join tables) require a singular primary key to uniquely
+identify each row. If you wish to model a table that does not already have
a single-field primary key, CakePHP's convention is that a
-single-field primary key is added to the table. You have to add a
+single-field primary key is added to the table. You must add a
single-field primary key if you want to use that table's model.
CakePHP does not support composite primary keys. If you want to
directly manipulate your join table data, use direct
:ref:`query ` calls or add a primary key to act on it
-as a normal model. E.g.::
+as a normal model. For example:
CREATE TABLE posts_tags (
id INT(10) NOT NULL AUTO_INCREMENT,
@@ -176,6 +176,7 @@ The basic pattern is
By naming the pieces of your application using CakePHP conventions,
you gain functionality without the hassle and maintenance tethers
of configuration. Here's a final example that ties the conventions
+together:
- Database table: "people"
- Model class: "Person", found at /app/Model/Person.php
diff --git a/en/getting-started/cakephp-folder-structure.rst b/en/getting-started/cakephp-folder-structure.rst
index 85805b0dee..f9c74fa8ce 100644
--- a/en/getting-started/cakephp-folder-structure.rst
+++ b/en/getting-started/cakephp-folder-structure.rst
@@ -26,9 +26,9 @@ You'll notice three main folders:
The App Folder
==============
-CakePHP's app folder is where you will do most of your application
-development. Let's look a little closer at the folders inside of
-app.
+CakePHP's *app* folder is where you will do most of your application
+development. Let's look a little closer at the folders inside
+*app*.
Config
Holds the (few) configuration files CakePHP uses. Database
@@ -41,7 +41,7 @@ Console
Controller
Contains your application's controllers and their components.
Lib
- Contains 1st party libraries that do not come from 3rd parties or
+ Contains libraries that do not come from 3rd parties or
external vendors. This allows you to separate your organization's
internal libraries from vendor libraries.
Locale
@@ -51,10 +51,10 @@ Model
Plugin
Contains plugin packages.
Test
- This directory contains all the test cases, and test fixtures for your
+ This directory contains all the test cases and test fixtures for your
application. The ``Test/Case`` directory should mirror your application and
contain one or more test cases per class in your application. For more
- information on test cases and test fixtures refer to the :doc:`/development/testing`
+ information on test cases and test fixtures, refer to the :doc:`/development/testing`
documentation.
tmp
This is where CakePHP stores temporary data. The actual data it
@@ -62,16 +62,16 @@ tmp
is usually used to store model descriptions, logs, and sometimes
session information.
- Make sure that this folder exists and that it is writable,
- otherwise the performance of your application will be severely
- impacted. In debug mode, CakePHP will warn you if it is not the
- case.
+ Make sure that this folder exists and is writable,
+ or the performance of your application will be severely
+ impacted. In debug mode, CakePHP will warn you if the folder is
+ absent or not writable.
Vendor
Any third-party classes or libraries should be placed here. Doing
so makes them easy to access using the App::import('vendor',
'name') function. Keen observers will note that this seems
- redundant, as there is also a vendors folder at the top level of
+ redundant, as there is also a *vendors* folder at the top level of
our directory structure. We'll get into the differences between the
two when we discuss managing multiple applications and more complex
system setups.
diff --git a/en/getting-started/cakephp-structure.rst b/en/getting-started/cakephp-structure.rst
index 8eb5d5eac6..94f07de958 100644
--- a/en/getting-started/cakephp-structure.rst
+++ b/en/getting-started/cakephp-structure.rst
@@ -51,7 +51,7 @@ available for your use, just in case you need to insert some logic
between CakePHP's core operations. Callbacks available include:
- :php:meth:`~Controller::afterFilter()`, executed after all controller logic,
- including the view render.
+ including the rendering of the view
- :php:meth:`~Controller::beforeFilter()`, executed before any controller action logic
- :php:meth:`~Controller::beforeRender()`, executed after controller logic, but before
the view is rendered
@@ -65,7 +65,7 @@ structure, you can specify your User model as behaving like a tree,
and gain free functionality for removing, adding, and shifting
nodes in your underlying tree structure.
-Models also are supported by another class called a DataSource.
+Models are also supported by another class called a DataSource.
DataSources are an abstraction that enable models to manipulate
different types of data consistently. While the main source of data
in a CakePHP application is often a database, you might write
@@ -73,9 +73,9 @@ additional DataSources that allow your models to represent RSS
feeds, CSV files, LDAP entries, or iCal events. DataSources allow
you to associate records from different sources: rather than being
limited to SQL joins, DataSources allow you to tell your LDAP model
-that it is associated to many iCal events.
+that it is associated with many iCal events.
-Just like controllers, models are featured with callbacks as well:
+Like controllers, models have callbacks:
- beforeFind()
- afterFind()
@@ -95,7 +95,8 @@ View Extensions ("Helpers")
A Helper is a class that aids in view logic. Much like a component
used among controllers, helpers allow presentational logic to be
accessed and shared between views. One of the core helpers,
-JsHelper, makes AJAX requests within views much easier and comes with support for jQuery (default), Prototype and Mootools.
+JsHelper, makes AJAX requests within views much easier and comes with
+support for jQuery (default), Prototype and Mootools.
Most applications have pieces of view code that are used
repeatedly. CakePHP facilitates view code reuse with layouts and
diff --git a/en/index.rst b/en/index.rst
index b3b3136802..7c95e2f9cd 100644
--- a/en/index.rst
+++ b/en/index.rst
@@ -17,8 +17,8 @@ the documentation.
**Read the Book Anywhere**
- Enjoy the CakePHP cookbook almost anywhere. Available, as both a PDF and
- EPUB, you can now read the docs on more devices and offline.
+ Enjoy the CakePHP cookbook almost anywhere. Available as both a PDF and
+ EPUB, you can now read it on more devices, as well as offline.
- `PDF <../_downloads/en/CakePHPCookbook.pdf>`_
- `EPUB <../_downloads/en/CakePHPCookbook.epub>`_
@@ -43,20 +43,20 @@ Learn about a typical :doc:`CakePHP request
Controllers
-----------
-Controllers handle requests, and help co-ordinate and prepare
-the response for the client. Read more about :doc:`/controllers`.
+Controllers handle requests and help co-ordinate and prepare
+responses for the client. Read more about :doc:`/controllers`.
Views
-----
Views are the presentation layer in CakePHP. They convert
-the data fetched from Models, into the output format the client
-requested. Read more about :doc:`/views`.
+the data fetched from Models into the output format requested by the
+client. Read more about :doc:`/views`.
Models
------
-Models are the heart of your application, they handle the validation,
+Models are the heart of your application. They handle the validation,
storage and retrieval of your data. Read more about :doc:`/models`.
Getting Help
diff --git a/en/installation.rst b/en/installation.rst
index f297d2c8d2..cb34f5b080 100755
--- a/en/installation.rst
+++ b/en/installation.rst
@@ -71,6 +71,15 @@ views and session information.
As such, make sure the directory ``app/tmp`` and all its subdirectories in your CakePHP installation
are writable by the web server user.
+One common issue is that the app/tmp directories and subdirectories must be writable both by the web server and the command line user.
+On a UNIX system, if your web server user is different from your command line user,
+you can run the following commands just once in your project to ensure that
+permissions will be setup properly::
+
+ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1`
+ setfacl -R -m u:${HTTPDUSER}:rwx app/tmp
+ setfacl -R -d -m u:${HTTPDUSER}:rwx app/tmp
+
Setup
=====
diff --git a/en/installation/advanced-installation.rst b/en/installation/advanced-installation.rst
index 2be660a6aa..54cac66740 100644
--- a/en/installation/advanced-installation.rst
+++ b/en/installation/advanced-installation.rst
@@ -41,7 +41,7 @@ would look like the following::
}
],
"require": {
- "pear-cakephp/cakephp": ">=2.4.0"
+ "cakephp/cakephp": ">=2.4.9"
},
"config": {
"vendor-dir": "Vendor/"
@@ -76,7 +76,7 @@ changing ``CAKE_CORE_INCLUDE_PATH`` to be a relative path::
define(
'CAKE_CORE_INCLUDE_PATH',
- ROOT . DS . APP_DIR . '/Vendor/pear-pear.cakephp.org/CakePHP'
+ ROOT . '/Vendor/pear-pear.cakephp.org/CakePHP'
);
.. note::
diff --git a/en/installation/url-rewriting.rst b/en/installation/url-rewriting.rst
index d1b6cdf6a6..809d5b41c3 100644
--- a/en/installation/url-rewriting.rst
+++ b/en/installation/url-rewriting.rst
@@ -9,10 +9,10 @@ usually does–we've noticed that a few users struggle with getting
everything to play nicely on their systems.
Here are a few things you might try to get it running correctly.
-First look at your httpd.conf (Make sure you are editing the system
-httpd.conf rather than a user- or site-specific httpd.conf).
+First look at your httpd.conf. (Make sure you are editing the system
+httpd.conf rather than a user- or site-specific httpd.conf.)
-These files can vary on different distributions and apache versions.
+These files can vary between different distributions and Apache versions.
You may also take a look at http://wiki.apache.org/httpd/DistrosDefaultLayout for further information.
@@ -34,30 +34,26 @@ You may also take a look at http://wiki.apache.org/httpd/DistrosDefaultLayout fo
# Deny from all
-#. Make sure you are loading up mod\_rewrite correctly. You should
+#. Make sure you are loading mod\_rewrite correctly. You should
see something like::
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
- In many systems these will be commented out (by being prepended
- with a #) by default, so you may just need to remove those leading
- # symbols.
+ In many systems these will be commented out by default, so you may
+ just need to remove the leading # symbols.
After you make changes, restart Apache to make sure the settings
are active.
Verify that your .htaccess files are actually in the right
- directories.
+ directories. Some operating systems treat files that start
+ with '.' as hidden and therefore won't copy them.
- This can happen during copying because some operating systems treat
- files that start with '.' as hidden and therefore won't see them to
- copy.
-
-#. Make sure your copy of CakePHP is from the downloads section of
- the site or our Git repository, and has been unpacked correctly by
+#. Make sure your copy of CakePHP comes from the downloads section of
+ the site or our Git repository, and has been unpacked correctly, by
checking for .htaccess files.
- CakePHP root directory (needs to be copied to your document, this
+ CakePHP root directory (must be copied to your document;
redirects everything to your CakePHP app)::
@@ -85,10 +81,10 @@ You may also take a look at http://wiki.apache.org/httpd/DistrosDefaultLayout fo
RewriteRule ^(.*)$ index.php [QSA,L]
- If your CakePHP site still has problems with mod\_rewrite you might
- want to try and modify settings for Virtual Hosts. If on Ubuntu,
+ If your CakePHP site still has problems with mod\_rewrite, you might
+ want to try modifying settings for Virtual Hosts. On Ubuntu,
edit the file /etc/apache2/sites-available/default (location is
- distribution dependent). In this file, ensure that
+ distribution-dependent). In this file, ensure that
``AllowOverride None`` is changed to ``AllowOverride All``, so you have::
@@ -102,7 +98,7 @@ You may also take a look at http://wiki.apache.org/httpd/DistrosDefaultLayout fo
Allow from all
- If on Mac OSX, another solution is to use the tool
+ On Mac OSX, another solution is to use the tool
`virtualhostx `_
to make a Virtual Host to point to your folder.
@@ -115,7 +111,7 @@ You may also take a look at http://wiki.apache.org/httpd/DistrosDefaultLayout fo
/app/.htaccess, /app/webroot/.htaccess).
This can be added to the same section with the RewriteEngine
- directive, so for example your webroot .htaccess file would look
+ directive, so for example, your webroot .htaccess file would look
like::
@@ -127,7 +123,7 @@ You may also take a look at http://wiki.apache.org/httpd/DistrosDefaultLayout fo
The details of those changes will depend on your setup, and can
- include additional things that are not CakePHP related. Please refer
+ include additional things that are not related to CakePHP. Please refer
to Apache's online documentation for more information.
#. (Optional) To improve production setup, you should prevent invalid assets
@@ -203,8 +199,8 @@ these steps:
#. Use `Microsoft's Web Platform Installer `_ to install the URL
`Rewrite Module 2.0 `_ or download it directly (`32-bit `_ / `64-bit `_).
-#. Create a new file in your CakePHP root folder, called web.config.
-#. Using Notepad or any XML-safe editor and copy the following
+#. Create a new file called web.config in your CakePHP root folder.
+#. Using Notepad or any XML-safe editor, copy the following
code into your new web.config file...
::
@@ -248,8 +244,8 @@ correctly.
URL-Rewriting on lighttpd
=========================
-Lighttpd does not support .htaccess functions, therefore you can remove all .htaccess files.
-In the lighttpd configuration make sure you've activiated "mod_rewrite". Add a line:
+Lighttpd does not support .htaccess functions, so you can remove all .htaccess files.
+In the lighttpd configuration, make sure you've activated "mod_rewrite". Add a line:
::
diff --git a/en/models.rst b/en/models.rst
index 5b7e9ff34e..8f1b3dca91 100644
--- a/en/models.rst
+++ b/en/models.rst
@@ -1,31 +1,30 @@
Models
######
-Models are the classes that sit as the business layer in your application.
-This means that they should be responsible for managing almost everything
-that happens regarding your data, its validity, interactions and evolution
-of the information workflow in your domain of work.
+Models are the classes that form the business layer in your application.
+They should be responsible for managing almost everything
+regarding your data, its validity, and its interactions, as well as the evolution
+of the information workflow in your domain.
-Usually model classes represent data and are used in CakePHP applications
-for data access, more specifically they represent a database table but they are
-not limited to this, but can be used to access anything that manipulates data
-such as files, external web services, iCal events, or rows in a CSV file.
+Usually, model classes represent data and are used in CakePHP applications
+for data access. They generally represent a database table but can be used
+to access anything that manipulates data
+such as files, external web services, or iCal events.
A model can be associated with other models. For example, a Recipe
-may be associated with the Author of the recipe as well as the
-Ingredient in the recipe.
+may be associated with an Author as well as an Ingredient.
This section will explain what features of the model can be
automated, how to override those features, and what methods and
-properties a model can have. It'll explain the different ways to
-associate your data. It'll describe how to find, save, and delete
-data. Finally, it'll look at Datasources.
+properties a model can have. It will explain the different ways to
+build associations for your data. It will describe how to find, save, and delete
+data. Finally, it will look at Datasources.
Understanding Models
====================
-A Model represents your data model. In object-oriented programming
-a data model is an object that represents a "thing", like a car, a
+A Model represents your data model. In object-oriented programming,
+a data model is an object that represents a thing such as a car, a
person, or a house. A blog, for example, may have many blog posts
and each blog post may have many comments. The Blog, Post, and
Comment are all examples of models, each associated with another.
@@ -37,52 +36,53 @@ Here is a simple example of a model definition in CakePHP::
public $name = 'Ingredient';
}
-With just this simple declaration, the Ingredient model is bestowed
-with all the functionality you need to create queries along with
-saving and deleting data. These magic methods come from CakePHP's
+With just this simple declaration, the Ingredient model is endowed
+with all the functionality you need to create queries and to
+save and delete data. These methods come from CakePHP's
Model class by the magic of inheritance. The Ingredient model
-extends the application model, AppModel, which extends CakePHP's
+extends the application model, AppModel, which in turn extends CakePHP's
internal Model class. It is this core Model class that bestows the
functionality onto your Ingredient model. ``App::uses('AppModel', 'Model')``
-ensures that the model is lazy loaded in every instance of its usage.
+ensures that the model is loaded when it is needed.
-This intermediate class, AppModel, is empty and if you haven't
-created your own, is taken from within the CakePHP core folder. Overriding
+The intermediate class, AppModel, is empty. If you haven't
+created your own, it is taken from the CakePHP core folder. Overriding
the AppModel allows you to define functionality that should be made
available to all models within your application. To do so, you need
to create your own ``AppModel.php`` file that resides in the Model folder,
-as all other models in your application. Creating a project using
+as do all other models in your application. Creating a project using
:doc:`Bake ` will automatically
generate this file for you.
See also :doc:`Behaviors ` for more information on
how to apply similar logic to multiple models.
-Back to our Ingredient model, in order to work on it, create the PHP file in the
-``/app/Model/`` directory. By convention it should have the same name as the class;
-for this example ``Ingredient.php``.
+Back to our Ingredient model. In order to work on it, create the PHP file in the
+``/app/Model/`` directory. By convention, it should have the same name as the class,
+which for this example will be ``Ingredient.php``.
.. note::
CakePHP will dynamically create a model object for you if it cannot
find a corresponding file in /app/Model. This also means that if
- your model file isn't named correctly (i.e. ingredient.php or
- Ingredients.php) CakePHP will use an instance of AppModel rather
- than your missing (from CakePHP's perspective) model file. If
+ your model file isn't named correctly (for instance, if it is named
+ ingredient.php or Ingredients.php rather than Ingredient.php),
+ CakePHP will use an instance of AppModel rather
+ than your model file (which CakePHP assumes is missing). If
you're trying to use a method you've defined in your model, or a
- behavior attached to your model and you're getting SQL errors that
- are the name of the method you're calling - it's a sure sign
- CakePHP can't find your model and you either need to check the file
+ behavior attached to your model, and you're getting SQL errors that
+ are the name of the method you're calling, it's a sure sign that
+ CakePHP can't find your model and you need to check the file
names, your application cache, or both.
.. note::
- Some class names are not usable for model names. For instance
- "File" cannot be used as "File" is a class already existing in the
+ Some class names are not usable for model names. For instance,
+ "File" cannot be used, since "File" is a class that already exists in the
CakePHP core.
-With your model defined, it can be accessed from within your
+When your model is defined, it can be accessed from within your
:doc:`Controller `. CakePHP will automatically
make the model available for access when its name matches that of
the controller. For example, a controller named
@@ -110,7 +110,7 @@ model::
}
This shows how to use models that are already linked. To understand how associations are
-defined take a look at the :doc:`Associations section `
+defined, take a look at the :doc:`Associations section `
More on models
==============
diff --git a/en/models/associations-linking-models-together.rst b/en/models/associations-linking-models-together.rst
index 1941d559b3..2e1128dcf5 100644
--- a/en/models/associations-linking-models-together.rst
+++ b/en/models/associations-linking-models-together.rst
@@ -37,12 +37,12 @@ one to many hasMany A user can have multiple recipes.
------------- --------------------- ---------------------------------------
many to one belongsTo Many recipes belong to a user.
------------- --------------------- ---------------------------------------
-many to many hasAndBelongsToMany Recipes have, and belong to many ingredients.
+many to many hasAndBelongsToMany Recipes have, and belong to, many ingredients.
============= ===================== =======================================
Associations are defined by creating a class variable named after
the association you are defining. The class variable can sometimes
-be as simple as a string, but can be as complete as a
+be as simple as a string, but can be as complex as a
multidimensional array used to define association specifics.
::
@@ -60,9 +60,9 @@ multidimensional array used to define association specifics.
In the above example, the first instance of the word 'Recipe' is
what is termed an 'Alias'. This is an identifier for the
-relationship and can be anything you choose. Usually, you will
+relationship, and can be anything you choose. Usually, you will
choose the same name as the class that it references. However,
-**aliases for each model must be unique app wide**. For example it is
+**aliases for each model must be unique across the app**. For example, it is
appropriate to have::
class User extends AppModel {
@@ -138,9 +138,9 @@ simply by following your model associations::
.. note::
Remember that associations are defined 'one way'. If you define
- User hasMany Recipe that has no effect on the Recipe Model. You
+ User hasMany Recipe, that has no effect on the Recipe Model. You
need to define Recipe belongsTo User to be able to access the User
- model from your Recipe model
+ model from your Recipe model.
hasOne
------
@@ -150,7 +150,7 @@ model.
First, your database tables need to be keyed correctly. For a
hasOne relationship to work, one table has to contain a foreign key
-that points to a record in the other. In this case the profiles
+that points to a record in the other. In this case, the profiles
table will contain a field called user\_id. The basic pattern is:
**hasOne:** the *other* model contains the foreign key.
@@ -167,9 +167,9 @@ Doctor hasOne Mentor mentors.doctor\_id
.. note::
- It is not mandatory to follow CakePHP conventions, you can easily override
- the use of any foreignKey in your associations definitions. Nevertheless sticking
- to conventions will make your code less repetitive, easier to read and to maintain.
+ It is not mandatory to follow CakePHP conventions. You can easily override
+ the use of any foreignKey in your associations definitions. Nevertheless, sticking
+ to conventions will make your code less repetitive and easier to read and maintain.
The User model file will be saved in /app/Model/User.php. To
define the 'User hasOne Profile' association, add the $hasOne
@@ -206,21 +206,21 @@ Possible keys for hasOne association arrays include:
- **className**: the class name of the model being associated to
the current model. If you're defining a 'User hasOne Profile'
- relationship, the className key should equal 'Profile.'
+ relationship, the className key should equal 'Profile'.
- **foreignKey**: the name of the foreign key found in the other
model. This is especially handy if you need to define multiple
hasOne relationships. The default value for this key is the
underscored, singular name of the current model, suffixed with
- '\_id'. In the example above it would default to 'user\_id'.
-- **conditions**: an array of find() compatible conditions or SQL
+ '\_id'. In the example above, it would default to 'user\_id'.
+- **conditions**: an array of find()-compatible conditions or SQL
strings such as array('Profile.approved' => true)
- **fields**: A list of fields to be retrieved when the associated
model data is fetched. Returns all fields by default.
-- **order**: an array of find() compatible order clauses or SQL
+- **order**: an array of find()-compatible order clauses or SQL
strings such as array('Profile.last_name' => 'ASC')
- **dependent**: When the dependent key is set to true, and the
model's delete() method is called with the cascade parameter set to
- true, associated model records are also deleted. In this case we
+ true, associated model records are also deleted. In this case, we
set it true so that deleting a User will also delete her associated
Profile.
@@ -299,7 +299,7 @@ Possible keys for belongsTo association arrays include:
- **className**: the class name of the model being associated to
the current model. If you're defining a 'Profile belongsTo User'
- relationship, the className key should equal 'User.'
+ relationship, the className key should equal 'User'.
- **foreignKey**: the name of the foreign key found in the current
model. This is especially handy if you need to define multiple
belongsTo relationships. The default value for this key is the
@@ -307,23 +307,21 @@ Possible keys for belongsTo association arrays include:
``_id``.
- **conditions**: an array of find() compatible conditions or SQL
strings such as ``array('User.active' => true)``
-- **type**: the type of the join to use in the SQL query, default
- is LEFT which may not fit your needs in all situations, INNER may
- be helpful when you want everything from your main and associated
- models or nothing at all! (effective when used with some conditions
- of course).
- **(NB: type value is in lower case - i.e. left, inner)**
+- **type**: the type of the join to use in the SQL query. The default
+ is 'LEFT', which may not fit your needs in all situations. The value
+ 'INNER' may be helpful (when used with some conditions) when you want
+ everything from your main and associated models or nothing at all.
- **fields**: A list of fields to be retrieved when the associated
model data is fetched. Returns all fields by default.
- **order**: an array of find() compatible order clauses or SQL
strings such as ``array('User.username' => 'ASC')``
-- **counterCache**: If set to true the associated Model will
+- **counterCache**: If set to true, the associated Model will
automatically increase or decrease the
"[singular\_model\_name]\_count" field in the foreign table
- whenever you do a ``save()`` or ``delete()``. If it's a string then it's the
+ whenever you do a ``save()`` or ``delete()``. If it's a string, then it's the
field name to use. The value in the counter field represents the
number of related rows. You can also specify multiple counter caches
- by defining an array, see :ref:`multiple-counterCache`
+ by defining an array. See :ref:`multiple-counterCache`.
- **counterScope**: Optional conditions array to use for updating
counter cache field.
@@ -422,7 +420,7 @@ Possible keys for hasMany association arrays include:
but may not be ideal for all circumstances.
- **finderQuery**: A complete SQL query CakePHP can use to fetch
associated model records. This should be used in situations that
- require very custom results.
+ require highly customized results.
If a query you're building requires a reference to the associated
model ID, use the special ``{$__cakeID__$}`` marker in the query.
For example, if your Apple model hasMany Orange, the query should
@@ -468,8 +466,8 @@ One thing to remember is that you'll need a complimentary Comment
belongsTo User association in order to get the data from both
directions. What we've outlined in this section empowers you to get
Comment data from the User. Adding the Comment belongsTo User
-association in the Comment model empowers you to get User data from
-the Comment model - completing the connection and allowing the flow
+association in the Comment model enables you to get User data from
+the Comment model, completing the connection and allowing the flow
of information from either model's perspective.
counterCache - Cache your count()
@@ -477,7 +475,7 @@ counterCache - Cache your count()
This function helps you cache the count of related data. Instead of
counting the records manually via ``find('count')``, the model
-itself tracks any addition/deleting towards the associated
+itself tracks any addition/deletion towards the associated
``$hasMany`` model and increases/decreases a dedicated integer
field within the parent model table.
@@ -487,7 +485,7 @@ by a underscore and the word "count"::
my_model_count
Let's say you have a model called ``ImageComment`` and a model
-called ``Image``, you would add a new INT-field to the ``images``
+called ``Image``. You would add a new INT-field to the ``images``
table and name it ``image_comment_count``.
Here are some more examples:
@@ -502,7 +500,7 @@ Image ImageComment images.image\_comment\_count
BlogEntry BlogEntryComment blog\_entries.blog\_entry\_comment\_count
========== ======================= =========================================
-Once you have added the counter field you are good to go. Activate
+Once you have added the counter field, you are good to go. Activate
counter-cache in your association by adding a ``counterCache`` key
and set the value to ``true``::
@@ -544,9 +542,9 @@ Using our Image model example, we can specify it like so::
Multiple counterCache
=====================
-Since 2.0 CakePHP supports having multiple ``counterCache`` in a single model
+Since 2.0, CakePHP has supported having multiple ``counterCache`` in a single model
relation. It is also possible to define a ``counterScope`` for each ``counterCache``.
-Assuming you have a ``User`` model and a ``Message`` model and you want to be able
+Assuming you have a ``User`` model and a ``Message`` model, and you want to be able
to count the amount of read and unread messages for each user.
========= ====================== ===========================================
@@ -559,7 +557,7 @@ User users.messages\_unread Count unread ``Message``
Message messages.is\_read Determines if a ``Message`` is read or not.
========= ====================== ===========================================
-With this setup your ``belongsTo`` would look like this::
+With this setup, your ``belongsTo`` would look like this::
class Message extends AppModel {
public $belongsTo = array(
@@ -575,7 +573,7 @@ With this setup your ``belongsTo`` would look like this::
hasAndBelongsToMany (HABTM)
---------------------------
-Alright. At this point, you can already call yourself a CakePHP
+All right. At this point, you can already call yourself a CakePHP
model associations professional. You're already well versed in the
three associations that take up the bulk of object relations.
@@ -591,17 +589,17 @@ doesn't "use up" the ingredient. I can also use it for a salad Recipe.
Links between hasMany associated objects are exclusive. If my User
hasMany Comments, a comment is only linked to a specific user. It's
-no longer up for grabs.
+not up for grabs.
Moving on. We'll need to set up an extra table in the database to
handle HABTM associations. This new join table's name needs to
include the names of both models involved, in alphabetical order,
and separated with an underscore ( \_ ). The contents of the table
-should be two fields, each foreign keys (which should be integers)
-pointing to both of the primary keys of the involved models. To
-avoid any issues - don't define a combined primary key for these
-two fields, if your application requires it you can define a unique
-index. If you plan to add any extra information to this table, or use
+should be two fields that are foreign keys (which should be integers)
+pointing to the primary keys of the involved models. To
+avoid any issues, don't define a combined primary key for these
+two fields. If your application requires a unique index, you can define one.
+If you plan to add any extra information to this table, or use
a 'with' model, you should add an additional primary key field (by convention
'id').
@@ -621,15 +619,15 @@ Foo HABTM Bar **bars_foos**.id, **bars_foos**.foo_id, **bars_foos**.
.. note::
- Table names are by convention in alphabetical order. It is
- possible to define a custom table name in association definition
+ Table names are in alphabetical order by convention. It is
+ possible to define a custom table name in association definition.
Make sure primary keys in tables **cakes** and **recipes** have
"id" fields as assumed by convention. If they're different than
-assumed, it has to be changed in model's :ref:`model-primaryKey`
+assumed, they must be changed in model's :ref:`model-primaryKey`.
Once this new table has been created, we can define the HABTM
-association in the model files. We're gonna skip straight to the
+association in the model files. We're going to skip straight to the
array syntax this time::
class Recipe extends AppModel {
@@ -658,7 +656,7 @@ Possible keys for HABTM association arrays include:
- **className**: the class name of the model being associated to
the current model. If you're defining a 'Recipe HABTM Ingredient'
- relationship, the className key should equal 'Ingredient.'
+ relationship, the className key should equal 'Ingredient'.
- **joinTable**: The name of the join table used in this
association (if the current table doesn't adhere to the naming
convention for HABTM join tables).
@@ -667,8 +665,8 @@ Possible keys for HABTM association arrays include:
above it would be called IngredientsRecipe. By using this key you can
override this default name. The join table model can be used just
like any "regular" model to access the join table directly. By creating
- a model class with such name and filename you can add any custom behavior
- to the join table searches, such as adding more information/columns to it
+ a model class with such name and filename, you can add any custom behavior
+ to the join table searches, such as adding more information/columns to it.
- **foreignKey**: the name of the foreign key found in the current
model. This is especially handy if you need to define multiple
HABTM relationships. The default value for this key is the
@@ -687,20 +685,20 @@ Possible keys for HABTM association arrays include:
no join records are deleted during a save operation.
- When set to ``keepExisting``, the behavior is similar to `true`,
but existing associations are not deleted.
-- **conditions**: an array of find() compatible conditions or SQL
+- **conditions**: an array of find()-compatible conditions or SQL
string. If you have conditions on an associated table, you should use a
'with' model, and define the necessary belongsTo associations on it.
- **fields**: A list of fields to be retrieved when the associated
model data is fetched. Returns all fields by default.
-- **order**: an array of find() compatible order clauses or SQL
+- **order**: an array of find()-compatible order clauses or SQL
strings
- **limit**: The maximum number of associated rows you want
returned.
- **offset**: The number of associated rows to skip over (given
the current conditions and order) before fetching and associating.
- **finderQuery**: A complete SQL query CakePHP can use to fetch associated
- model records. This should be used in situations that require very custom
- results.
+ model records. This should be used in situations that require
+ highly customized results.
Once this association has been defined, find operations on the
Recipe model will also fetch related Tag records if they exist::
@@ -741,14 +739,14 @@ like to fetch Recipe data when using the Ingredient model.
.. note::
- HABTM data is treated like a complete set, each time a new data association is added
- the complete set of associated rows in database is dropped and created again so you
+ HABTM data is treated like a complete set. Each time a new data association is added,
+ the complete set of associated rows in the database is dropped and created again so you
will always need to pass the whole data set for saving. For an alternative to using
- HABTM see :ref:`hasMany-through`
+ HABTM, see :ref:`hasMany-through`.
.. tip::
- For more information on saving HABTM objects see :ref:`saving-habtm`
+ For more information on saving HABTM objects, see :ref:`saving-habtm`
.. _hasMany-through:
@@ -756,15 +754,15 @@ like to fetch Recipe data when using the Ingredient model.
hasMany through (The Join Model)
--------------------------------
-It is sometimes desirable to store additional data with a many to
-many association. Consider the following
+It is sometimes desirable to store additional data with a many-to-many
+association. Consider the following
`Student hasAndBelongsToMany Course`
`Course hasAndBelongsToMany Student`
In other words, a Student can take many Courses and a Course can be
-taken by many Students. This is a simple many to many association
+taken by many Students. This is a simple many-to-many association
demanding a table such as this::
id | student_id | course_id
@@ -782,7 +780,7 @@ the columns as it is not replaced in the new insert.
.. versionchanged:: 2.1
- You can set ``unique`` setting to ``keepExisting`` circumvent
+ You can set the ``unique`` setting to ``keepExisting`` to circumvent
losing extra data during the save operation. See ``unique``
key in :ref:`HABTM association arrays `.
@@ -818,7 +816,7 @@ The CourseMembership join model uniquely identifies a given
Student's participation on a Course in addition to extra
meta-information.
-Join models are pretty useful things to be able to use and CakePHP
+Join models are pretty useful things to be able to use, and CakePHP
makes it easy to do so with its built-in hasMany and belongsTo
associations and saveAll feature.
@@ -838,8 +836,8 @@ associations on the fly. This may be for any number of reasons:
This association creation and destruction is done using the CakePHP
model bindModel() and unbindModel() methods. (There is also a very
-helpful behavior called "Containable", please refer to manual
-section about Built-in behaviors for more information). Let's set
+helpful behavior called "Containable". Please refer to the manual
+section about Built-in behaviors for more information.) Let's set
up a few models so we can see how bindModel() and unbindModel()
work. We'll start with two models::
@@ -889,7 +887,7 @@ controller action::
.. note::
Removing or adding associations using bind- and unbindModel() only
- works for the *next* find operation only unless the second
+ works for the *next* find operation unless the second
parameter has been set to false. If the second parameter has been
set to *false*, the bind remains in place for the remainder of the
request.
@@ -904,13 +902,13 @@ Now that we've successfully removed an association on the fly,
let's add one. Our as-of-yet unprincipled Leader needs some
associated Principles. The model file for our Principle model is
bare, except for the public $name statement. Let's associate some
-Principles to our Leader on the fly (but remember–only for just the
+Principles to our Leader on the fly (but remember, only for the
following find operation). This function appears in the
LeadersController::
public function another_action() {
// There is no Leader hasMany Principles in
- // the leader.php model file, so a find here,
+ // the leader.php model file, so a find here
// only fetches Leaders.
$this->Leader->find('all');
@@ -953,9 +951,9 @@ Multiple relations to the same model
------------------------------------
There are cases where a Model has more than one relation to another
-Model. For example you might have a Message model that has two
-relations to the User model. One relation to the user that sends a
-message, and a second to the user that receives the message. The
+Model. For example, you might have a Message model that has two
+relations to the User model: one relation to the user who sends a
+message, and a second to the user who receives the message. The
messages table will have a field user\_id, but also a field
recipient\_id. Now your Message model can look something like::
@@ -1009,8 +1007,8 @@ It is also possible to create self associations as shown below::
**Fetching a nested array of associated records:**
-If your table has ``parent_id`` field you can also use :ref:`model-find-threaded`
-to fetch nested array of records using a single query without
+If your table has a ``parent_id`` field, you can also use :ref:`model-find-threaded`
+to fetch a nested array of records using a single query without
setting up any associations.
.. _joining-tables:
@@ -1018,11 +1016,11 @@ setting up any associations.
Joining tables
--------------
-In SQL you can combine related tables using the JOIN statement.
-This allows you to perform complex searches across multiples tables
-(i.e: search posts given several tags).
+In SQL, you can combine related tables using the JOIN statement.
+This allows you to perform complex searches across multiple tables
+(for example, search posts given several tags).
-In CakePHP some associations (belongsTo and hasOne) performs
+In CakePHP, some associations (belongsTo and hasOne) perform
automatic joins to retrieve data, so you can issue queries to
retrieve models based on data in the related one.
@@ -1033,10 +1031,10 @@ the desired results for your query.
.. note::
- Remember you need to set the recursion to -1 for this to work. I.e:
+ Remember that you need to set the recursion to -1 for this to work:
$this->Channel->recursive = -1;
-To force a join between tables you need to use the "modern" syntax
+To force a join between tables, you need to use the "modern" syntax
for Model::find(), adding a 'joins' key to the $options array. For
example::
@@ -1056,7 +1054,7 @@ example::
Note that the 'join' arrays are not keyed.
-In the above example, a model called Item is left joined to the
+In the above example, a model called Item is left-joined to the
channels table. You can alias the table with the Model name, so the
retrieved data complies with the CakePHP data structure.
@@ -1090,8 +1088,8 @@ fields::
You could perform several joins as needed in hasAndBelongsToMany:
-Suppose a Book hasAndBelongsToMany Tag association. This relation
-uses a books\_tags table as join table, so you need to join the
+Suppose there is a Book hasAndBelongsToMany Tag association. This relation
+uses a books\_tags table as a join table, so you need to join the
books table to the books\_tags table, and this with the tags
table::
@@ -1118,10 +1116,10 @@ table::
$books = $Book->find('all', $options);
-Using joins allows you to have a maximum flexibility in how CakePHP handles associations
-and fetch the data, however in most cases you can use other tools to achieve the same results
+Using joins allows you to have maximum flexibility in how CakePHP handles associations
+and fetches the data. However, in most cases, you can use other tools to achieve the same results
such as correctly defining associations, binding models on the fly and using the Containable
-behavior. This feature should be used with care because it could lead, in a few cases, into bad formed
+behavior. This feature should be used with care because it could lead, in a few cases, into ill-formed
SQL queries if combined with any of the former techniques described for associating models.
diff --git a/en/models/behaviors.rst b/en/models/behaviors.rst
index 4699f162af..dbc649b0c6 100644
--- a/en/models/behaviors.rst
+++ b/en/models/behaviors.rst
@@ -259,7 +259,7 @@ before the model callbacks of the same name. Behavior
callbacks allow your behaviors to capture events in attached models
and augment the parameters or splice in additional behavior.
-All behavior callbacks are fired **before** the model/behavior callbacks are:
+All behavior callbacks are fired **before** the model callbacks are:
- ``beforeFind``
- ``afterFind``
diff --git a/en/models/data-validation.rst b/en/models/data-validation.rst
index 1ab123d3c4..ebd6e1d7af 100644
--- a/en/models/data-validation.rst
+++ b/en/models/data-validation.rst
@@ -905,7 +905,7 @@ with usage examples.
.. versionadded:: 2.3
This method was added in 2.3
-.. php:staticmethod:: inList(string $check, array $list, $strict = true)
+.. php:staticmethod:: inList(string $check, array $list, boolean $caseInsensitive = false)
This rule will ensure that the value is in a given set. It needs an
array of values. The field is valid if the field's value matches
@@ -922,6 +922,8 @@ with usage examples.
)
);
+ Comparison is case sensitive by default. You can set ``$caseInsensitive`` to true
+ if you need case insensitive comparison.
.. php:staticmethod:: ip(string $check, string $type = 'both')
@@ -977,11 +979,15 @@ with usage examples.
representation of the data". Be careful that it may be larger than
the number of characters when handling non-ASCII characters.
-.. php:staticmethod:: mimeType(mixed $check, array $mimeTypes)
+.. php:staticmethod:: mimeType(mixed $check, array|string $mimeTypes)
.. versionadded:: 2.2
- This rule checks for valid mimeType
+ This rule checks for valid mime types. Comparison is case sensitive.
+
+ .. versionchanged:: 2.5
+
+ Since 2.5 ``$mimeTypes`` can be a regex string.
::
@@ -990,6 +996,10 @@ with usage examples.
'rule' => array('mimeType', array('image/gif')),
'message' => 'Invalid mime type.'
),
+ 'logo' => array(
+ 'rule' => array('mimeType', '#image/.+#'),
+ 'message' => 'Invalid mime type.'
+ ),
);
.. php:staticmethod:: minLength(string $check, integer $min)
@@ -1027,7 +1037,7 @@ with usage examples.
)
);
-.. php:staticmethod:: multiple(mixed $check, mixed $options = array())
+.. php:staticmethod:: multiple(mixed $check, mixed $options = array(), boolean $caseInsensitive = false)
Use this for validating a multiple select input. It supports
parameters "in", "max" and "min".
@@ -1045,6 +1055,8 @@ with usage examples.
)
);
+ Comparison is case sensitive by default. You can set ``$caseInsensitive`` to true
+ if you need case insensitive comparison.
.. php:staticmethod:: notEmpty(mixed $check)
diff --git a/en/models/retrieving-your-data.rst b/en/models/retrieving-your-data.rst
index 8fec0cfe10..f675744920 100644
--- a/en/models/retrieving-your-data.rst
+++ b/en/models/retrieving-your-data.rst
@@ -13,13 +13,13 @@ find
``find(string $type = 'first', array $params = array())``
Find is the multifunctional workhorse of all model data-retrieval functions.
-``$type`` can be either ``'all'``, ``'first'``, ``'count'``, ``'list'``,
-``'neighbors'`` or ``'threaded'`` or any custom finder you can define.
-Keep in mind that ``$type`` is case sensitive. Using an upper case character
-(for example ``All``) will not produce the expected results.
+``$type`` can be ``'all'``, ``'first'``, ``'count'``, ``'list'``,
+``'neighbors'`` or ``'threaded'``, or any custom finder you can define.
+Keep in mind that ``$type`` is case-sensitive. Using an upper case character
+(for example, ``All``) will not produce the expected results.
-``$params`` is used to pass all parameters to the various finds,
-and has the following possible keys by default - all of which are
+``$params`` is used to pass all parameters to the various types of find(),
+and has the following possible keys by default, all of which are
optional::
array(
@@ -36,18 +36,17 @@ optional::
'callbacks' => true //other possible values are false, 'before', 'after'
)
-It's also possible to add and use other parameters, as is made use
-of by some find types, behaviors and of course possibly with your
-own model methods.
+It's also possible to add and use other parameters. Some types of find()
+and behaviors make use of this ability, and your own model methods can, too.
-If your find operation fails to match any records you will get an empty array.
+If your find() operation fails to match any records, you will get an empty array.
.. _model-find-first:
find('first')
=============
-``find('first', $params)`` will return one result, you'd use this for any case
+``find('first', $params)`` will return one result. You'd use this for any case
where you expect only one result. Below are a couple of simple (controller code)
examples::
@@ -63,8 +62,8 @@ examples::
// ...
}
-In the first example, no parameters at all are passed to find -
-therefore no conditions or sort order will be used. The format
+In the first example, no parameters at all are passed to find, so
+no conditions or sort order will be used. The format
returned from ``find('first')`` call is of the form::
Array
@@ -112,15 +111,15 @@ couple of simple (controller code) examples::
Don't pass ``fields`` as an array to ``find('count')``. You would
only need to specify fields for a DISTINCT count (since otherwise,
- the count is always the same - dictated by the conditions).
+ the count is always the same, dictated by the conditions).
.. _model-find-all:
find('all')
===========
-``find('all', $params)`` returns an array of (potentially multiple) results.
-It is in fact the mechanism used by all ``find()`` variants, as
+``find('all', $params)`` returns an array of potentially multiple results.
+It is, in fact, the mechanism used by all ``find()`` variants, as
well as ``paginate``. Below are a couple of simple (controller
code) examples::
@@ -139,8 +138,8 @@ code) examples::
.. note::
- In the above example ``$allAuthors`` will contain every user in the
- users table. There will be no condition applied to the find as none
+ In the above example, ``$allAuthors`` will contain every user in the
+ users table. There will be no condition applied to the find, since none
were passed.
The results of a call to ``find('all')`` will be of the following
@@ -175,7 +174,7 @@ find('list')
============
``find('list', $params)`` returns an indexed array, useful for any
-place where you would want a list such as for populating input select
+place where you would want a list, such as for populating input select
boxes. Below are a couple of simple (controller code) examples::
public function some_function() {
@@ -195,8 +194,8 @@ boxes. Below are a couple of simple (controller code) examples::
.. note::
- In the above example ``$allAuthors`` will contain every user in the
- users table. There will be no condition applied to the find as none
+ In the above example, ``$allAuthors`` will contain every user in the
+ users table. There will be no condition applied to the find, since none
were passed.
The results of a call to ``find('list')`` will be in the following
@@ -213,9 +212,9 @@ form::
[3] => 'displayValue3',
)
-When calling ``find('list')`` the ``fields`` passed are used to
-determine what should be used as the array key, value and
-optionally what to group the results by. By default the primary key
+When calling ``find('list')``, the ``fields`` passed are used to
+determine what should be used as the array key and value, and
+optionally what to group the results by. By default, the primary key
for the model is used for the key, and the display field (which can
be configured using the model attribute
:ref:`model-displayField`) is used for the value.
@@ -355,17 +354,17 @@ call to ``find('threaded')`` will be of the following form::
)
)
-The order results appear can be changed as it is influenced by the
+The order in which results appear can be changed, as it is influenced by the
order of processing. For example, if ``'order' => 'name ASC'`` is
passed in the params to ``find('threaded')``, the results will
-appear in name order. Likewise any order can be used, there is no
-inbuilt requirement of this method for the top result to be
+appear in name order. Any order can be used; there is no
+built-in requirement of this method for the top result to be
returned first.
.. warning::
If you specify ``fields``, you need to always include the
- id & parent_id (or their current aliases)::
+ id and parent_id (or their current aliases)::
public function some_function() {
$categories = $this->Category->find('threaded', array(
@@ -373,7 +372,7 @@ returned first.
));
}
- Otherwise the returned array will not be of the expected nested structure from above.
+ Otherwise, the returned array will not be of the expected nested structure from above.
.. _model-find-neighbors:
@@ -395,9 +394,9 @@ return the row before and after the one you request. Below is a simple
You can see in this example the two required elements of the
``$params`` array: field and value. Other elements are still
-allowed as with any other find (Ex: If your model acts as
-containable, then you can specify 'contain' in ``$params``). The
-format returned from a ``find('neighbors')`` call is in the form:
+allowed as with any other find. (For example: If your model acts as
+containable, then you can specify 'contain' in ``$params``.) The
+result returned from a ``find('neighbors')`` call is in the form:
::
@@ -451,11 +450,11 @@ format returned from a ``find('neighbors')`` call is in the form:
Creating custom find types
==========================
-The ``find`` method is flexible enough to accept your custom finders, this is
+The ``find`` method is flexible enough to accept your custom finders. This is
done by declaring your own types in a model variable and by implementing a special
function in your model class.
-A Model Find Type is a shortcut to find options. For example, the following two finds are equivalent
+A Model Find Type is a shortcut to find() options. For example, the following two finds are equivalent
::
@@ -481,8 +480,8 @@ change you need to do is add your type to the :php:attr:`Model::$findMethods` va
}
Basically this is just telling CakePHP to accept the value ``available`` as the first
-argument of the ``find`` function. Next step is to implement the function ``_findAvailable``.
-This is done by convention, if you wanted to implement a finder called ``myFancySearch`` then
+argument of the ``find`` function. The next step is to implement the function ``_findAvailable``.
+This is done by convention. If you wanted to implement a finder called ``myFancySearch``, then
the method to implement would be named ``_findMyFancySearch``.
::
@@ -514,7 +513,7 @@ This all comes together in the following example (controller code):
}
-The special ``_find[Type]`` methods receive 3 arguments as shown above. The first one
+The special ``_find[Type]`` methods receive three arguments as shown above. The first one
means the state of the query execution, which could be either ``before`` or ``after``. It
is done this way because this function is just a sort of callback function that has the
ability to modify the query before it is done, or to modify the results after they are fetched.
@@ -524,7 +523,7 @@ The ``before`` state is the moment to modify the query, bind new associations, a
behaviors, and interpret any special key that is passed in the second argument of ``find``. This
state requires you to return the $query argument (modified or not).
-The ``after`` state is the perfect place to inspect the results, inject new data, process it
+The ``after`` state is the perfect place to inspect the results, inject new data, process it in order
to return it in another format, or do whatever you like to the recently fetched data. This state
requires you to return the $results array (modified or not).
@@ -549,8 +548,23 @@ It is also possible to paginate via a custom find type as follows:
Setting the ``$this->paginate`` property as above on the controller will result in the ``type``
of the find becoming ``available``, and will also allow you to continue to modify the find results.
+To simply return the count of a custom find type, call ``count`` like you normally would, but pass in the
+find type in an array for the second argument.
+
+::
+
+ class ArticlesController extends AppController {
+
+ // Will find the count of all published articles (using the available find defined above)
+ public function index() {
+ $count = $this->Article->find('count', array(
+ 'type' => 'available'
+ ));
+ }
+ }
+
If your pagination page count is becoming corrupt, it may be necessary to add the following code to
-your ``AppModel``, which should fix pagination count:
+your ``AppModel``, which should fix the pagination count:
::
@@ -593,7 +607,7 @@ your ``AppModel``, which should fix pagination count:
You no longer need to override _findCount for fixing incorrect count results.
The ``'before'`` state of your custom finder will now be called again with
$query['operation'] = 'count'. The returned $query will be used in ``_findCount()``
-If needed you can distinguish by checking for ``'operation'`` key
+If necessary, you can distinguish by checking the ``'operation'`` key
and return a different ``$query``::
protected function _findAvailable($state, $query, $results = array()) {
@@ -682,10 +696,10 @@ findBy() functions return results like ``find('first')``
``query(string $query)``
SQL calls that you can't or don't want to make via other model
-methods (this should only rarely be necessary) can be made using
-the model's ``query()`` method.
+methods can be made using the model's ``query()`` method
+(though this should only rarely be necessary).
-If you use this method be sure to properly escape all parameters using the
+If you use this method, be sure to properly escape all parameters using the
``value()`` method on the database driver. Failing to escape parameters
will create SQL injection vulnerabilities.
@@ -766,9 +780,9 @@ which returns::
Returns the value of a single field, specified as ``$name``, from
the first record matched by $conditions as ordered by $order. If no
-conditions are passed and the model id is set, will return the
+conditions are passed and the model id is set, it will return the
field value for the current model result. If no matching record is
-found returns false.
+found, it returns false.
::
@@ -816,8 +830,8 @@ Complex Find Conditions
=======================
Most of the model's find calls involve passing sets of conditions
-in one way or another. In general CakePHP prefers using arrays for
-expressing any conditions that needs to be put after the WHERE clause
+in one way or another. In general, CakePHP prefers using arrays for
+expressing any conditions that need to be put after the WHERE clause
in any SQL query.
Using arrays is clearer and easier to read, and also makes it very
@@ -826,7 +840,12 @@ your query (fields, values, operators, etc.) into discrete,
manipulatable parts. This allows CakePHP to generate the most
efficient query possible, ensure proper SQL syntax, and properly
escape each individual part of the query. Using the array syntax
-also enables CakePHP to secure your queries against any SQL injection attack
+also enables CakePHP to secure your queries against any SQL injection attack.
+
+.. warning::
+
+ CakePHP only escapes the array values. You should **never** put user data
+ into the keys. Doing so will make you vulnerable to SQL injections.
At its most basic, an array-based query looks like this::
@@ -835,8 +854,8 @@ At its most basic, an array-based query looks like this::
$this->Post->find('first', array('conditions' => $conditions));
The structure here is fairly self-explanatory: it will find any
-post where the title equals "This is a post". Note that we could
-have used just "title" as the field name, but when building
+post where the title equals "This is a post" and the author id is equal to 1. Note
+that we could have used just "title" as the field name, but when building
queries, it is good practice to always specify the model name, as
it improves the clarity of the code, and helps prevent collisions
in the future, should you choose to change your schema.
@@ -859,7 +878,7 @@ title was in a given set of values::
)
To do a NOT IN(...) match to find posts where the title is not in
-the given set of values::
+the given set of values, do the following::
array(
"NOT" => array(
@@ -879,12 +898,12 @@ You can also create finds that compare two fields in the database::
array("Post.created = Post.modified")
-This above example will return posts where the created date is
-equal to the modified date (ie it will return posts that have never
+The above example will return posts where the created date is
+equal to the modified date (that is, it will return posts that have never
been modified).
Remember that if you find yourself unable to form a WHERE clause in
-this method (ex. boolean operations), you can always specify it as
+this method (for example, boolean operations), you can always specify it as
a string like::
array(
@@ -892,8 +911,8 @@ a string like::
// other conditions as usual
)
-By default, CakePHP joins multiple conditions with boolean AND;
-which means, the snippet above would only match posts that have
+By default, CakePHP joins multiple conditions with boolean AND.
+This means the snippet above would only match posts that have
been created in the past two weeks, and have a title that matches
one in the given set. However, we could just as easily find posts
that match either condition::
@@ -905,11 +924,11 @@ that match either condition::
CakePHP accepts all valid SQL boolean operations, including AND, OR,
NOT, XOR, etc., and they can be upper or lower case, whichever you
-prefer. These conditions are also infinitely nest-able. Let's say
+prefer. These conditions are also infinitely nestable. Let's say
you had a belongsTo relationship between Posts and Authors. Let's
say you wanted to find all the posts that contained a certain
keyword ("magic") or were created in the past two weeks, but you
-want to restrict your search to posts written by Bob::
+wanted to restrict your search to posts written by Bob::
array(
"Author.name" => "Bob",
@@ -981,7 +1000,7 @@ operators, such as MIN(), MAX(), etc., in a similar fashion::
'order' = >array('User.id DESC')
)
-You can create very complex conditions, by nesting multiple
+You can create very complex conditions by nesting multiple
condition arrays::
array(
@@ -1001,7 +1020,7 @@ condition arrays::
)
)
-Which produces the following SQL::
+which produces the following SQL::
SELECT `Company`.`id`, `Company`.`name`,
`Company`.`description`, `Company`.`location`,
@@ -1020,12 +1039,12 @@ Which produces the following SQL::
Sub-queries
-----------
-For this example, imagine we have a "users" table with "id", "name"
-and "status". The status can be "A", "B" or "C". And we want to get
-all the users that have status other than "B" using sub-query.
+For this example, imagine that we have a "users" table with "id", "name"
+and "status". The status can be "A", "B" or "C". We want to retrieve
+all the users that have status other than "B" using a sub-query.
-In order to achieve that we are going to get the model data source
-and ask it to build the query as if we were calling a find method,
+In order to achieve that, we are going to get the model data source
+and ask it to build the query as if we were calling a find() method,
but it will just return the SQL statement. After that we make an
expression and add it to the conditions array::
@@ -1071,7 +1090,7 @@ This should generate the following SQL::
"User2"."status" = 'B'
)
-Also, if you need to pass just part of your query as raw SQL as the
+Also, if you need to pass just part of your query as raw SQL as
above, datasource **expressions** with raw SQL work for any part of
the find query.
diff --git a/en/models/virtual-fields.rst b/en/models/virtual-fields.rst
index 41360a2805..f1b5227d60 100644
--- a/en/models/virtual-fields.rst
+++ b/en/models/virtual-fields.rst
@@ -22,7 +22,7 @@ would be::
And with PostgreSQL::
public $virtualFields = array(
- 'name' => 'User.first_name || \' \' || User.last_name'
+ 'name' => "User.first_name || ' ' || User.last_name"
);
In subsequent find operations, your User results would contain a
diff --git a/en/plugins.rst b/en/plugins.rst
index 301c36d3b4..265ad89358 100644
--- a/en/plugins.rst
+++ b/en/plugins.rst
@@ -60,7 +60,7 @@ three plugins, and not the rest.
Finally, you can also specify a set of defaults for loadAll which will apply to
every plugin that doesn't have a more specific configuration.
-Load the bootstrap file from all plugins, and the routes from the Blog plugin::
+Load the bootstrap file from all plugins, and additionally the routes from the Blog plugin::
CakePlugin::loadAll(array(
array('bootstrap' => true),
@@ -209,6 +209,16 @@ Please refer to the chapter
:doc:`/console-and-shells/code-generation-with-bake` if you
have any problems with using the command line.
+.. warning::
+
+ Plugins do not work as namespacing to separate code.
+ Due to PHP lacking namespaces in older versions
+ you cannot have the same class,
+ or same filename, in your plugins.
+ Even if it is two different plugins.
+ So use unique classes and filenames, possible prefixing
+ the class and filename with the plugin name.
+
Plugin Controllers
==================
diff --git a/en/tutorials-and-examples/blog-auth-example/auth.rst b/en/tutorials-and-examples/blog-auth-example/auth.rst
index 84d53da764..0ff83f4f92 100644
--- a/en/tutorials-and-examples/blog-auth-example/auth.rst
+++ b/en/tutorials-and-examples/blog-auth-example/auth.rst
@@ -226,6 +226,8 @@ Password hashing is not done yet, open your ``app/Model/User.php`` model file
and add the following::
// app/Model/User.php
+
+ App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
@@ -388,7 +390,7 @@ logic as possible into models. Let's then implement the function::
// app/Model/Post.php
public function isOwnedBy($post, $user) {
- return $this->field('id', array('id' => $post, 'user_id' => $user)) === $post;
+ return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false;
}
diff --git a/en/tutorials-and-examples/blog/part-two.rst b/en/tutorials-and-examples/blog/part-two.rst
index ec95620e1f..d14a446ed9 100644
--- a/en/tutorials-and-examples/blog/part-two.rst
+++ b/en/tutorials-and-examples/blog/part-two.rst
@@ -25,9 +25,9 @@ in the PostsController, and will be tied to a database table called
CakePHP will dynamically create a model object for you if it
cannot find a corresponding file in /app/Model. This also means
- that if you accidentally name your file wrong (i.e. post.php or
- posts.php), CakePHP will not recognize any of your settings and will
- use the defaults instead.
+ that if you accidentally name your file wrong (for example, post.php
+ or posts.php instead of Post.php), CakePHP will not recognize
+ any of your settings and will use the defaults instead.
For more on models, such as table prefixes, callbacks, and
validation, check out the :doc:`/models` chapter of the
@@ -50,7 +50,7 @@ directory. Here's what the basic controller should look like::
Now, let's add an action to our controller. Actions often represent
a single function or interface in an application. For example, when
-users request www.example.com/posts/index (which is also the same
+users request www.example.com/posts/index (which is the same
as www.example.com/posts/), they might expect to see a listing of
posts. The code for that action would look something like this::
@@ -63,7 +63,7 @@ posts. The code for that action would look something like this::
}
By defining function ``index()``
-in our PostsController, users can now access the logic there by
+in our PostsController, users can access the logic there by
requesting www.example.com/posts/index. Similarly, if we were to
define a function called ``foobar()``, users would be able to
access that at www.example.com/posts/foobar.
@@ -72,7 +72,7 @@ access that at www.example.com/posts/foobar.
You may be tempted to name your controllers and actions a certain
way to obtain a certain URL. Resist that temptation. Follow CakePHP
- conventions (plural controller names, etc.) and create readable,
+ conventions (capitalization, plural names, etc.) and create readable,
understandable action names. You can map URLs to your code using
"routes" covered later on.
@@ -94,15 +94,15 @@ logic and flow defined by our controller, let's create a view for
the index action we created above.
CakePHP views are just presentation-flavored fragments that fit inside
-an application's layout. For most applications they're HTML mixed
+an application's layout. For most applications, they're HTML mixed
with PHP, but they may end up as XML, CSV, or even binary data.
-Layouts are presentation code that is wrapped around a view, and
-can be defined and switched between, but for now, let's just use
-the default.
+A layout is presentation code that is wrapped around a view.
+Multiple layouts can be defined, and you can switch between
+them, but for now, let's just use the default.
-Remember in the last section how we assigned the 'posts' variable
-to the view using the ``set()`` method? That would hand down data
+Remember how in the last section we assigned the 'posts' variable
+to the view using the ``set()`` method? That would pass data
to the view that would look something like this::
// print_r($posts) output:
@@ -145,8 +145,8 @@ to the view that would look something like this::
)
CakePHP's view files are stored in ``/app/View`` inside a folder
-named after the controller they correspond to (we'll have to create
-a folder named 'Posts' in this case). To format this post data in a
+named after the controller to which they correspond. (We'll have to create
+a folder named 'Posts' in this case.) To format this post data into a
nice table, our view code might look something like this
.. code-block:: php
@@ -176,8 +176,6 @@ nice table, our view code might look something like this
-Hopefully this should look somewhat simple.
-
You might have noticed the use of an object called ``$this->Html``.
This is an instance of the CakePHP :php:class:`HtmlHelper` class. CakePHP
comes with a set of view helpers that make things like linking,
@@ -199,13 +197,14 @@ http://www.example.com/posts/index. You should see your view,
correctly formatted with the title and table listing of the posts.
If you happened to have clicked on one of the links we created in
-this view (that link a post's title to a URL /posts/view/some\_id),
-you were probably informed by CakePHP that the action hasn't yet
+this view (which link a post's title to a URL /posts/view/some\_id),
+you were probably informed by CakePHP that the action hadn't yet
been defined. If you were not so informed, either something has
gone wrong, or you actually did define it already, in which case
you are very sneaky. Otherwise, we'll create it in the
PostsController now::
+ // File: /app/Controller/PostsController.php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
@@ -227,7 +226,7 @@ PostsController now::
}
The ``set()`` call should look familiar. Notice we're using
-``findById()`` rather than ``find('all')`` because we only really want
+``findById()`` rather than ``find('all')`` because we only want
a single post's information.
Notice that our view action takes a parameter: the ID of the post
@@ -235,7 +234,7 @@ we'd like to see. This parameter is handed to the action through
the requested URL. If a user requests ``/posts/view/3``, then the value
'3' is passed as ``$id``.
-We also do a bit of error checking to ensure a user is actually
+We also do a bit of error checking to ensure that a user is actually
accessing a record. If a user requests ``/posts/view``, we will throw a
``NotFoundException`` and let the CakePHP ErrorHandler take over. We
also perform a similar check to make sure the user has accessed a
@@ -261,7 +260,7 @@ Adding Posts
============
Reading from the database and showing us the posts is a great
-start, but let's allow for the adding of new posts.
+start, but let's allow for adding new posts.
First, start by creating an ``add()`` action in the
PostsController::
@@ -313,8 +312,8 @@ PostsController::
your AppController.
Here's what the ``add()`` action does: if the HTTP method of the
-request was POST, try to save the data using the Post model. If for some
-reason it doesn't save, just render the view. This gives us a
+request was POST, it tries to save the data using the Post model. If for some
+reason it doesn't save, it just renders the view. This gives us a
chance to show the user validation errors or other warnings.
Every CakePHP request includes a ``CakeRequest`` object which is accessible using
@@ -334,7 +333,7 @@ redirection. In the layout we have
message and clears the corresponding session variable. The
controller's :php:meth:`Controller::redirect` function
redirects to another URL. The param ``array('action' => 'index')``
-translates to URL /posts i.e the index action of posts controller.
+translates to URL /posts (that is, the index action of the posts controller).
You can refer to :php:func:`Router::url()` function on the
`API `_ to see the formats in which you can specify a
URL for various CakePHP functions.
@@ -343,15 +342,15 @@ Calling the ``save()`` method will check for validation errors and
abort the save if any occur. We'll discuss how those errors are
handled in the following sections.
-The reason why we call the ``create()`` method first is to resets the model
+We call the ``create()`` method first in order to reset the model
state for saving new information. It does not actually create a record in the
-database but clears Model::$id and sets Model::$data based on your database
+database, but clears Model::$id and sets Model::$data based on your database
field defaults.
Data Validation
===============
-CakePHP goes a long way in taking the monotony out of form input
+CakePHP goes a long way toward taking the monotony out of form input
validation. Everyone hates coding up endless forms and their
validation routines. CakePHP makes it easier and faster.
@@ -373,7 +372,7 @@ Here's our add view:
echo $this->Form->end('Save Post');
?>
-Here, we use the FormHelper to generate the opening tag for an HTML
+We use the FormHelper to generate the opening tag for an HTML
form. Here's the HTML that ``$this->Form->create()`` generates:
.. code-block:: html
@@ -381,9 +380,9 @@ form. Here's the HTML that ``$this->Form->create()`` generates:
` a été ajoutée.
+ Il a pour objectif d'aider à la création de librairies autocompletion pour
+ les variables d'environnement de shell comme bash, ou zsh. Aucun script shell
+ n'est inclu dans CakePHP, mais les outils sous-jacents sont maintenant
+ disponibles.
+
+Controller
+==========
+
+AuthComponent
+-------------
+
+- ``loggedIn()`` est maintenant dépréciée et sera retirée dans 3.0.
+- Lors de l'utilisation de ``ajaxLogin``, AuthComponent va retourner un code de
+ statut ``403`` au lieu de ``200`` quand l'utilisateur n'est pas authentifié.
+
+CookieComponent
+---------------
+
+- :php:class:`CookieComponent` peut utiliser le nouveau chiffrement AES-256
+ offert par :php:class:`Security`. Vous pouvez activer ceci en appelant
+ :php:meth:`CookieComponent::type()` avec 'aes'.
+
+RequestHandlerComponent
+-----------------------
+
+- :php:meth:`RequestHandlerComponent::renderAs()` ne définit plus
+ ``Controller::$ext``. Cela posait des problèmes lors de l'utilisation d'une
+ extension autre que celle par défaut pour les vues.
+
+AclComponent
+------------
+
+- Les échecs de vérification de noeud ACL sont maintenant directement mis dans
+ les logs. L'appel de ``trigger_error()`` a été retiré.
+
+Scaffold
+--------
+- Le scaffold dynamique est maintenant déprécié et sera retiré dans 3.0.
+
+
+Core
+====
+
+CakePlugin
+----------
+
+- :php:meth:`CakePlugin::loadAll()` fusionne maintenant les options par défaut
+ et celles spécifiques au plugin comme on peut s'y attendre intuitivement.
+ Regardez les cas de test pour plus de détails.
+
+Event
+=====
+
+EventManager
+------------
+
+Les Events liés au gestionnaire global sont maintenant déclenchés dans l'ordre
+de priorité des events liés au gestionnaire local. Ceci peut entraîner le
+déclenchement des listeners dans un ordre différent par rapport aux versions
+précédentes. Au lieu d'avoir des listeners globaux attrapés, et ensuite
+instancier les listeners étant déclenchés plus tard, les deux ensembles de
+listeners sont combinés en une liste de listeners basé sur leurs priorités
+et ensuite déclenchés en un ensemble. Les listeners globaux d'une prioriété
+donnée sont toujours déclenchés avant l'instanciation des listeners.
+
+I18n
+====
+
+- La classe :php:class:`I18n` a de nombreuses nouvelles constantes. Ces
+ constantes vous permettent de remplacer les hardcoded integers avec des
+ valeurs lisibles par exemple : ``I18n::LC_MESSAGES``.
+
+
+Model
+=====
+
+- Les nombres unsigned sont maintenant supportés par les sources de données
+ qui les fournissent (MySQL). Vous pouvez définir l'option ``unsigned`` à true
+ dans vos fichiers schema/fixture pour commencer à utiliser cette
+ fonctionnalité.
+- Les Jointures inclues dans les requêtes sont maintenant ajoutées **après** que
+ les jointures des associations sont ajoutées. Cela facilite la jointure des
+ tables qui dépendent d'associations générées.
+
+Network
+=======
+
+CakeEmail
+---------
+
+- Les adresses Email dans CakeEmail ne sont pas validées avec ``filter_var``
+ par défaut. Cela assouplit les règles d'addresse email en autorisant les
+ addresses d'email interne comme ``root@localhost`` par exemple.
+- Vous pouvez maintenant spécifier la clé ``layout`` dans la config d'email
+ sans avoir à spécifier la clé ``template``.
+
+CakeRequest
+-----------
+
+- :php:meth:`CakeRequest::addDetector()` supporte maintenant ``options`` qui
+ accepte un tableau des options valides lors de la création de paramètre
+ basé sur les detecteurs.
+
+- ``CakeRequest::onlyAllow()`` a été dépréciée. En remplacement, une nouvelle
+ méthode nommée :php:meth:`CakeRequest::allowMethod()` a été ajoutée avec
+ une fonctionnalité identique. Le nouveau nom de la méthode est plus intuitif
+ et transmet mieux ce que la méthode fait.
+
+CakeSession
+-----------
+
+- Sessions ne seront pas démarrées si elles sont connues pour être vides. Si
+ le cookie de session ne peut être trouvé, une session ne sera pas démarrée
+ à moins qu'une opération d'écriture ne soit faite.
+
+
+Routing
+=======
+
+Router
+------
+
+- :php:meth:`Router::mapResources()` accepte la clé ``connectOptions`` dans
+ l'argument ``$options``. Regardez :ref:`custom-rest-routing` pour plus de
+ détails.
+
+Utility
+=======
+
+Debugger
+--------
+
+- ``Debugger::dump()`` et ``Debugger::log()`` supportent un paramètre
+ ``$depth``. Ce nouveau paramètre facilite la sortie de structures d'objet
+ imbriquée plus profonde.
+
+Hash
+----
+
+- :php:meth:`Hash::insert()` et :php:meth:`Hash::remove()` supportent maintenant
+ les expressions de matcher dans les selecteurs de chemin.
+
+File
+----
+
+- :php:meth:`File::replaceText()` a été ajoutée. Cette méthode vous permet
+ de facilement remplacer le texte en un fichier en utilisant ``str_replace``.
+
+
+Folder
+------
+
+- :php:meth:`Folder::addPathElement()` accepte maintenant un tableau pour le
+ paramètre ``$element``.
+
+Security
+--------
+
+- :php:meth:`Security::encrypt()` et :php:meth:`Security::decrypt()` ont été
+ ajoutées. Ces méthodes montrent une API très simple pour accéder au
+ chiffrement symétrique AES-256.
+ Ils doivent être utilisés en faveur des méthodes ``cipher()`` et
+ ``rijndael()``.
+
+Validation
+----------
+
+- Le troisième paramètre pour :php:meth:`Validation::inList()` et
+ :php:meth:`Validation::multiple()` a été modifié de `$strict` en
+ `$caseInsensitive`. `$strict` a été retiré puisqu'il ne fonctionnait pas
+ correctement et pouvait être facilement contourné. Vous pouvez maintenant
+ définir ce paramètre à true pour des comparaisons non sensibles à la casse.
+ Par défaut, c'est à false et cela ca comparer la valeur et lister la casse
+ sensible comme avant.
+
+- Le paramètre ``$mimeTypes`` de :php:meth:`Validation::mimeType()` peut aussi
+ être une chaîne regex. Aussi maintenant quand ``$mimeTypes`` est un tableau
+ ses valeurs sont en minuscule.
+
+
+Logging
+=======
+
+FileLog
+-------
+
+- CakeLog ne s'auto-configure plus tout seul. Au final, tous les fichiers de
+ log ne seront plus auto-créés si aucun flux n'est écouté. Assurez-vous que
+ vous avez au moins un moteur par défaut configuré si vous voulez écouter tous
+ les types et les niveaux.
+
+Error
+=====
+
+ExceptionRenderer
+-----------------
+
+ExceptionRenderer remplit maintenant les tempplates d'erreur avec les variables
+"code", "message" et "url". "name" a été déprécié mais est toujours disponible.
+Cela uniformise les variables à travers tous les templates d'erreur.
+
+Testing
+=======
+
+- Les fichiers de fixture peuvent maintenant être placés dans des
+ sous-répertoires. Vous pouvez utiliser les fixtures dans les sous-répertoires
+ en incluant le nom du répertoire après le ``.``. Par exemple,
+ `app.my_dir/article` va charger ``App/Test/Fixture/my_dir/ArticleFixture``.
+ On notera que le répertoire de fixture ne sera pas inflecté ou modifié dans
+ tous les cas.
+- Les Fixtures peuvent maintenant définir ``$canUseMemory`` à false pour
+ désactiver le moteur de stockage de la mémoire utilisée dans MySQL.
+
+View
+====
+
+View
+----
+
+- ``$title_for_layout`` est déprécié. Utilisez ``$this->fetch('title');`` et
+ ``$this->assign('title', 'your-page-title');`` à la place.
+- :php:meth:`View::get()` accepte maintenant un deuxième argument pour fournir
+ une valeur par défaut.
+
+FormHelper
+----------
+
+- FormHelper va maintenant générer les inputs de fichier pour les types de champ
+ ``binary``.
+- :php:meth:`FormHelper::end()` a eu un deuxième paramètre ajouté. Ce paramètre
+ vous laisse passer les propriétés supplémentaires aux champs utilisés pour
+ sécuriser les formulaires avec SecurityComponent.
+- :php:meth:`FormHelper::end()` et :php:meth:`FormHelper::secure()` vous
+ permettent de passer des options supplémentaires qui sont changées en
+ attributs sur les inputs cachés générés. C'est utile quand vous voulez
+ utiliser l'attribut HTML5 ``form``.
+
+PaginationHelper
+----------------
+
+- :php:meth:`PaginatorHelper::sort()` a maintenant une option ``lock`` pour
+ créer le tri des liens de pagination avec seulement la direction par défaut.
+
+ScaffoldView
+------------
+
+- Le Scaffold Dynamique est mainteanant déprécié et sera retiré dans 3.0.
diff --git a/fr/appendices/glossary.rst b/fr/appendices/glossary.rst
index 9e214b2c2f..050853af92 100644
--- a/fr/appendices/glossary.rst
+++ b/fr/appendices/glossary.rst
@@ -52,16 +52,16 @@ Glossaire
)
CSRF
- Les Reqûetes de site croisées de Contrefaçon. Emêche les attaques de
+ Les Requêtes de site croisées de Contrefaçon. Empêche les attaques de
replay, les soumissions doubles et les requêtes contrefaîtes provenant
d'autres domaines.
routes.php
Un fichier dans APP/Config qui contient la configuration de routing.
Ce fichier est inclus avant que chaque requête soit traitée.
- Il devrait connecter toutes les routes dont votre applications a besoin
- afin que les requêtes puissent être routées aux contrôleur + action
- corrects.
+ Il devrait connecter toutes les routes dont votre application a besoin
+ afin que les requêtes puissent être routées aux contrôleurs + actions
+ correctes.
DRY
Ne vous répétez pas vous-même. Est un principe de développement de
diff --git a/fr/console-and-shells.rst b/fr/console-and-shells.rst
index 6910f17f82..97b8eec443 100644
--- a/fr/console-and-shells.rst
+++ b/fr/console-and-shells.rst
@@ -417,7 +417,7 @@ voulez l'arrêter, ou forcer à l'avoir::
Ce qui est au-dessus met la sortie objet dans un mode de sortie en ligne. Dans
le mode de sortie en ligne, il n'y a aucun style du tout. Il y a trois modes
-que vous pouvez utiliser::
+que vous pouvez utiliser:
* ``ConsoleOutput::RAW`` - Sortie en ligne, aucun style ou format ne sera fait
C'est un bon mode à utiliser si vous sortez du XML ou si voulez débugger
@@ -1071,6 +1071,7 @@ Plus de sujets
:maxdepth: 1
console-and-shells/cron-jobs
+ console-and-shells/completion-shell
console-and-shells/code-generation-with-bake
console-and-shells/schema-management-and-migrations
console-and-shells/i18n-shell
diff --git a/fr/console-and-shells/code-generation-with-bake.rst b/fr/console-and-shells/code-generation-with-bake.rst
index b9ed4e52b5..87545ea31b 100755
--- a/fr/console-and-shells/code-generation-with-bake.rst
+++ b/fr/console-and-shells/code-generation-with-bake.rst
@@ -54,6 +54,12 @@ ligne de commande ::
$ cake bake plugin plugin_name
$ cake bake all
+.. versionchanged:: 2.5
+ Les fichiers Test créés par ``bake test`` incluent les appels vers
+ `PHPunit's markTestIncomplete() `_
+ pour attirer votre attention sur les méthodes de test vides. Avant 2.5, les
+ tests vides passaient sans messages.
+
Modifier le HTML par défaut produit par les templates de bake
=============================================================
diff --git a/fr/console-and-shells/completion-shell.rst b/fr/console-and-shells/completion-shell.rst
new file mode 100644
index 0000000000..3f3a4facff
--- /dev/null
+++ b/fr/console-and-shells/completion-shell.rst
@@ -0,0 +1,118 @@
+Completion du Shell
+###################
+
+.. versionadded:: 2.5
+
+Travailler avec la console donne au développeur beaucoup de possibilités mais
+devoir complètement connaître et écrire ces commandes peut être fastidieux.
+Spécialement lors du développement de nouveaux shells où les commandes
+diffèrent à chaque itération. Les Shells de Completion aident ce niveau-là
+en fournissant une API pour écrire les scripts de completion pour les shells
+comme like bash, zsh, fish etc...
+
+Sous Commandes
+==============
+
+Les Shell de Completion se compose d'un certain nombre de sous-commandes pour
+permettre au développeur de créer son script de completion. Chacun pour une
+étape différente dans le processus d'autocompletion.
+
+commandes
+---------
+
+Pour les premières étapes, les commandes sortent les Commandes de Shell
+disponibles, y compris le nom du plugin quand il est valable. (Toutes les
+possibilités retournées, pour celle-ci et les autres sous-commandes, sont
+séparées par un espace.) Par exemple::
+
+ ./Console/cake Completion commands
+
+Retourne::
+
+ acl api bake command_list completion console i18n schema server test testsuite upgrade
+
+Votre script de completion peut selectionner les commandes pertinentes de cette
+liste pour continuer avec. (Pour celle-là et les sous-commandes suivantes.)
+
+subCommands
+-----------
+
+Une fois que la commande préférée a été choisie, les subCommands apparaissent
+à la deuxième étape et sort la sous-commande possible pour la commande de
+shell donnée. Par exemple::
+
+ ./Console/cake Completion subcommands bake
+
+Retourne::
+
+ controller db_config fixture model plugin project test view
+
+options
+--------
+
+En troisième et dernière options, les options de sortie pour une (sous)
+commande donnée comme défini dans getOptionParser. (Y compris les options par
+défaut héritées du Shell.)
+Par exemple::
+
+ ./Console/cake Completion options bake
+
+Retourne::
+
+ --help -h --verbose -v --quiet -q --connection -c --theme -t
+
+Exemple de Bash
+===============
+
+L'exemple de bash suivant provient de l'auteur original::
+
+ # bash completion for CakePHP console
+
+ _cake()
+ {
+ local cur prev opts cake
+ COMPREPLY=()
+ cake="${COMP_WORDS[0]}"
+ cur="${COMP_WORDS[COMP_CWORD]}"
+ prev="${COMP_WORDS[COMP_CWORD-1]}"
+
+ if [[ "$cur" == -* ]] ; then
+ if [[ ${COMP_CWORD} = 1 ]] ; then
+ opts=$(${cake} Completion options)
+ elif [[ ${COMP_CWORD} = 2 ]] ; then
+ opts=$(${cake} Completion options "${COMP_WORDS[1]}")
+ else
+ opts=$(${cake} Completion options "${COMP_WORDS[1]}" "${COMP_WORDS[2]}")
+ fi
+
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ return 0
+ fi
+
+ if [[ ${COMP_CWORD} = 1 ]] ; then
+ opts=$(${cake} Completion commands)
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ return 0
+ fi
+
+ if [[ ${COMP_CWORD} = 2 ]] ; then
+ opts=$(${cake} Completion subcommands $prev)
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ if [[ $COMPREPLY = "" ]] ; then
+ COMPREPLY=( $(compgen -df -- ${cur}) )
+ return 0
+ fi
+ return 0
+ fi
+
+
+ opts=$(${cake} Completion fuzzy "${COMP_WORDS[@]:1}")
+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
+ if [[ $COMPREPLY = "" ]] ; then
+ COMPREPLY=( $(compgen -df -- ${cur}) )
+ return 0
+ fi
+ return 0;
+ }
+
+ complete -F _cake cake Console/cake
diff --git a/fr/contributing/cakephp-coding-conventions.rst b/fr/contributing/cakephp-coding-conventions.rst
index 5d03b42277..4ae710e71f 100644
--- a/fr/contributing/cakephp-coding-conventions.rst
+++ b/fr/contributing/cakephp-coding-conventions.rst
@@ -10,7 +10,7 @@ Vous pouvez utilisez le `CakePHP Code Sniffer
`_ pour vérifier que votre code
suit les normes requises.
-Ajout de nouvelles fonctionnalités
+Ajout de Nouvelles Fonctionnalités
==================================
Aucune nouvelle fonctionnalité ne devrait être ajoutée, sans avoir fait ses
@@ -21,7 +21,7 @@ Indentation
Un onglet sera utilisé pour l'indentation.
-Ainsi, l'indentation devrait ressembler à cela::
+Ainsi, l'indentation devrait ressembler à ceci::
// niveau de base
// niveau 1
@@ -35,16 +35,16 @@ Ou::
$stringVariable = "moose";
if ($booleanVariable) {
echo "Valeur boléenne si true";
- if ($stringVariable == "moose") {
+ if ($stringVariable === "moose") {
echo "Nous avons rencontré un moose";
}
}
-Structures de contrôle
+Structures de Contrôle
======================
Les structures de contrôle sont par exemple "``if``", "``for``", "``foreach``",
-"``while``", "``switch``" etc. En-dessous, une exemple avec "``if``"::
+"``while``", "``switch``" etc. Ci-dessous, un exemple avec "``if``"::
if ((expr_1) || (expr_2)) {
// action_1;
@@ -60,22 +60,21 @@ Les structures de contrôle sont par exemple "``if``", "``for``", "``foreach``",
* Toujours utiliser des accolades dans les structures de contrôle,
même si elles ne sont pas nécessaires. Elles augmentent la lisibilité
du code, et elles vous donnent moins d'erreurs logiques.
-
* L'ouverture des accolades doit être placée sur la même ligne que la
structure de contrôle. La fermeture des accolades doit être placée sur de
- nouvelles lignes, et ils devraient avoir le même niveau d'indentation que
- la structure de contrôle. La déclaration inclue dans les accolades doit
+ nouvelles lignes, et ils doivent avoir le même niveau d'indentation que
+ la structure de contrôle. La déclaration incluse dans les accolades doit
commencer sur une nouvelle ligne, et le code qu'il contient doit gagner un
nouveau niveau d'indentation.
-* Les attributs Inline ne devraient pas être utilisés à l'intérieur de les
+* Les attributs Inline ne devraient pas être utilisés à l'intérieur des
structures de contrôle.
::
- // mauvais = pas de parenthèses, déclaration mal placée
+ // mauvais = pas d'accolades, déclaration mal placée
if (expr) statement;
- // mauvais = pas de parenthèses
+ // mauvais = pas d'accolades
if (expr)
statement;
@@ -102,7 +101,7 @@ Les opérateurs ternaires sont permis quand l'opération entière rentre sur une
ligne. Les opérateurs ternaires plus longs doivent être séparés en
expression ``if else``. Les opérateurs ternaires ne doivent pas être imbriqués.
Des parenthèses optionnelles peuvent être utilisées autour de la condition
-vérifiée de l'opération pour clarifier::
+vérifiée de l'opération pour rendre le code plus clair::
// Bien, simple et lisible
$variable = isset($options['variable']) ? $options['variable'] : true;
@@ -122,7 +121,7 @@ un block PHP plus large, soit dans des tags PHP séparés::
You are the admin user.
";
+ echo '
You are the admin user.
';
endif;
?>
The following is also acceptable:
@@ -130,8 +129,8 @@ un block PHP plus large, soit dans des tags PHP séparés::
You are the admin user.
-Comparison
-==========
+Comparaison
+===========
Toujours essayer d'être aussi strict que possible. Si un test non strict
est délibéré, il peut être sage de le commenter afin d'éviter de le confondre
@@ -156,7 +155,7 @@ La valeur avec laquelle on vérifie devra être placée sur le côté droit::
// ...
}
-Appels des fonctions
+Appels des Fonctions
====================
Les fonctions doivent être appelées sans espace entre le nom de la fonction et
@@ -165,27 +164,27 @@ d'un appel de fonction::
$var = foo($bar, $bar2, $bar3);
-Comme vous pouvez le voir, il devrait y avoir un espace des deux côtés des
+Comme vous pouvez le voir, il doit y avoir un espace des deux côtés des
signes égal (=).
-Définition des méthodes
+Définition des Méthodes
=======================
-Exemple d'un définition de fonction::
+Exemple d'un définition de méthode::
- function someFunction($arg1, $arg2 = '') {
+ public function someFunction($arg1, $arg2 = '') {
if (expr) {
statement;
}
return $var;
}
-Les paramètres avec une valeur par défaut, devraient être placés en dernier
+Les paramètres avec une valeur par défaut, doivent être placés en dernier
dans la défintion de la fonction. Essayez de faire en sorte que vos fonctions
-retournent quelque chose, au moins true ou false = ainsi cela peut déterminer
-si l'appel de la fonction est un succès::
+retournent quelque chose, au moins ``true`` ou ``false``, ainsi cela peut
+déterminer si l'appel de la fonction est un succès::
- function connection($dns, $persistent = false) {
+ public function connection($dns, $persistent = false) {
if (is_array($dns)) {
$dnsInfo = $dns;
} else {
@@ -200,16 +199,57 @@ si l'appel de la fonction est un succès::
Il y a des espaces des deux côtés du signe égal.
-Commenter le code
+Typehinting
+-----------
+
+Les arguments qui attendent des objets ou des tableaux peuvent être typés.
+Nous ne typons que les méthodes publiques car le typage prend du temps::
+
+ /**
+ * Some method description.
+ *
+ * @param Model $Model Le model à utiliser.
+ * @param array $array Une valeur de tableau.
+ * @param boolean $boolean Une valeur boléenne.
+ */
+ public function foo(Model $Model, array $array, $boolean) {
+ }
+
+Ici ``$Model`` doit être une instance de ``Model`` et ``$array`` doit être un
+``array``.
+
+Notez que si vous souhaitez autoriser que ``$array`` soit aussi une instance
+de ``ArrayObject``, vous ne devez pas typer puisque ``array`` accepte seulement
+le type primitif::
+
+ /**
+ * Description de la method.
+ *
+ * @param array|ArrayObject $array Some array value.
+ */
+ public function foo($array) {
+ }
+
+Chaînage des Méthodes
+---------------------
+
+Le chaînage des méthodes doit avoir plusieurs méthodes réparties sur des
+lignes distinctes et indentées avec une tabulation::
+
+ $email->from('foo@example.com')
+ ->to('bar@example.com')
+ ->subject('Un super message')
+ ->send();
+
+Commenter le Code
=================
Tous les commentaires doivent être écrits en anglais, et doivent clairement
décrire le block de code commenté.
Les commentaires doivent inclure les tags de
-`phpDocumentor suivants `_:
+`phpDocumentor `_ suivants:
-* `@access `_
* `@author `_
* `@copyright `_
* `@deprecated `_
@@ -222,12 +262,13 @@ Les commentaires doivent inclure les tags de
* `@tutorial `_
* `@version `_
-Les tags de PhpDoc sont un peu du même style que les tags de JavaDoc dans Java.
-Les Tags sont seulement traités si ils sont la première chose dans la ligne
-DocBlock, par exemple::
+Les tags de PhpDoc sont un peu du même style que les tags de JavaDoc dans
+Java. Les tags sont seulement traités si ils sont la première chose dans la
+ligne DocBlock, par exemple::
/**
* Exemple de Tag.
+ *
* @author ce tag est analysé, mais @version est ignoré
* @version 1.0 ce tag est aussi analysé
*/
@@ -235,15 +276,19 @@ DocBlock, par exemple::
::
/**
- * Exemple de tags inline phpDoc.
+ * Exemple de tag inline phpDoc.
*
* Cette fonction travaille dur avec foo() pour gouverner le monde.
+ *
+ * @return void
*/
function bar() {
}
/**
* Foo function
+ *
+ * @return void
*/
function foo() {
}
@@ -251,7 +296,7 @@ DocBlock, par exemple::
Les blocks de commentaires, avec une exception du premier block dans le
fichier, doivent toujours être précédés par un retour à la ligne.
-Inclure les fichiers
+Inclure les Fichiers
====================
``include``, ``require``, ``include_once`` et ``require_once`` n'ont pas de
@@ -265,16 +310,17 @@ parenthèses::
require_once 'ClassFileName.php';
require_once $class;
-Quand on inclut les fichiers avec des classes ou librairies, utilisez seulement
-et toujours la fonction `require\_once `_.
+Quand vous incluez les fichiers avec des classes ou librairies, utilisez
+seulement et toujours la fonction
+`require\_once `_.
-Les tags PHP
+Les Tags PHP
============
Toujours utiliser les tags longs (````) plutôt que les tags courts
-( ?>).
+(`` ?>``).
-Convention de nommage
+Convention de Nommage
=====================
Fonctions
@@ -296,10 +342,10 @@ Les noms de classe doivent être écrites en CamelCase, par exemple::
Variables
---------
-Les noms de variable doivent être aussi descriptives que possibles, mais
-aussi courtes que possibles. Les variables normales doivent démarrer
-avec une lettre minuscule, et doivent être écrites en camelBack en cas
-de mots multiples. Les variables contenant des objets doivent démarrer
+Les noms de variable doivent être aussi descriptifs que possible, mais
+aussi courts que possible. Les variables normales doivent démarrer
+avec une lettre minuscule, et doivent être écrites en camelBack si il y a
+plusieurs mots. Les variables contenant des objets doivent démarrer
avec une majuscule, et d'une certaine manière être associées à la classe d'où
elles proviennent. Exemple::
@@ -308,12 +354,12 @@ elles proviennent. Exemple::
$Dispatcher = new Dispatcher();
-Visibilité des membres
+Visibilité des Membres
----------------------
Utilisez les mots-clés private et protected de PHP5 pour les méthodes et
variables. De plus les noms des méthodes et variables protégées commencent
-avec un underscore simple ("\_"). Exemple::
+avec un underscore simple (``_``). Exemple::
class A {
protected $_jeSuisUneVariableProtegee;
@@ -324,7 +370,7 @@ avec un underscore simple ("\_"). Exemple::
}
Les noms de méthodes et variables privées commencent avec un underscore double
-("\_\_"). Exemple::
+(``__``). Exemple::
class A {
private $__iAmAPrivateVariable;
@@ -334,24 +380,13 @@ Les noms de méthodes et variables privées commencent avec un underscore double
}
}
-Essayez cependant d'éviter les méthodes et variables privées, et de plutôt
-utiliser des protégées.
-Ce qui suivra peut être accessible ou modifié en sous-classes, tandis que
-celles privées évitent l'extension ou la réutilisation. La visibilité privée
+Essayez cependant d'éviter les méthodes et variables privées et privilégiez
+plutôt les variables protégées.
+Ainsi elles pourront être accessible ou modifié par les sous-classes, alors que
+celles privées empêchent l'extension ou leur réutilisation. La visibilité privée
rend aussi le test beaucoup plus difficile.
-Chaînage des méthodes
----------------------
-
-Le chaînage des méthodes doit avoir des méthodes multiples réparties dans des
-lignes distinctes, et indentées avec une tabulation::
-
- $email->from('foo@example.com')
- ->to('bar@example.com')
- ->subject('Un super message')
- ->send();
-
-Exemple d'adresses
+Exemple d'Adresses
------------------
Pour tous les exemples d'URL et d'adresse email, utilisez "example.com",
@@ -361,20 +396,18 @@ Pour tous les exemples d'URL et d'adresse email, utilisez "example.com",
* WWW: `http://www.example.com `_
* FTP: `ftp://ftp.example.com `_
-Le nom de domaine ``example.com`` est réservé à cela (voir :rfc:`2606`) et est
+Le nom de domaine "example.com" est réservé à cela (voir :rfc:`2606`) et est
recommandé pour l'utilisation dans la documentation ou comme exemples.
Fichiers
--------
Les noms de fichier qui ne contiennent pas de classes, doivent être écrits en
-minuscules et soulignés, par exemple:
-
-::
+minuscules et soulignés, par exemple::
nom_de_fichier_long.php
-Types de variables
+Types de Variables
------------------
Les types de variables pour l'utilisation dans DocBlocks:
@@ -383,14 +416,16 @@ Type
Description
mixed
Une variable avec un type indéfini (ou multiple).
-integer
+int
Variable de type Integer (Tout nombre).
float
Type Float (nombres à virgule).
-boolean
+bool
Type Logique (true ou false).
string
- Type String (toutes les valeurs en "" ou ' ').
+ Type String (toutes les valeurs en " " ou ' ').
+null
+ Type null. Habituellement utilisé avec un autre type.
array
Type Tableau.
object
@@ -399,6 +434,15 @@ resource
Type Ressource (retourné par exemple par mysql\_connect()).
Rappelez vous que quand vous spécifiez un type en mixed, vous devez
indiquer si il est inconnu, ou les types possibles.
+callable
+ Function appelable.
+
+Vous pouvez aussi combiner les types en utilisant le caractère pipe::
+
+ int|bool
+
+Pour plus de deux types, il est habituellement mieux d'utiliser seulement
+``mixed``.
Casting
-------
@@ -423,16 +467,12 @@ Type
Constantes
----------
-Les constantes doivent être définies en majuscules:
-
-::
+Les constantes doivent être définies en majuscules::
define('CONSTANTE', 1);
Si un nom de constante a plusieurs mots, ils doivent être séparés par un
-caractère underscore, par exemple:
-
-::
+caractère underscore, par exemple::
define('NOM_LONG_DE_CONSTANTE', 2);
diff --git a/fr/controllers.rst b/fr/controllers.rst
index 7b6576934f..08ae57e084 100644
--- a/fr/controllers.rst
+++ b/fr/controllers.rst
@@ -12,11 +12,11 @@ code et facilitera le test de votre code.
Habituellement, les controllers sont utilisés pour gérer la logique autour
d'un seul model. Par exemple, si vous construisez un site pour gérer une
-boulangerie en-ligne, vous aurez sans doute un RecettesController et un
-IngredientsController qui gérent les recettes et leurs ingrédients. Dans
-CakePHP, les controllers sont nommés d'après le model principal qu'ils
-gèrent. Il est aussi totalement possible d'avoir des controllers qui
-travaillent avec plus d'un model.
+boulangerie en-ligne, vous aurez sans doute un RecettesController qui gère
+vos recettes et un IngredientsController qui gére vos ingrédients. Cependant,
+il est aussi possible d'avoir des controllers qui fonctionnent avec plus qu'un
+model. Dans CakePHP, un controller est nommé d'après le model principal qu'il
+gère.
Les controllers de votre application sont des classes qui étendent la classe
CakePHP ``AppController``, qui hérite elle-même de la classe
@@ -24,11 +24,10 @@ CakePHP ``AppController``, qui hérite elle-même de la classe
dans ``/app/Controller/AppController.php`` et elle devrait contenir les
méthodes partagées par tous les controllers de votre application.
-Les controllers peuvent inclure un certain nombre de méthodes qui sont
-généralement appelées *actions*. Les actions sont les méthodes d'un controller
-qui gèrent les requêtes. Par défaut, toutes les méthodes publiques d'un
-controller sont des actions accessibles via une URL. Les actions sont
-responsables de l'interprétation des requêtes et de la création de
+Les controllers peuvent inclure un certain nombre de méthodes qui gèrent les
+requête. Celles-ci sont appelées des *actions*. Par défaut, chaque méthode
+publique dans un controller est une action accessible via une URL. Une action
+est responsable de l'interprétation des requêtes et de la création de
la réponse. Habituellement, les réponses sont sous forme de vue rendue, mais
il y a aussi d'autres façons de créer des réponses.
@@ -40,21 +39,20 @@ Le Controller App
Comme indiqué dans l'introduction, la classe ``AppController`` est la classe
mère de tous les controllers de votre application. ``AppController`` étend
elle-même la classe :php:class:`Controller` incluse dans la librairie du cœur
-de CakePHP. Ainsi, ``AppController`` est définie dans
+de CakePHP. ``AppController`` est définie dans
``/app/Controller/AppController.php`` comme ceci::
class AppController extends Controller {
}
Les attributs et méthodes de controller créés dans ``AppController`` seront
-disponibles dans tous les controllers de votre application. C'est l'endroit
-idéal pour créer du code commun à tous vos controllers. Les Components (que
+disponibles dans tous les controllers de votre application. Les Components (que
vous découvrirez plus loin) sont mieux appropriés pour du code utilisé dans
la plupart (mais pas nécessairement tous) des controllers.
Bien que les règles habituelles d'héritage de la programmation orientée objet
soient appliquées, CakePHP exécute également un travail supplémentaire si des
-attributs spécifiques des controllers sont fournis, comme la liste des
+attributs spécifiques des controllers sont fournis, comme les
components ou helpers utilisés par un controller. Dans ces situations, les
valeurs des tableaux de ``AppController`` sont fusionnées avec les tableaux de
la classe controller enfant. Les valeurs dans la classe enfant vont toujours
@@ -72,7 +70,7 @@ surcharger celles dans ``AppController``.
N'oubliez pas d'ajouter les helpers Html et Form si vous avez défini la
propriété :php:attr:`~Controller::$helpers` dans votre classe ``AppController``.
-Pensez à appeler les fonctions de rappel (callbacks) de AppController dans
+Pensez aussi à appeler les fonctions de rappel (callbacks) de AppController dans
celles du controller enfant pour de meilleurs résultats::
public function beforeFilter() {
@@ -131,9 +129,9 @@ fait des conventions que CakePHP utilise, vous n'avez pas à créer et rendre
la vue manuellement. Au lieu de ça, une fois qu'une action du controller est
terminée, CakePHP va gérer le rendu et la livraison de la Vue.
-Si pour certaines raisons, vous voulez échapper au comportement par défaut. Les
-deux techniques suivantes vont échapper le comportement de rendu par défaut de
-la vue.
+Si pour certaines raisons, vous voulez éviter le comportement par défaut, les
+deux techniques suivantes ne vont pas appliquer le comportement de rendu par
+défaut de la vue.
* Si vous retournez une chaîne de caractères, ou un objet qui peut être
converti en une chaîne de caractères à partir d'une action du controller,
@@ -141,7 +139,7 @@ la vue.
* Vous pouvez retourner un objet :php:class:`CakeResponse` avec la réponse
complètement créée.
-Quand les méthodes du controller sont utilisées avec
+Quand vous utilisez les méthodes du controller avec
:php:meth:`~Controller::requestAction()`, vous voudrez souvent retourner les
données qui ne sont pas des chaînes de caractère. Si vous avez des méthodes
du controller qui sont utilisées pour des requêtes web normales + requestAction,
@@ -218,7 +216,7 @@ consultez
Interactions avec les vues
--------------------------
-Les Controllers interagissent avec la vue de plusieurs façons.
+Les Controllers interagissent avec les vues de plusieurs façons.
Premièrement, ils sont capables de passer des données aux vues, en utilisant
:php:meth:`~Controller::set()`. Vous pouvez aussi décider quelle classe de vue
utiliser, et quel fichier de vue doit être rendu à partir du controller.
@@ -241,14 +239,7 @@ utiliser, et quel fichier de vue doit être rendu à partir du controller.
La méthode :php:meth:`~Controller::set()` peut également prendre un tableau
associatif comme premier paramètre. Cela peut souvent être une manière
- rapide d'affecter en une seule fois un jeu complet d'informations à la vue.
-
- .. versionchanged:: 1.3
- Les clefs de votre tableau ne seront plus infléchies avant d'être
- assignées à la vue (‘clef\_avec\_underscore’ ne devient plus
- ‘clefAvecUnderscore’, etc...).
-
- ::
+ rapide d'affecter en une seule fois un jeu complet d'informations à la vue::
$data = array(
'couleur' => 'rose',
@@ -262,7 +253,7 @@ utiliser, et quel fichier de vue doit être rendu à partir du controller.
$this->set($data);
- L'attribut ``$pageTitle`` n'existe plus, utilisez
+ L'attribut ``$pageTitle`` n'existe plus. Utilisez
:php:meth:`~Controller::set()` pour définir le titre::
$this->set('title_for_layout', 'Ceci est la page titre');
@@ -291,25 +282,23 @@ utiliser, et quel fichier de vue doit être rendu à partir du controller.
// ...
}
- Bien que CakePHP appellera cette fonction automatiquement à la
+ Bien que CakePHP appelle cette fonction automatiquement à la
fin de chaque action (à moins que vous n'ayez défini ``$this->autoRender``
à false), vous pouvez l'utiliser pour spécifier un fichier de vue
alternatif en précisant le nom d'une action dans le controller, via
le paramètre ``$action``.
- Si ``$action`` commence avec un '/' on suppose que c'est un fichier de
+ Si ``$view`` commence avec un '/' on suppose que c'est un fichier de
vue ou un élément dont le chemin est relatif au dossier ``/app/View``. Cela
permet un affichage direct des éléments, ce qui est très pratique lors
- d'appels ajax.
+ d'appels AJAX.
::
// Rend un élément dans /View/Elements/ajaxreturn.ctp
$this->render('/Elements/ajaxreturn');
- Vous pouvez aussi spécifier une vue alternative ou un fichier element en
- utilisant le troisième paramètre, ``$file``. Le paramètre
- :php:attr:`~View::$layout` vous permet de spécifier le layout de la vue
- qui est rendue.
+ Le paramètre :php:attr:`~View::$layout` vous permet de spécifier le layout
+ de la vue qui est rendue.
Rendre une vue spécifique
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -415,7 +404,7 @@ Contrôle de Flux
L'URL généré serait:
``http://www.example.com/commandes/confirmation?produit=pizza&quantite=5#top``
-.. php:method:: flash(string $message, string $url, integer $pause, string $layout)
+.. php:method:: flash(string $message, string|array $url, integer $pause, string $layout)
Tout comme :php:meth:`~Controller::redirect()`, la méthode
:php:meth:`~Controller::flash()` est utilisée pour rediriger un utilisateur
diff --git a/fr/controllers/components.rst b/fr/controllers/components.rst
index 0bab76f5a3..086e2bb33f 100644
--- a/fr/controllers/components.rst
+++ b/fr/controllers/components.rst
@@ -2,21 +2,18 @@ Components (Composants)
#######################
Les Components (Composants) sont des regroupements de logique applicative
-qui sont partagés entre les controllers. Si vous vous surprenez à vouloir
-copier et coller des choses entre vos controllers, alors vous devriez envisager
-de regrouper plusieurs fonctionnalités dans un Component.
-
-CakePHP est également livré avec un fantastique ensemble de components,
-que vous pouvez utiliser pour vous aider :
-
-.. include:: /core-libraries/toc-components.rst
- :start-line: 7
+qui sont partagés entre les controllers. CakePHP est également livré avec un
+fantastique ensemble de components, que vous pouvez utiliser pour vous aider.
+Si vous vous surprenez à vouloir copier et coller des choses entre vos
+controllers, alors vous devriez envisager de regrouper plusieurs
+fonctionnalités dans un Component. Créer des components permettent de garder
+un code de controller propre et vous permet de réutiliser du code entre des
+projets.
Chacun de ces components d'origine est détaillé dans son chapitre
-spécifique. Pour l'heure, nous allons vous montrer comment créer
-vos propres components. La création de components vous permet de garder
-le code de vos controllers propres et vous permet de réutiliser
-du code entre vos projets.
+spécifique. Regardez :doc:`/core-libraries/toc-components`. Cette section
+décrit la façon de configurer et d'utiliser les components et la façon de
+créer vos propres components.
.. _configuring-components:
@@ -150,6 +147,8 @@ qui vous permettent d'augmenter le cycle de la requête. Allez voir l'api
:ref:`component-api` pour plus d'informations sur les callbacks possibles
des components.
+.. _creating-a-component:
+
Créer un Component
==================
diff --git a/fr/controllers/request-response.rst b/fr/controllers/request-response.rst
index 7822e9aea8..a742afb916 100644
--- a/fr/controllers/request-response.rst
+++ b/fr/controllers/request-response.rst
@@ -69,7 +69,8 @@ Tous ceux-ci vous fourniront un accès aux arguments passés et aux paramètres
nommés. Il y a de nombreux paramètres importants et utiles que CakePHP utilise
en interne, il sont aussi trouvables dans les paramètres de la requête:
-* ``plugin`` Le plugin gérant la requête, va être nul pour les non-plugins.
+* ``plugin`` Le plugin gérant la requête, va être nul quand il n'y a pas de
+ plugins.
* ``controller`` Le controller gère la requête courante.
* ``action`` L'action gère la requête courante.
* ``prefix`` Le prefixe pour l'action courante. Voir :ref:`prefix-routing` pour
@@ -95,7 +96,7 @@ Les paramètres Querystring peuvent être lus en utilisant
Vous pouvez soit directement accéder à la propriété
:php:attr:`~CakeRequest::$query`, soit vous pouvez utiliser
-:php:meth:`CakeRequest::query()` pour lire l'URL requêtée d'une manière sans
+:php:meth:`CakeRequest::query()` pour lire l'URL requêtée sans
erreur. Toute clé qui n'existe pas va retourner ``null``::
$foo = $this->request->query('value_that_does_not_exist');
@@ -308,6 +309,18 @@ API de CakeRequest
.. versionadded:: 2.3
+ .. deprecated:: 2.5
+ Utilisez :php:meth:`CakeRequest::allowMethod()` à la place.
+
+.. php:method:: allowMethod($methods)
+
+ Définit les méthodes HTTP autorisées, si cela ne correspond pas, une
+ exception MethodNotAllowedException sera lancée.
+ La réponse 405 va inclure l'en-tête nécessaire ``Allow`` avec les méthodes
+ passées.
+
+ .. versionadded:: 2.5
+
.. php:method:: referer($local = false)
Retourne l'adresse de référence de la requête.
@@ -514,7 +527,7 @@ réponse::
Comme montré dans l'exemple ci-dessus, vous devez passer le
chemin du fichier à la méthode. CakePHP va envoyer le bon en-tête de type de
contenu si c'est un type de fichier connu listé dans
-:php:attr:`CakeReponse::$_mimeTypes`. Vous pouvez ajouter des nouveaux types
+:php:attr:`CakeResponse::$_mimeTypes`. Vous pouvez ajouter des nouveaux types
avant d'appeler :php:meth:`CakeResponse::file()` en utilisant la méthode
:php:meth:`CakeResponse::type()`.
@@ -770,8 +783,8 @@ Probablement l'une des plus grandes victoires de :php:class:`CakeResponse` vient
de comment il facilite les tests des controllers et des components. Au lieu
d'avoir des méthodes répandues à travers plusieurs objets, vous avez un seul
objet pour mocker pendant que les controllers et les components déleguent à
-:php:class:`CakeResponse`. Cela vous aide à rester plus près d'un test 'unit' et
-facilite les tests des controllers::
+:php:class:`CakeResponse`. Cela vous aide à rester plus près d'un test unitaire
+et facilite les tests des controllers::
public function testSomething() {
$this->controller->response = $this->getMock('CakeResponse');
diff --git a/fr/controllers/scaffolding.rst b/fr/controllers/scaffolding.rst
index 949e19a55d..2ab2254869 100644
--- a/fr/controllers/scaffolding.rst
+++ b/fr/controllers/scaffolding.rst
@@ -1,6 +1,9 @@
Scaffolding
###########
+.. deprecated:: 2.5
+ Le scaffolding dynamique sera retiré et remplacé dans 3.0
+
Une application scaffolding (échafaudage en Français) est une technique
permettant au développeur de définir et créer une application qui peut
construire, afficher, modifier et détruire facilement des objets.
diff --git a/fr/core-libraries/caching.rst b/fr/core-libraries/caching.rst
index 0c809b3e98..8ff0bc0e2a 100644
--- a/fr/core-libraries/caching.rst
+++ b/fr/core-libraries/caching.rst
@@ -1,16 +1,16 @@
La mise en cache
################
-La mise en cache est fréquemment utilisée pour réduire le temps pris pour
-créer ou lire depuis une autre ressource. La mise en cache est souvent
-utilisée pour rendre la lecture de ressources consommatrices en temps en
-ressources moins consommatrices. Vous pouvez aisément stocker le résultats
-de requêtes consommatrices en ressources, ou des accès à distance a des
-services web qui ne changent pas fréquemment dans un cache. Une fois dans
-un cache, re-lire les ressources stockées depuis le cache est moins
-consommateur en ressource qu'un accès a une ressource distante.
-
-Mettre en cache dans CakePHP est principalement facilité par la classe
+La mise en cache est fréquemment utilisée pour réduire le temps pris pour créer
+ou lire depuis une autre ressource. La mise en cache est souvent utilisée pour
+rendre la lecture de ressources consommatrices en temps en ressources moins
+consommatrice. Vous pouvez aisément stocker en cache les résultats de requêtes
+consommatrices en ressources ou les accès à distance à des services web qui ne
+changent pas fréquemment. Une fois mis en cache, re-lire les ressources
+stockées depuis le cache est moins consommateur en ressource qu'un accès a une
+ressource distante.
+
+La mise en cache dans CakePHP se fait principalement par la classe
:php:class:`Cache`. Cette classe fournit un ensemble de méthodes
statiques qui fournissent une API uniforme pour le traitement des
différentes implémentations de mise en cache. CakePHP arrive avec plusieurs
@@ -18,10 +18,10 @@ moteurs de cache intégrés, et fournit un système facile pour implémenter
votre propre système de mise en cache. Les moteurs de cache intégrés sont:
* ``FileCache`` File cache est un cache simple qui utilise des fichiers
- locaux. C'est le moteur de cache le plus lent, et ne fournit que peut
- de fonctionnalité pour les opérations atomiques. Cependant, le stockage
- sur disque est souvent peu consommateur en ressource, au stockage de
- grands objets, ou des éléments qui sont rarement écrits fonctionnent
+ locaux. C'est le moteur de cache le plus lent, et il ne fournit que peu
+ de fonctionnalités pour les opérations atomiques. Cependant, le stockage
+ sur disque est souvent peu consommateur en ressource, le stockage de
+ grands objets ou des éléments qui sont rarement écrits fonctionne
bien dans les fichiers. C'est le moteur de Cache par défaut pour 2.3+.
* ``ApcCache`` Le cache APC utilise l'extension PHP
`APC `_. Cette extension utilise la mémoire partagée du
@@ -29,25 +29,31 @@ votre propre système de mise en cache. Les moteurs de cache intégrés sont:
fournir les fonctionnalités atomiques en lecture/écriture.
Par défaut CakePHP dans 2.0-2.2 utilisera ce moteur de cache si il est
disponible.
-* ``Wincache`` utilise l'extension `Wincache `_.
- Wincache est similaire aux fonctionnalités APC au niveau des fonctionnalités
- et des performances, mais optimisé pour Windows et IIS.
-* ``XcacheEngine`` Similaire à APC, `Xcache `_.
+* ``Wincache`` Utilise l'extension `Wincache `_.
+ Wincache a des fonctionnalités et des performances semblables à APC, mais
+ optimisé pour Windows et IIS.
+* ``XcacheEngine`` Similaire à APC, `Xcache `_.
est une extension PHP qui fournit des fonctionnalités similaires à APC.
* ``MemcacheEngine`` Utilise l'extension `Memcache `_.
Memcache fournit un cache très rapide qui peut être distribué au travers
- de nombreux serveurs, et fournit les opérations atomiques.
+ de nombreux serveurs et il permet les opérations atomiques.
+* ``MemcachedEngine`` Utilise l'extension
+ `Memcached `_. Il est aussi une interface avec
+ memcache mais il fournit une meilleur performance.
* ``RedisEngine`` Utilise l'extension
`phpredis `_. Redis fournit un système
- de cache cohérent et rapide similaire à memcached, et fournit aussi des
- opérations atomic.
+ de cache cohérent et rapide similaire à memcached et il permet aussi les
+ opérations atomiques.
. versionchanged:: 2.3
FileEngine est toujours le moteur de cache par défaut. Dans le passé, un
- certain nombre de personnes avait des difficultés à configurer et déployer
+ certain nombre de personnes avait des difficultés à configurer et à déployer
APC correctement dans les deux cli + web. Utiliser les fichiers devrait
faciliter la configuration de CakePHP pour les nouveaux développeurs.
+.. versionchanged:: 2.5
+ Le moteur Memcached a été ajouté. Et le moteur Memcache a été déprécié.
+
Quelque soit le moteur de cache que vous choisirez d'utiliser, votre
application interagit avec :php:class:`Cache` de manière cohérente. Cela
signifie que vous pouvez aisément permuter les moteurs de cache en fonction de
@@ -61,23 +67,23 @@ Configuration de la classe Cache
La configuration de la classe Cache peut être effectuée n'importe où, mais
généralement vous voudrez configurer le cache dans
``app/Config/bootstrap.php``. Vous pouvez configurer autant de configurations
-de cache dont vous avez besoin, et utiliser tous les mélanges de moteurs de
-cache. CakePHP utilise deux configurations de cache en interne, qui sont
-configurés dans ``app/Config/core.php``. Si vous utilisez APC ou Memcache vous
-devrez vous assurer de définir des clés uniques pour les caches du noyau.
-Ceci vous évitera que de multiples applications viennent réécrire les données
-cache de l'autre.
-
-L'utilisation de multiples configurations de cache peut aider à réduire
-le nombre de fois où vous aurez à utiliser :php:func:`Cache::set()`.
-Aussi bien que centraliser tout vos paramètres de cache. L'utilisation
-de configurations multiples vous permet également de changer le stockage
+de cache dont vous avez besoin, et vous pouvez utiliser tous les mélanges de
+moteurs de cache. CakePHP utilise deux configurations de cache en interne, qui
+sont configurés dans ``app/Config/core.php``. Si vous utilisez APC ou Memcache
+vous devrez vous assurer de définir des clés uniques pour les caches du noyau.
+Ceci vous évitera qu'une application vienne réécrire les données cache d'une
+autre application.
+
+L'utilisation de plusieurs configurations de cache peut aider à réduire
+le nombre de fois où vous aurez à utiliser :php:func:`Cache::set()` et
+permettra aussi de centraliser tous vos paramètres de cache. L'utilisation
+de plusieurs configurations vous permet également de changer le stockage
comme vous l'entendez.
.. note::
- Vous devez spécifier quel moteur utiliser. Il ne met **pas** par défaut
- à `File`.
+ Vous devez spécifier le moteur à utiliser. Il ne met **pas** File par
+ défaut.
Exemple::
@@ -98,12 +104,12 @@ Exemple::
En insérant le code ci-dessus dans votre ``app/Config/bootstrap.php`` vous
aurez deux configurations de cache supplémentaires. Le nom de ces
-configurations 'short' ou 'long' est utilisé comme le paramètre ``$config``
+configurations 'short' ou 'long' est utilisé comme paramètre ``$config``
pour :php:func:`Cache::write()` et :php:func:`Cache::read()`.
.. note::
- Quand vous utilisez le moteur FileEngine vous pourriez avoir besoin de
+ Quand vous utilisez le moteur FileEngine vous pouvez avoir besoin de
l'option ``mask`` pour vous assurer que les fichiers cachés sont
créés avec les bonnes permissions.
@@ -117,14 +123,14 @@ Création d'un moteur de stockage pour le Cache
==============================================
Vous pouvez fournir vos propre adaptateurs ``Cache`` dans ``app/Lib``
-aussi bien que dans un plugin en utilisant ``$plugin/Lib``.
+ou dans un plugin en utilisant ``$plugin/Lib``.
Les moteurs de cache App/plugin peuvent aussi remplacer les moteurs
-du noyau. Les adaptateurs de cache doivent être dans un répertoire cache.
+du coeur. Les adaptateurs de cache doivent être dans un répertoire cache.
Si vous avez un moteur de cache nommé ``MonMoteurDeCachePerso`` il devra
être placé soit dans ``app/Lib/Cache/Engine/MonMoteurDeCachePerso.php``
-comme une app/libs. Ou dans
-``$plugin/Lib/Cache/Engine/MonMoteurDeCachePerso.php`` comme parti d'un
-plugin. Les configurations de cache provenant de plugin doivent utiliser la
+comme une app/librairie ou dans
+``$plugin/Lib/Cache/Engine/MonMoteurDeCachePerso.php`` faisant parti d'un
+plugin. Les configurations de cache venant d'un plugin doivent utiliser la
notation par points de plugin.::
Cache::config('custom', array(
@@ -134,19 +140,19 @@ notation par points de plugin.::
.. note::
- Le cache App et plugin doit être configuré dans
+ Les moteurs de cache App et Plugin doivent être configurés dans
``app/Config/bootstrap.php``. Si vous essayez de les configurer
dans core.php ils ne fonctionneront pas correctement.
-Les moteurs de cache personnalisés doivent entendre
-:php:class:`CacheEngine` qui définit un nombre de méthodes d'abstraction
-ainsi que quelques méthodes d'initialisation.
+Les moteurs de cache personnalisés doivent étendre
+:php:class:`CacheEngine` qui définit un certain nombre de méthodes
+d'abstraction ainsi que quelques méthodes d'initialisation.
L'API requise pour CacheEngine est
.. php:class:: CacheEngine
- La classe de base pour tous les moteurs de cache utilisé avec le Cache.
+ La classe de base pour tous les moteurs de cache utilisée avec le Cache.
.. php:method:: write($key, $value, $config = 'default')
@@ -157,7 +163,7 @@ L'API requise pour CacheEngine est
.. php:method:: read($key)
- :retourne: La valeur cachée ou false en cas d'échec.
+ :retourne: La valeur mise en cache ou false en cas d'échec.
Lit une clé depuis le cache. Retourne false pour indiquer
que l'entrée a expiré ou n'existe pas.
@@ -173,12 +179,12 @@ L'API requise pour CacheEngine est
:retourne: Un Booléen true en cas de succès.
- Efface toutes les clés depuis le cache. Si $check est true, vous devez
- valider que chacune des valeurs est actuellement expirée.
+ Efface toutes les clés depuis le cache. Si $check est à true, vous devez
+ valider que chacune des valeurs a réellement expirée.
.. php:method:: clearGroup($group)
- :return: Boolean true on success.
+ :return: Boolean true en cas de succès.
Supprime toutes les clés à partir du cache appartenant au même groupe.
@@ -196,19 +202,19 @@ L'API requise pour CacheEngine est
.. php:method:: gc()
- Non requis, mais utilisé pour faire du nettoyage quand les ressources
- expires. Le moteur FileEngine utilise cela pour effacer les fichiers
+ Non requise, mais utilisée pour faire du nettoyage quand les ressources
+ expirent. Le moteur FileEngine utilise cela pour effacer les fichiers
qui contiennent des contenus expirés.
Utilisation du Cache pour stocker le résultat des requêtes les plus courantes
=============================================================================
Vous pouvez considérablement améliorer les performances de vos applications
-en plaçant les résultats qui ne changent que peu fréquemment, ou qui peuvent
+en plaçant les résultats qui ne changent que peu fréquemment ou qui peuvent
être sujets à de nombreuses lectures dans le cache. Un exemple parfait de
-ceci sont les résultats d'un find :php:meth:`Model::find()`.
-Une méthode qui utilise Le Cache pour stocker les résultats pourrait ressembler
-à cela ::
+ceci pourrait être les résultats d'un find :php:meth:`Model::find()`.
+Une méthode qui utilise la mise en Cache pour stocker les résultats pourrait
+ressembler à cela ::
class Post extends AppModel {
@@ -226,16 +232,33 @@ Vous pouvez améliorer le code ci-dessus en déplaçant la lecture du cache
dans un comportement, qui lit depuis le cache, ou qui exécute les méthodes
de model. C'est un exercice que vous pouvez faire.
+Depuis 2.5, vous pouvez accomplir ce qui est au-dessus de façon bien plus simple
+en utilisant :php:meth:`Cache::remember()`. Utiliser la nouvelle
+méthode ci-dessous ressemblerait à ceci::
+
+ class Post extends AppModel {
+
+ public function newest() {
+ $model = $this;
+ return Cache::remember('newest_posts', function() use ($model){
+ return $model->find('all', array(
+ 'order' => 'Post.updated DESC',
+ 'limit' => 10
+ ));
+ }, 'longterm');
+ }
+ }
+
Utilisation du Cache pour stocker les compteurs
===============================================
L'utilisation de compteurs dans le cache peut être une chose intéressante. Par
exemple un simple compte à rebours pour retenir les 'slots' restants d'un
-concours pourraient être stockés en Cache. La classe Cache propose des moyens
+concours pourrait être stocké en Cache. La classe Cache propose des moyens
atomiques pour incrémenter/décrémenter des valeurs de compteur facilement.
-Les opérations atomiques sont importantes pour ces valeurs parce que ça réduit
-le risque de contention, et la capacité de deux utilisateurs à simultanément
-en abaisser la valeur et de résulter à une valeur incorrecte.
+Les opérations atomiques sont importantes pour ces valeurs parce que cela réduit
+le risque de contention et la capacité de deux utilisateurs à simultanément
+en abaisser la valeur et de se retrouver avec une valeur incorrecte.
Après avoir défini une valeur entière vous pouvez la manipuler en utilisant
:php:meth:`Cache::increment()` et :php:meth:`Cache::decrement()`::
@@ -251,7 +274,7 @@ Après avoir défini une valeur entière vous pouvez la manipuler en utilisant
.. note::
L'incrémentation et la décrémentation ne fonctionne pas avec le moteur
- FileEngine. Vous devez utiliser APC ou Memcache en remplacement.
+ FileEngine. Vous devez utiliser APC ou Memcached en remplacement.
Utilisation des groupes
=======================
@@ -262,7 +285,7 @@ Parfois vous voudrez marquer plusieurs entrées de cache comme appartenant à
un même groupe ou un namespace. C'est une exigence courante pour invalider
des grosses quantités de clés alors que quelques changements d'informations
sont partagés pour toutes les entrées dans un même groupe. Cela est possible
-en déclarant les groupes dans la configuration deu cache::
+en déclarant les groupes dans la configuration de cache::
Cache::config('site_home', array(
'engine' => 'Redis',
@@ -271,8 +294,8 @@ en déclarant les groupes dans la configuration deu cache::
));
Disons que vous voulez stocker le HTML généré pour votre page d'accueil
-dans le cache, mais voulez aussi invalider automatiquement ce cache à chaque
-fois qu'un commentaire ou un post est ajouté à votre base de données.
+dans le cache, mais vous voulez aussi invalider automatiquement ce cache à
+chaque fois qu'un commentaire ou un post est ajouté à votre base de données.
En ajoutant les groupes ``comment`` et ``post``, nous avons effectivement
taggés les clés stockées dans la configuration du cache avec les noms des
deux groupes.
@@ -309,7 +332,7 @@ même groupe::
}
}
-Les groupes son partagés à travers toutes les configs de cache en utilisant
+Les groupes sont partagés à travers toutes les configs de cache en utilisant
le même moteur et le même préfixe. Si vous utilisez les groupes et voulez tirer
profit de la suppression de groupe, choisissez un préfixe commun pour toutes
vos configs.
@@ -327,9 +350,9 @@ l'API de Cache
.. php:staticmethod:: config($name = null, $settings = array())
``Cache::config()`` est utilisée pour créer des configurations
- de cache supplémentaire. Ces configurations supplémentaires
+ de cache supplémentaires. Ces configurations supplémentaires
peuvent avoir différentes durées, moteurs, chemins, ou préfixes
- que la configuration par défaut du cache.
+ par rapport à la configuration par défaut du cache.
.. php:staticmethod:: read($key, $config = 'default')
@@ -338,7 +361,7 @@ l'API de Cache
configuration par défaut sera utilisée. ``Cache::read()`` retournera
la valeur en cache si c'est un cache valide ou ``false`` si le
cache a expiré ou n'existe pas. Le contenu du cache pourrait
- évaluer false, donc assurez-vous que vous utilisez les opérateurs
+ être vu comme false, donc assurez-vous que vous utilisez les opérateurs
de comparaison stricte ``===`` ou ``!==``.
Par exemple::
@@ -358,13 +381,13 @@ l'API de Cache
.. php:staticmethod:: write($key, $value, $config = 'default')
- Cache::write() Ecrira $value dans le cache. Vous pouvez lire ou
+ Cache::write() va écrire $value dans le cache. Vous pouvez lire ou
effacer cette valeur plus tard en vous y référant avec ``$key``..
Vous pouvez spécifier une configuration optionnelle pour stocker
- le cache. Si il n'y a pas de ``$config`` de spécifié c'est la
+ le cache. Si il n'y a pas de ``$config`` spécifiée c'est la
configuration par défaut qui sera appliquée. Cache::write()
- peut stocker n'importe quel type d'objet est est idéal pour
- stocker les résultats des finds de vos modèles.::
+ peut stocker n'importe quel type d'objet et elle est idéale pour
+ stocker les résultats des finds de vos models.::
if (($posts = Cache::read('posts')) === false) {
@@ -372,14 +395,14 @@ l'API de Cache
Cache::write('posts', $posts);
}
- Utiliser ``Cache::write()`` et ``Cache::read()`` pour aisément réduire
+ Utiliser ``Cache::write()`` et ``Cache::read()`` pour facilement réduire
le nombre de déplacement fait dans la base de données pour rechercher
les posts.
.. php:staticmethod:: delete($key, $config = 'default')
- ``Cache::delete()`` vous permet d'enlever complètement un objet en cache
- du lieu de stockage.
+ ``Cache::delete()`` vous permet d'enlever complètement un objet mis en cache
+ de son lieu de stockage de Cache.
.. php:staticmethod:: set($settings = array(), $value = null, $config = 'default')
@@ -388,7 +411,7 @@ l'API de Cache
Si vous utilisez ``Cache::set()`` pour changer les paramètres pour une
écriture, vous devez aussi utiliser ``Cache::set()`` avant de lire les
données en retour. Si vous ne faites pas cela, les paramètres par défaut
- seront utilisés quand la clé de cache est lu.::
+ seront utilisés quand la clé de cache est lue.::
Cache::set(array('duration' => '+30 days'));
Cache::write('results', $data);
@@ -398,7 +421,7 @@ l'API de Cache
Cache::set(array('duration' => '+30 days'));
$results = Cache::read('results');
- Si vous trouvez que vous répétez l'appel à ``Cache::set()`` peut être
+ Si vous trouvez que vous répétez l'appel à ``Cache::set()`` peut-être
devriez-vous créer une nouvelle :php:func:`Cache::config()`. Qui
enlèvera les besoins d'appeler ``Cache::set()``.
@@ -417,7 +440,8 @@ l'API de Cache
Détruit toutes les valeurs en cache pour une configuration de cache. Dans
les moteurs comme Apc, Memcache et Wincache le préfixe de configuration de
cache est utilisé pour enlever les entrées de cache.
- Soyez sûre que différentes configuration de cache ont différent préfixe.
+ Assurez-vous que les différentes configuration de cache ont un préfixe
+ différent.
.. php:method:: clearGroup($group, $config = 'default')
@@ -427,16 +451,39 @@ l'API de Cache
.. php:staticmethod:: gc($config)
- collectes d'entrée de Garbage dans la configuration du cache. Utilisé
- principalement par FileEngine. Il devrait être mis en œuvre par n'importe
- quel moteur de cache qui requiert des évictions manuelles de données en
- cache.
+ La Garbage (Poubelle) collecte les entrées dans la configuration du cache.
+ Utilisée principalement par FileEngine. Elle doit être mise en œuvre par
+ n'importe quel moteur de cache qui requiert des évictions manuelles de
+ données de cache.
.. php:staticmethod:: groupConfigs($group = null)
- :return: Tableau de groups et leurs noms de configuration liés.
+ :return: Tableau de groupes et leurs noms de configuration liés.
+
+ Récupère les noms de groupe pour configurer la correspondance.
+
+.. php:staticmethod:: remember($key, $callable, $config = 'default')
+
+ Fournit une manière facile pour faire la lecture à travers la mise en cache.
+ Si la clé cache existe, elle sera retournée. Si la clé n'existe pas, la
+ callable sera invoquée et les résultats stockés dans le cache au niveau de
+ la clé fournie.
+
+ Par exemple, vous voulez souvent mettre en cache les résultats de requête.
+ Vous pouvez utiliser ``remember()`` pour faciliter ceci. En supposant
+ que vous utilisez PHP5.3 ou supérieur::
+
+ class Articles extends AppModel {
+ function all() {
+ $model = $this;
+ return Cache::remember('all_articles', function() use ($model){
+ return $model->find('all');
+ });
+ }
+ }
- Récupère les noms de group pour configurer la coorespondance.
+ .. versionadded:: 2.5
+ remember() a été ajoutée dans 2.5.
.. meta::
:title lang=fr: Mise en cache
diff --git a/fr/core-libraries/components/access-control-lists.rst b/fr/core-libraries/components/access-control-lists.rst
index 6205346881..d7137836e1 100644
--- a/fr/core-libraries/components/access-control-lists.rst
+++ b/fr/core-libraries/components/access-control-lists.rst
@@ -3,16 +3,6 @@ Liste de contrôle d'accès (ACL)
.. php:class:: AclComponent(ComponentCollection $collection, array $settings = array())
-La fonctionnalité de listes de contrôle d'accès (Access Control List, ACL)
-de CakePHP est l'une des plus souvent discutée, probablement parce
-qu'elle est la plus recherchée, mais aussi parce qu'elle peut-être la plus
-déroutante. Si vous recherchez une bonne façon de débuter avec les ACLs
-en général, lisez ce qui suit.
-
-Soyez courageux et persévérant avec ce sujet, même si au départ cela paraît
-difficile. Une fois que vous aurez pris le coup, ce sera un outil extrêmement
-puissant, à garder sous la main quand vous développez votre application.
-
Comprendre le fonctionnement des ACL
====================================
@@ -23,21 +13,21 @@ très précise et pourtant facilement maintenable et manipulable.
Les listes de contrôles d'accès, ou ACL (Access Control Lists), manipulent deux
choses principales : les choses qui veulent accéder à des trucs et celles qui
sont recherchées. Dans le jargon ACL, les choses qui veulent accéder à des
-trucs (le plus souvent les utilisateurs) sont appelées access request objects
-(objets requête d'accès) ou AROs. Les choses du système qui sont recherchées
-(le plus souvent les actions ou les données) sont appelées access control
-objects (objets contrôle d'accès) ou ACOs. Les entités sont appelées "objets",
-parce que parfois, l'objet demandé n'est pas une personne - des fois, vous
-pourriez vouloir limiter l'accès à certains controllers de CakePHP qui doivent
-initier leur logique dans d'autres parties de votre application. Les ACOs
-pourraient être n'importe quoi que vous voudriez contrôler, d'une action de
-controller à un service Web, en passant par une case de l'agenda en ligne de
-votre Mamy.
+trucs (le plus souvent les utilisateurs) sont représentées par des access
+request objects (objets requête d'accès) ou AROs. Les choses du système qui
+sont recherchées (le plus souvent les actions ou les données) sont appelées
+access control objects (objets contrôle d'accès) ou ACOs. Les entités sont
+appelées "objets", parce que parfois, l'objet demandé n'est pas une personne -
+des fois, vous pourriez vouloir limiter l'accès à certains controllers de
+CakePHP qui doivent initier leur logique dans d'autres parties de votre
+application. Les ACOs pourraient être n'importe quoi que vous voudriez
+contrôler, d'une action de controller à un service Web, en passant par une case
+de l'agenda en ligne de votre Mamy.
Rappel :
-- ACO - Objet Contrôle d'Accès - Quelque chose qui est recherché
-- ARO - Objet Requête d'Accès - Quelque chose qui veut quelque chose
+- ACO - Objet Contrôle d'Accès - Représente quelque chose qui est recherché
+- ARO - Objet Requête d'Accès - Représente quelque chose qui veut quelque chose
Généralement, les ACL sont utilisées pour décider quand un ARO peut obtenir
l'accès à un ACO.
@@ -48,7 +38,7 @@ utilisé par un célèbre groupe d'aventuriers tirés du roman fantastique le
*Seigneur des Anneaux*. Le chef du groupe, Gandalf, veut gérer les biens du
groupe, tout en maintenant un bon niveau de confidentialité et de sécurité
entre les autres membres de l'équipe. La première chose dont il a besoin est de
-créer une liste d'AROs qui comprend :
+créer une liste d'AROs (requêteurs) qui comprend :
- Gandalf
- Aragorn
@@ -486,7 +476,7 @@ association. Réciproquement, si vous voulez gérer les opérations d'édition
sur un article spécifique d'un blog ou d'une liste de recette, vous devez
choisir de lier un ACO à cet enregistrement spécifique du model.
-L'``alias`` d'un objet ACL est un simple label lisible pour un humain que vous
+Un ``alias`` est un simple label lisible pour un humain que vous
pouvez utiliser pour identifier un objet ACL qui n'est pas en relation directe
avec un enregistrement d'un model. Les alias sont couramment utilisés pour
nommer les groupes d'utilisateurs ou les collections d'ACOs.
@@ -721,9 +711,9 @@ et tout à la fin les controllers qui les manipulent. A côté des controllers
eux-mêmes, nous allons vouloir contrôler l'accès à des actions spécifiques
dans ces controllers.
-En partant de cette idée, nous allons configurer un arbre d'ACO qui va imiter
-une configuration d'application CakePHP. Depuis nos cinq ACOs, nous allons créer
-un arbre d'ACO qui devra ressembler à ça :
+Nous allons configurer un arbre d'ACO qui va imiter une configuration
+d'application CakePHP. Depuis nos cinq ACOs, nous allons créer un arbre d'ACO
+qui devra ressembler à ça :
- Armes
- Anneaux
diff --git a/fr/core-libraries/components/authentication.rst b/fr/core-libraries/components/authentication.rst
index f684c43d93..2deb871653 100755
--- a/fr/core-libraries/components/authentication.rst
+++ b/fr/core-libraries/components/authentication.rst
@@ -411,7 +411,7 @@ la classe de hasher de mot de passe appropriée::
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data['User']['password'])) {
- $passwordHasher = new SimplePasswordHasher();
+ $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data['User']['password'] = $passwordHasher->hash(
$this->data['User']['password']
);
diff --git a/fr/core-libraries/components/cookie.rst b/fr/core-libraries/components/cookie.rst
index 445af17ed3..ad05ac8753 100644
--- a/fr/core-libraries/components/cookie.rst
+++ b/fr/core-libraries/components/cookie.rst
@@ -25,8 +25,9 @@ permet de définir la façon dont le Component cookie fonctionne.
| string $key | null | Cette chaîne de caractère est utilisée pour chiffrer |
| | | la valeur écrite dans le cookie. Cette chaîne devrait|
| | | être aléatoire et difficile à deviner. |
-| | | Quand on utilise le chiffrement rijndael, cette |
-| | | valeur doit être plus grande que 32 bytes. |
+| | | Quand on utilise le chiffrement rijndael ou le |
+| | | chiffrement aes, cette valeur doit être plus grande |
+| | | que 32 bytes. |
+-----------------+--------------+------------------------------------------------------+
| string $domain | '' | Le nom de domaine autoriser à accéder au cookie ex: |
| | | Utiliser '.votredomaine.com' pour autoriser les |
@@ -68,6 +69,7 @@ d'une connexion sécurisée, qui est disponible au chemin
::
public $components = array('Cookie');
+
public function beforeFilter() {
parent::beforeFilter();
$this->Cookie->name = 'baker_id';
@@ -77,6 +79,7 @@ d'une connexion sécurisée, qui est disponible au chemin
$this->Cookie->secure = true; // ex. seulement envoyé si on utilise un HTTPS sécurisé
$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
$this->Cookie->httpOnly = true;
+ $this->Cookie->type('aes');
}
Ensuite, regardons comment utiliser les différentes méthodes du Component
@@ -109,11 +112,9 @@ Le Component Cookie offre plusieurs méthodes pour travailler avec les Cookies.
Toutes les valeurs dans le cookie sont chiffrées par défaut. Si vous voulez
stocker vos valeurs en texte clair, definissez le troisème paramètre de la
- méthode write() à false. Le chiffrement utilisé sur les valeurs de cookie
- est un système de chiffrement très simple. Il utilise ``Security.salt`` et
- une variable de classe de configuration prédéfinie ``Security.cipherSeed``
- pour chiffrer les valeurs. Vous devriez changer ``Security.cipherSeed``
- dans app/Config/core.php pour assurer un meilleur chiffrement.::
+ méthode write() à false. Vous devriez vous rappeler de définir le mode de
+ chiffrement à 'aes' pour s'assurer que les valeurs sont chiffrées de façon
+ sécurisée::
$this->Cookie->write('name', 'Larry', false);
@@ -170,12 +171,15 @@ Le Component Cookie offre plusieurs méthodes pour travailler avec les Cookies.
.. php:method:: type($type)
Vous permet de changer le schéma de chiffrement. Par défaut, le schéma
- 'cipher' est utilisé. Cependant, vous devriez utiliser le schéma 'rijndael'
- pour une sécurité améliorée.
+ 'cipher' est utilisé pour une compatibilité rétroactive. Cependant, vous
+ devriez toujours utiliser les schémas 'rijndael' ou 'aes'.
.. versionchanged:: 2.2
Le type 'rijndael' a été ajouté.
+ .. versionadded:: 2.5
+ Le type 'aes' a été ajouté.
+
.. meta::
:title lang=fr: Cookie
diff --git a/fr/core-libraries/components/pagination.rst b/fr/core-libraries/components/pagination.rst
index 249f0928ed..687bc81b36 100644
--- a/fr/core-libraries/components/pagination.rst
+++ b/fr/core-libraries/components/pagination.rst
@@ -200,12 +200,12 @@ utilisez::
public function paginateCount($conditions = null, $recursive = 0,
$extra = array()) {
$sql = "SELECT
-+ DISTINCT ON(
-+ week, home_team_id, away_team_id
-+ )
-+ week, home_team_id, away_team_id
-+ FROM
-+ games";
+ DISTINCT ON(
+ week, home_team_id, away_team_id
+ )
+ week, home_team_id, away_team_id
+ FROM
+ games";
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
diff --git a/fr/core-libraries/components/security-component.rst b/fr/core-libraries/components/security-component.rst
index 00a0a79b9f..894c0dee09 100644
--- a/fr/core-libraries/components/security-component.rst
+++ b/fr/core-libraries/components/security-component.rst
@@ -358,13 +358,15 @@ pouvez définir ``$this->Security->csrfCheck = false;`` dans votre
``beforeFilter`` ou utiliser le tableau components. Par défaut la protection
CSRF est activée, et paramétrée pour l'utilisation de jetons à usage unique.
-Désactiver le Component Security pour des Actions Spécifiques
-=============================================================
+Désactiver CSRF et la Validation des Données Post pour des Actions Spécifiques
+==============================================================================
Il peut arriver que vous souhaitiez désactiver toutes les vérifications de
sécurité pour une action (ex. ajax request).
Vous pouvez "délocker" ces actions en les listant dans
-``$this->Security->unlockedActions`` dans votre ``beforeFilter``.
+``$this->Security->unlockedActions`` dans votre ``beforeFilter``. La propriété
+``unlockedActions`` **ne** va **pas** avoir d'effets sur les autres
+fonctionnalités de ``SecurityComponent``.
.. versionadded:: 2.3
diff --git a/fr/core-libraries/components/sessions.rst b/fr/core-libraries/components/sessions.rst
index 36be04068e..45fd001dc6 100644
--- a/fr/core-libraries/components/sessions.rst
+++ b/fr/core-libraries/components/sessions.rst
@@ -3,14 +3,14 @@ Sessions
.. php:class:: SessionComponent(ComponentCollection $collection, array $settings = array())
-Le component` session de CakePHP fournit le moyen de faire persister les données
-client entre les pages requêtées. Il agit comme une interface pour
-``$_SESSION`` et offre aussi des méthodes pratiques pour de nombreuses
-fonctions relatives à ``$_SESSION`.
-
-Les sessions peuvent être paramétrées de différentes façons dans CakePHP.
-Pour plus d'information, vous devriez lire la documentation
-:doc:`Session configuration `
+Le component session de CakePHP fournit le moyen de faire persister les données
+client entre les pages requêtées. Il agit comme une interface pour ``$_SESSION``
+et offre aussi des méthodes pratiques pour de nombreuses fonctions relatives
+à ``$_SESSION``.
+
+Les sessions peuvent être paramétrées de différentes façons dans CakePHP. Pour
+plus d'information, vous devriez lire la documentation :doc:`Session
+configuration `
Interagir avec les données de Session
=====================================
diff --git a/fr/core-libraries/events.rst b/fr/core-libraries/events.rst
index 8d3c63ae90..63f5aa978f 100644
--- a/fr/core-libraries/events.rst
+++ b/fr/core-libraries/events.rst
@@ -36,90 +36,104 @@ qui détiennent l'information et la possibilité d'arrêter la propagation des
peuvent déléguer cette tâche a d'autres objets et avoir la chance de modifier
l'état et l'événement lui-même pour le reste des callbacks.
-Interagir avec le gestionnaire d'événement
-==========================================
-
-Imaginons que vous être en train de construire un plugin Caddie, mais vous ne
-voulez pas vraiment l'encombrer avec une logique d'expédition, expédier un mail
-à l'utilisateur ou décrémenter les articles depuis le stock, c'est votre
-souhait de traiter tout cela séparément dans un autre plugin ou dans le code de
-l'application. Typiquement, quand vous n'utilisez pas directement le modèle
-observateur(observer pattern) vous voudriez faire cela en attachant des
-behaviors à la volée à vos modèles, et peut être quelques components aux
-controllers.
-
-Faire cela représente un challenge la plupart du temps, puisque vous allez
-devoir aborder du code pour charger de manière externe ces behaviors ou
-d'attacher des hooks aux controllers de votre plugin. Avant CakePHP 2.1
-quelques développeurs choisissaient d'implémenter des événements systèmes
-génériques pour résoudre ce problème, et certain de ces systèmes étaient
-offerts comme plugins. Maintenant, vous pouvez bénéficier en standard d'un
-système d'événements qui vous laissera proprement séparer ce qui concerne vos
-plugins et le code de l'application avec le gestionnaire d'événements intégré.
-
-Distribution des événements
----------------------------
-
-Revenons à notre exemple, nous aurions un model `Order` qui gèrera la logique
-d'achat, et probablement une méthode `place` pour enregistrer les détails de
-la commande et faire d'autres logiques::
+Le sous-système d'event est au coeur des callbacks de Model, de Behavior, de
+Controller, de View et de Helper. Si vous avez jamais utilisé aucun d'eux,
+vous êtes déjà quelque part familier avec les events dans CakePHP.
+
+Example event usage
+===================
+
+Let's suppose you are building a Cart plugin, and you'd like to focus on just
+handling order logic. You don't really want to include shipping logic, emailing
+the user or decrementing the item from the stock, but these are important tasks
+to the people using your plugin. If you were not using events, you may try to
+implement this by attaching behaviors to models, or adding components to your
+controllers. Doing so represents a challenge most of the time, since you
+would have to come up with the code for externally loading those behaviors or
+attaching hooks to your plugin controllers.
+
+Instead, you can use events to allow you to cleanly separate the concerns of
+your code and allow additional concerns to hook into your plugin using events.
+For example in your Cart plugin you have an Order model that deals with creating
+orders. You'd like to notify the rest of the application that an order has been
+created. To keep your Order model clean you could use events::
// Cart/Model/Order.php
+ App::uses('CakeEvent', 'Event');
class Order extends AppModel {
public function place($order) {
if ($this->save($order)) {
$this->Cart->remove($order);
- $this->sendNotificationEmail();
- $this->decrementFromStock();
- $this->updateUserStatistics();
- // ...
+ $event = new CakeEvent('Model.Order.afterPlace', $this, array(
+ 'order' => $order
+ ));
+ $this->getEventManager()->dispatch($event);
return true;
}
return false;
}
}
-Bien, cela ne semble pas correct du tout. Un plugin ne devrait pas faire
-d'hypothèse sur l'envoi d'email, et devrait même ne pas avoir à décrémenter
-les données d'inventaire, et finalement le suivi statistique n'est pas le
-meilleur endroit pour le faire. Nous avons donc besoin d'une autre solution,
-ré-écrivons en utilisant le gestionnaire d'événements. ::
+The above code allows you to easily notify the other parts of the application
+that an order has been created. You can then do tasks like send email
+notifications, update stock, log relevant statistics and other tasks in separate
+objects that focus on those concerns.
- // Cart/Model/Order.php
- App::uses('CakeEvent', 'Event');
- class Order extends AppModel {
+Accéder aux gestionnaires d'event
+=================================
- public function place($order) {
- if ($this->save($order)) {
- $this->Cart->remove($order);
- $this->getEventManager()->dispatch(new CakeEvent('Model.Order.afterPlace', $this, array(
- 'order' => $order
- )));
- return true;
- }
- return false;
- }
- }
+In CakePHP events are triggered against event managers. Event managers are
+available in every Model, View and Controller using ``getEventManager()``::
+
+ $events = $this->getEventManager();
+
+Each model has a separate event manager, while the View and Controller
+share one. This allows model events to be self contained, and allow components
+or controllers to act upon events created in the view if necessary.
+
+Le gestionnaire d'événement global
+----------------------------------
+
+In addition to instance level event managers, CakePHP provides a global event
+manager that allows you to listen to any event fired in an application. This
+is useful when attaching listeners to a specific instance might be cumbersome or
+difficult. The global manager is a singleton instance of
+:php:class:`CakeEventManager`. When an event is
+dispatched, it will be dispatched to the both the global and instance level
+listeners in priority order. You can access the global manager using a static method::
+
+ // Dans n'importe quel fichier de config ou morceau de code qui s'exécute avant l'événement
+ App::uses('CakeEventManager', 'Event');
+ CakeEventManager::instance()->attach(
+ $aCallback,
+ 'Model.Order.afterPlace'
+ );
+
+Un élément important que vous devriez considérer est qu'il y a des événements
+qui seront déclenchés en ayant le même nom mais différents sujets, donc les
+vérifier dans l'objet événement est généralement requis dans chacune des
+fonctions qui sont attachées globalement pour éviter quelques bugs.
+Souvenez-vous qu'une extrême flexibilité implique une extrême complexité.
+
+.. versionchanged:: 2.5
+
+ Avant 2.5, les listeners du gestionnaire global étaient gardés dans une
+ liste séparée et déclenchés **avant** que les instances de listeners le
+ soient.
+
+Distribution des événements
+===========================
-Cela semble beaucoup plus clair, puisque cela nous donne l'opportunité
-d'introduire des classes d'événement et des méthodes. La première chose que
-vous devriez noter c'est l'appel à ``getEventManager()`` qui est une méthode
-disponible par défaut dans tous les Models, Controllers, et les Vues. Cette
-méthode ne retournera pas la même instance du gestionnaire aux travers des
-models, et n'est pas partagée entre les controllers et les models, mais elle
-l'est entre les controllers et les vues, cependant. Nous reverrons plus tard
-comment surmonter ce détail d'implémentation.
-
-La méthode ``getEventManager`` retourne une instance de
-:php:class:`CakeEventManager`, et pour dispatcher les événements vous utilisez
-:php:meth:`CakeEventManager::dispatch()` qui reçoit une instance de la classe
-:php:class:`CakeEvent`. Disséquons maintenant le processus de dispatching
-d'un événement::
-
- new CakeEvent('Model.Order.afterPlace', $this, array(
+Once you have obtained an instance of an event manager you can dispatch events
+using :php:meth:`~CakeEventManager::dispatch()`. This method takes an instance
+of the :php:class:`CakeEvent` class. Let's look at dispatching an event::
+
+ // Create a new event and dispatch it.
+ $event = new CakeEvent('Model.Order.afterPlace', $this, array(
'order' => $order
));
+ $this->getEventManager()->dispatch($event);
:php:class:`CakeEvent` reçoit 3 arguments dans son constructeur. Le premier
est le nom de l'événement, vous devrez essayer de garder ce nom aussi unique
@@ -152,58 +166,6 @@ emails, éventuellement mettre à jour les statistiques de l'utilisateur dans
des objets séparés et même déléguer cela à des tâches hors-ligne si vous
en avez besoin.
-Enregistrement des callbacks
-----------------------------
-
-Comment allons nous enregistrer les callbacks ou les observateurs
-(observers) dans notre nouvel événement `afterPlace`? Ceci est sujet à
-une grande variété d'implémentation, mais elles ont toutes à appeler la méthode
-:php:meth:`CakeEventManager::attach()` pour enregistrer les nouveaux acteurs.
-Par souci de simplicité, imaginons que nous savons dans le plugin de quoi les
-callbacks sont capables dans le controller, et disons que ce controller
-est responsable de leur attachement. Le code possible pourrait être cela ::
-
- // Les écouteurs (Listeners) configurés quelque part ailleurs, un fichier de config par ex:
- Configure::write('Order.afterPlace', array(
- 'email-sending' => 'EmailSender::sendBuyEmail',
- 'inventory' => array($this->InventoryManager, 'decrement'),
- 'logger' => function($event) {
- // Les fonction Anonyme ne sont permises que dans PHP 5.3+
- CakeLog::write('info', 'Un nouvel achat à été placé avec l\'id: ' . $event->subject()->id);
- }
- ));
-
- // Cart/Controller/OrdersController.php
- class OrdersController extends AppController {
-
- public function finish() {
- foreach (Configure::read('Order.afterPlace') as $l) {
- $this->Order->getEventManager()->attach($l, 'Model.Order.afterPlace');
- }
- if ($this->Order->place($this->Cart->items())) {
- // ...
- }
- }
- }
-
-Ce ne sera pas la façon la plus propre de la faire, ainsi nous pouvons arriver
-avec nos propres moyens pour attacher des écouteurs au gestionnaire d'événement
-d'un objet. Cette façon simple de les définir en utilisant la classe
-`Configure` est destinée a des fins didactiques seulement. Ce petit exemple
-nous permet de montrer quel type de callbacks peuvent être attachés au
-gestionnaire (manager). Comme vous vous en doutiez, la méthode `attach` prend
-n'importe quel type de `callback` PHP valide, c'est une chaîne représentant
-l'appel à une fonction statique, un tableau ayant une instance de classe et une
-méthode, une fonction anonyme si vous utilisez PHP 5.3 ,etc...
-Les callbacks attachés recevront l'objet événement comme premier argument.
-
-:php:meth:`CakeEventManager::attach()` accepte trois arguments. Le plus à
-gauche est le callback lui même, n'importe quoi que PHP peut traiter comme
-une fonction appelable. Le second argument est le nom de l'événement, et le
-callback ne sera envoyé que si l'objet `CakeEvent` envoyé a un nom
-correspondant. Le dernier argument est un tableau d'options pour configurer
-la priorité du callback,et les arguments préférentiels à envoyer.
-
Enregistrer les écouteurs
-------------------------
@@ -245,6 +207,35 @@ manipuler les instances de l'interface `CakeEventListener`. En interne, le
gestionnaire d'événement lira le tableau retourné par la méthode
`implementedEvents` et relie les callbacks en conséquence.
+Registering anonymous listeners
+-------------------------------
+
+While event listener objects are generally a better way to implement listeners,
+you can also bind any ``callable`` as an event listener. For example if we
+wanted to put any orders into the log files, we could use a simple anonymous
+function to do so::
+
+ // Anonymous functions require PHP 5.3+
+ $this->Order->getEventManager()->attach(function($event) {
+ CakeLog::write(
+ 'info',
+ 'A new order was placed with id: ' . $event->subject()->id
+ );
+ }, 'Model.Order.afterPlace');
+
+In addition to anonymous functions you can use any other callable type that PHP
+supports::
+
+ $events = array(
+ 'email-sending' => 'EmailSender::sendBuyEmail',
+ 'inventory' => array($this->InventoryManager, 'decrement'),
+ );
+ foreach ($events as $callable) {
+ $eventManager->attach($callable, 'Model.Order.afterPlace');
+ }
+
+.. _event-priorities:
+
Établir des priorités
---------------------
@@ -440,7 +431,7 @@ Retirer des callbacks et écouteurs (listeners)
Si pour quelque raison que ce soit, vous voulez retirer certains callbacks
depuis le gestionnaire d'événement, appelez juste la méthode
:php:meth:`CakeEventManager::detach()` en utilisant comme arguments les
-deux premiers paramètres que vous avez utilisés pour les attacher ::
+deux premiers paramètres que vous avez utilisés pour les attacher::
// Attacher une fonction
$this->getEventManager()->attach(array($this, 'doSomething'), 'My.event');
@@ -456,73 +447,14 @@ deux premiers paramètres que vous avez utilisés pour les attacher ::
$this->getEventManager()->detach($myFunction, 'My.event');
// Attacher un écouteur Cake (CakeEventListener)
- $listener = new MyCakeEventLister();
+ $listener = new MyEventLister();
$this->getEventManager()->attach($listener);
// Détacher une simple clé d'événement depuis un écouteur (listener)
$this->getEventManager()->detach($listener, 'My.event');
// Détacher tous les callbacks implémentés par un écouteur (listener)
- $this->getEventManager()->attach($listener);
-
-Le gestionnaire d'événement global
-==================================
-
-Comme noté précédemment, cela pourrait être difficile d'attacher les
-observateurs à un gestionnaire d'événement particulier dans un objet. il y
-a certains cas où avoir la possibilité d'attacher des callbacks à un événement
-est nécessaire sans avoir accès à l'instance objet qui le déclenchera. Aussi,
-pour empêcher les gens d'implémenter pour chacun d'eux un mécanisme différent
-pour le chargement des callbacks dans les gestionnaires en fonction de la
-configuration, CakePHP fournit le concept du gestionnaire d'événement global
-`global event manager`.
-
-Le gestionnaire global est une instance singleton de la classe
-``CakeEventManager`` qui reçoit tous les événements que n'importe quel
-gestionnaire d'événement dans l'application dispatches. C'est à la fois
-flexible et puissant, mais si vous l'utilisez vous devez prendre plus
-de précautions avec le traitement des événements.
-
-Pour définir le concept une fois de plus, et utiliser notre exemple
-`beforePlace` souvenons nous que nous utilisions le gestionnaire d'événement
-local qui est retourné par la fonction `getEventManager`. En interne ce
-gestionnaire d'événement local dispatche l'événement dans le gestionnaire
-d'événement global avant de déclencher les callbacks internes attachés. La
-priorité de chacun des managers est indépendante, le callback global se
-lancera dans leur propre file d'attente et ainsi les callbacks locaux
-seront appelés dans l'ordre de priorité respectifs.
-
-Accéder au gestionnaire d'événement global est aussi simple que d'appeler une
-fonction statique, l'exemple suivant va attacher un événement global à
-l'événement `beforePlace` ::
-
- // Dans n'importe quel fichier de config ou morceau de code qui s'exécute avant l'événement
- App::uses('CakeEventManager', 'Event');
- CakeEventManager::instance()->attach($aCallback, 'Model.Order.beforePlace');
-
-Comme vous pouvez le voir, nous avons juste changé comment nous avons accès à
-l'instance du gestionnaire d'événement, et nous pouvons appliquer les mêmes
-concepts que nous avons appris précédemment à propos du déclenchement, de
-l'attachement, du détachement, du stoppage d'événement, etc...
-
-Un élément important que vous devriez considérer est qu'il y a des événements
-qui seront déclenchés en ayant le même nom mais différents sujets, donc les
-vérifier dans l'objet événement est généralement requis dans chacune des
-fonctions qui sont attachées globalement pour éviter quelques bugs.
-Souvenez-vous qu'une extrême flexibilité implique une extrême complexité.
-
-Examinez ce callback qui veut écouter tous les models beforeFind mais en
-réalité, il ne peut pas faire sa logique si le model est le caddie::
-
- App::uses('CakeEventManager', 'Event');
- CakeEventManager::instance()->attach('myCallback', 'Model.beforeFind');
-
- public function myCallback($event) {
- if ($event->subject() instanceof Cart) {
- return;
- }
- return array('conditions' => ...);
- }
+ $this->getEventManager()->detach($listener);
Conclusion
==========
@@ -530,19 +462,12 @@ Conclusion
Les événements sont une bonne façon de séparer les préoccupations dans
votre application et rend les classes a la fois cohérentes et découplées des
autres, néanmoins l'utilisation des événements n'est pas la solution
-à tous les problèmes. La plupart des applications n'auront pas réellement
-besoin de cette fonctionnalité, nous vous recommandons d'examiner d'autres
-options quand vous implémentez les callbacks comme
-l'utilisation des behaviors, des components et des helpers.
-
-Gardez à l'esprit que beaucoup de pouvoir implique beaucoup de responsabilité,
-découpler vos classes par ce moyen signifie également que vous avez besoin
-d'effectuer une plus grande et meilleur intégration en testant votre code.
-Abuser de cet outil ne donnera pas à votre application une meilleure
-architecture, bien au contraire, cela sera beaucoup plus difficile à lire. En
-revanche si vous utilisez cet option à bon escient, seulement pour les choses
-dont vous avez besoin, Ce sera plus simple de travailler avec votre code, de
-le tester et de l'intégrer.
+à tous les problèmes. Les Events peuvent être utilisés pour découpler le code
+de l'application et rendre les plugins extensibles.
+
+Gardez à l'esprit que beaucoup de pouvoir implique beaucoup de responsabilité.
+Utiliser trop d'events peut rendre le debug plus difficile et nécessite des
+tests d'intégration supplémentaires.
Lecture Supplémentaire
======================
diff --git a/fr/core-libraries/global-constants-and-functions.rst b/fr/core-libraries/global-constants-and-functions.rst
index 7c237f6c64..962cd7ea85 100644
--- a/fr/core-libraries/global-constants-and-functions.rst
+++ b/fr/core-libraries/global-constants-and-functions.rst
@@ -41,16 +41,16 @@ CakePHP, comme le débogage et la traduction de contenu.
.. php:function:: __c(string $msg, integer $category, mixed $args = null)
- Notez que la catégorie doit être spécifiée avec une valeur numérique,
- au lieu d'un nom de constante. Les valeurs sont:
+ Notez que la catégorie doit être spécifiée avec une constante de classe
+ I18n, au lieu d'un nom de constante. Les valeurs sont:
- - 0 - LC_ALL
- - 1 - LC_COLLATE
- - 2 - LC_CTYPE
- - 3 - LC_MONETARY
- - 4 - LC_NUMERIC
- - 5 - LC_TIME
- - 6 - LC_MESSAGES
+ - I18n::LC_ALL - LC_ALL
+ - I18n::LC_COLLATE - LC_COLLATE
+ - I18n::LC_CTYPE - LC_CTYPE
+ - I18n::LC_MONETARY - LC_MONETARY
+ - I18n::LC_NUMERIC - LC_NUMERIC
+ - I18n::LC_TIME - LC_TIME
+ - I18n::LC_MESSAGES - LC_MESSAGES
.. php:function:: __d(string $domain, string $msg, mixed $args = null)
@@ -65,16 +65,16 @@ CakePHP, comme le débogage et la traduction de contenu.
Vous permet de remplacer le domaine courant pour la recherche d'un message.
Permet également de spécifier une catégorie.
- Notez que la catégorie doit être spécifiée avec une valeur numérique,
+ Notez que la catégorie doit être spécifiée avec une constante de classe I18n
au lieu du nom de la constante. Les valeurs sont:
- - 0 - LC_ALL
- - 1 - LC_COLLATE
- - 2 - LC_CTYPE
- - 3 - LC_MONETARY
- - 4 - LC_NUMERIC
- - 5 - LC_TIME
- - 6 - LC_MESSAGES
+ - I18n::LC_ALL - LC_ALL
+ - I18n::LC_COLLATE - LC_COLLATE
+ - I18n::LC_CTYPE - LC_CTYPE
+ - I18n::LC_MONETARY - LC_MONETARY
+ - I18n::LC_NUMERIC - LC_NUMERIC
+ - I18n::LC_TIME - LC_TIME
+ - I18n::LC_MESSAGES - LC_MESSAGES
.. php:function:: __dcn(string $domain, string $singular, string $plural, integer $count, integer $category, mixed $args = null)
@@ -84,16 +84,16 @@ CakePHP, comme le débogage et la traduction de contenu.
pour le compteur $count depuis le domaine $domain. Certaines langues ont
plus d'une forme de pluriel dépendant du compteur.
- Notez que la catégorie doit être spécifiée avec des valeurs numériques,
- au lieu des noms de constantes. Les valeurs sont:
+ Notez que la catégorie doit être spécifiée avec des une constante de classe
+ I18n, au lieu des noms de constantes. Les valeurs sont:
- - 0 - LC_ALL
- - 1 - LC_COLLATE
- - 2 - LC_CTYPE
- - 3 - LC_MONETARY
- - 4 - LC_NUMERIC
- - 5 - LC_TIME
- - 6 - LC_MESSAGES
+ - I18n::LC_ALL - LC_ALL
+ - I18n::LC_COLLATE - LC_COLLATE
+ - I18n::LC_CTYPE - LC_CTYPE
+ - I18n::LC_MONETARY - LC_MONETARY
+ - I18n::LC_NUMERIC - LC_NUMERIC
+ - I18n::LC_TIME - LC_TIME
+ - I18n::LC_MESSAGES - LC_MESSAGES
.. php:function:: __dn(string $domain, string $singular, string $plural, integer $count, mixed $args = null)
@@ -144,7 +144,7 @@ CakePHP, comme le débogage et la traduction de contenu.
Cette fonction émule également PHP_SELF et DOCUMENT_ROOT sur
les serveurs ne les supportant pas. En fait, c'est une bonne idée
- de toujours utiliser ``env()`` plutôt que ``$_SERVER`` ou ``getenv()`
+ de toujours utiliser ``env()`` plutôt que ``$_SERVER`` ou ``getenv()``
(notamment si vous prévoyez de distribuer le code), puisque
c'est un wrapper d'émulation totale.
diff --git a/fr/core-libraries/helpers/form.rst b/fr/core-libraries/helpers/form.rst
index b409369d74..b9c3df60ab 100644
--- a/fr/core-libraries/helpers/form.rst
+++ b/fr/core-libraries/helpers/form.rst
@@ -234,7 +234,7 @@ Il y plusieurs options pour create():
Fermer le Formulaire
====================
-.. php:method:: end($options = null)
+.. php:method:: end($options = null, $secureAttributes = array())
Le FormHelper inclut également une méthode ``end()`` qui
complète le marquage du formulaire. Souvent, ``end()`` affiche juste
@@ -291,6 +291,9 @@ Fermer le Formulaire
dans votre application vous devez toujours terminer vos formulaires
avec ``end()``.
+ .. versionchanged:: 2.5
+ Le paramètre ``$secureAttributes`` a été ajouté dans 2.5.
+
.. _automagic-form-elements:
Création d'éléments de Formulaire
@@ -332,6 +335,8 @@ ce champ. En interne ``input()`` délègue aux autre méthode du FormHelper.
day, month, year, hour, minute, et meridian selects
time
hour, minute, et meridian selects
+ binary
+ file
Le paramètre ``$options`` vous permet de personnaliser le
fonctionnement de ``input()``, et contrôle finement ce qui est généré.
@@ -342,6 +347,9 @@ ce champ. En interne ``input()`` délègue aux autre méthode du FormHelper.
du model doit avoir été chargé pendant la requête. Ou être directement
associé au model fourni par :php:meth:`~FormHelper::create()`.
+ .. versionadded:: 2.5
+ Le type binaire mappe maintenant vers un input de fichier.
+
.. versionadded:: 2.3
.. _html5-required:
@@ -429,10 +437,11 @@ ce champ. En interne ``input()`` délègue aux autre méthode du FormHelper.
Essayez d'éviter l'utilisation de `FormHelper::input()` pour générer
les boutons submit. Utilisez plutôt :php:meth:`FormHelper::submit()`.
-.. php:method:: inputs(mixed $fields = null, array $blacklist = null)
+.. php:method:: inputs(mixed $fields = null, array $blacklist = null, $options = array())
Génère un ensemble d'inputs (entrées) pour ``$fields``. Si $fields est
- null, le model courant sera utilisé.
+ null, tous les champs, sauf ceux définis dans ``$blacklist``, du model
+ courant seront utilisés.
En plus de l'affichage des champs de controller, ``$fields`` peut
être utilisé pour contrôler legend et fieldset (jeu de champs) rendus
@@ -1076,8 +1085,9 @@ Ex: name=data[User][username], id=UserUsername
les informations sauvegardées pour le model ``User``), la valeur
correspondant au champs ``notes`` sera automatiquement ajoutée au HTML
généré. Exemple:
-
+
.. code-block:: html
+
@@ -1167,8 +1177,8 @@ Ex: name=data[User][username], id=UserUsername
désactivera tous les boutons radios générés.
* ``$attributes['legend']`` Les éléments Radio sont enveloppés avec un
- label et un fieldset (jeu de champs) par défaut. Définir
- ``$attributes['legend']`` à false pour les retirer.::
+ legend et un fieldset par défaut. Définir ``$attributes['legend']`` à
+ false pour les retirer.::
$options = array('H' => 'Homme', 'F' => 'Femme');
$attributes = array('legend' => false);
diff --git a/fr/core-libraries/helpers/html.rst b/fr/core-libraries/helpers/html.rst
index 427c2bb66a..33791ee2b5 100644
--- a/fr/core-libraries/helpers/html.rst
+++ b/fr/core-libraries/helpers/html.rst
@@ -189,7 +189,7 @@ couvrira les méthodes du Helper Html et comment les utiliser.
/>
Cette méthode peut aussi être utilisée pour ajouter les balise de mots clés
- et les descriptions. Exemple::
+ et les descriptions. Exemple:
.. code-block:: php
@@ -419,7 +419,7 @@ couvrira les méthodes du Helper Html et comment les utiliser.
tableau et incluez les noms pour TOUS les paramètres dans l'URL. En
utilisant la syntaxe en chaîne pour les paramètres (par ex
"recipes/view/6/comments:false" va résulter à ce que les caractères
- seront echappés du HTML et le lien ne fonctionnera pas comme souhaité.:
+ seront echappés du HTML et le lien ne fonctionnera pas comme souhaité.::
Html->link(
@@ -440,9 +440,9 @@ couvrira les méthodes du Helper Html et comment les utiliser.
- Les caractères spéciaux HTML de ``$title``seront convertis en entités
+ Les caractères spéciaux HTML de ``$title`` seront convertis en entités
HTML. Pour désactiver cette conversion, définissez l'option escape à
- false dans le tableau ``$options``.::
+ false dans le tableau ``$options``::
Html->link(
@@ -505,7 +505,7 @@ couvrira les méthodes du Helper Html et comment les utiliser.
.. versionadded:: 2.1
- Retourne une balise formatée audio/video::
+ Retourne une balise formatée audio/video:
.. code-block:: php
@@ -522,7 +522,7 @@ couvrira les méthodes du Helper Html et comment les utiliser.
// Sortie
- Html->media(
+ Html->media(
array(
'video.mp4',
array(
@@ -1056,7 +1056,7 @@ Création d'un chemin de navigation avec le Helper Html
pour démarrer le fil d'Ariane sur chacune de vos pages.::
$this->Html->addCrumb('Users', '/users');
- $this->Html->addCrumb('Add User', '/users/add');
+ $this->Html->addCrumb('Add User', array('controller' => 'users', 'action' => 'add'));
Ceci ajoutera la sortie "**Home > Users > Add User**" dans votre layout
où le fil d'Ariane a été ajouté.
@@ -1065,7 +1065,7 @@ Création d'un chemin de navigation avec le Helper Html
:param array $options: Un tableau de :term:`html attributes` pour les
elements contenant ``
``. Peut aussi contenir les options
- 'separator', 'firstClass' et 'lastClass'.
+ 'separator', 'firstClass', 'lastClass' et 'escape'.
:param string|array $startText: Le texte ou l'elément qui précède ul.
Retourne le fil d'Ariane comme une liste (x)html.
@@ -1085,6 +1085,8 @@ Création d'un chemin de navigation avec le Helper Html
.. versionchanged:: 2.3
Les options 'separator', 'firstClass' et 'lastClass' ont été ajoutées.
+ .. versionchanged:: 2.5
+ L'option 'escape' a été ajoutée.
.. meta::
:title lang=fr: HtmlHelper
diff --git a/fr/core-libraries/helpers/js.rst b/fr/core-libraries/helpers/js.rst
index 5c523b1a98..351b57afb8 100644
--- a/fr/core-libraries/helpers/js.rst
+++ b/fr/core-libraries/helpers/js.rst
@@ -837,7 +837,7 @@ Ajouter des effets et des transitions
-------------------------------------
Depuis que `indicator`` n'est plus supporté, vous devez ajouter
-les effets d'indicator vous même.::
+les effets d'indicator vous même.:
.. code-block:: php
@@ -849,7 +849,7 @@ les effets d'indicator vous même.::
-
+ fetch('content'); ?>
Html->image(
diff --git a/fr/core-libraries/helpers/paginator.rst b/fr/core-libraries/helpers/paginator.rst
index e94f805f85..f564633f6f 100644
--- a/fr/core-libraries/helpers/paginator.rst
+++ b/fr/core-libraries/helpers/paginator.rst
@@ -8,7 +8,7 @@ comme les numéros de pages et les liens suivant/précédent. Il travaille en
tamdem avec :php:class:`PaginatorComponent`.
Voir aussi :doc:`/core-libraries/components/pagination` pour des informations
-sur la façon de créé des jeux de données paginés et faire des requêtes paginées.
+sur la façon de créer des jeux de données paginés et faire des requêtes paginées.
Création de liens triés
=======================
@@ -22,7 +22,7 @@ Création de liens triés
:param array $options: Options pour le tri des liens.
Génère un lien de tri. Définit le nom ou les paramètres de la chaîne de
-recherche pour le tri et la direction. Les liens par défaut fournirons un tri
+recherche pour le tri et la direction. Les liens par défaut fourniront un tri
ascendant. Après le premier clique, les liens générés avec ``sort()`` gèreront
le changement de direction automatiquement. Les liens de tri par défaut
ascendant. Si le jeu de résultat est trié en ascendant avec la clé spécifiée
@@ -30,9 +30,16 @@ le liens retourné triera en 'décroissant'.
Les clés acceptée pour ``$options``:
-* ``escape`` Si vous voulez que le contenu soit encoder en HTML, true par
+* ``escape`` Si vous voulez que le contenu soit encodé en HTML, true par
défaut.
* ``model`` Le model à utiliser, par défaut à PaginatorHelper::defaultModel().
+* ``direction`` La direction par défaut à utiliser quand ce lien n'est pas actif.
+* ``lock`` Verrouiller la direction. Va seulement utiliser la direction par
+ défaut, par défaut à false.
+
+ .. versionadded:: 2.5
+ Vous pouvez maintenant définir l'option lock à true afin de verrouiller
+ la direction du tri dans la direction spécifiée.
En considérant que vous paginez des posts, qu'ils sont sur la page un::
@@ -55,7 +62,7 @@ Sortie:
User account
-Si vous utilisez du HTML comme des images dans vos liens rappelez-vous de
+Si vous utilisez de l'HTML comme des images dans vos liens rappelez-vous de
paramétrer l'échappement::
echo $this->Paginator->sort(
@@ -84,6 +91,11 @@ Sortie
User Id
+L'option lock peut être utilisée pour verrouiller le tri dans la direction
+spécifiée::
+
+ echo $this->Paginator->sort('user_id', null, array('direction' => 'asc', 'lock' => true));
+
.. php:method:: sortDir(string $model = null, mixed $options = array())
récupère la direction courante du tri du jeu d'enregistrement.
diff --git a/fr/core-libraries/helpers/rss.rst b/fr/core-libraries/helpers/rss.rst
index 607fb35099..92d55dc80a 100644
--- a/fr/core-libraries/helpers/rss.rst
+++ b/fr/core-libraries/helpers/rss.rst
@@ -93,10 +93,10 @@ Un layout Rss est très simple, mettez les contenus suivants dans
$channelData = array();
}
if (!isset($channelData['title'])) {
- $channelData['title'] = $title_for_layout;
- }
- $channel = $this->Rss->channel(array(), $channelData, $content_for_layout);
- echo $this->Rss->document($documentData,$channel);
+ $channelData['title'] = $this->fetch('title');
+ }
+ $channel = $this->Rss->channel(array(), $channelData, $this->fetch('content'));
+ echo $this->Rss->document($documentData, $channel);
Il ne ressemble pas à plus mais grâce à la puissance du ``RssHelper``
il fait beaucoup pour améliorer le visuel pour nous. Nous n'avons pas défini
diff --git a/fr/core-libraries/internationalization-and-localization.rst b/fr/core-libraries/internationalization-and-localization.rst
index 53c109d0c7..e90e98a985 100644
--- a/fr/core-libraries/internationalization-and-localization.rst
+++ b/fr/core-libraries/internationalization-and-localization.rst
@@ -57,7 +57,7 @@ traductions. CakePHP cherchera vos fichiers po dans les dossiers suivants ::
/app/Locale//LC_MESSAGES/.po
Le domaine par défaut est 'default', donc votre dossier "locale"
-devrait ressembler à cela ::
+devrait ressembler à cela::
/app/Locale/eng/LC_MESSAGES/default.po (Anglais)
/app/Locale/fra/LC_MESSAGES/default.po (Français)
@@ -95,7 +95,7 @@ d'une solution différente. Par ex ::
// Code du fichier App Controller.
public function beforeFilter() {
$locale = Configure::read('Config.language');
- if ($locale && file_exists(VIEWS . $locale . DS . $this->viewPath)) {
+ if ($locale && file_exists(APP . 'View' . DS . $locale . DS . $this->viewPath)) {
// utilise /app/views/fra/pages/tos.ctp au lieu de /app/views/pages/tos.ctp
$this->viewPath = $locale . DS . $this->viewPath;
}
diff --git a/fr/core-libraries/logging.rst b/fr/core-libraries/logging.rst
index 85599e30fd..f76d63c432 100755
--- a/fr/core-libraries/logging.rst
+++ b/fr/core-libraries/logging.rst
@@ -52,10 +52,11 @@ utilisé pour localiser et charger le handler de log. Toutes les autres
propriétés de configuration sont passées au constructeur des flux de log comme
un tableau.::
- App::uses('CakeLogInterface', 'Log');
+ App::uses('BaseLog', 'Log');
- class DatabaseLog implements CakeLogInterface {
+ class DatabaseLog extends BaseLog {
public function __construct($options = array()) {
+ parent::__construct($options);
// ...
}
@@ -64,8 +65,15 @@ un tableau.::
}
}
-CakePHP n'a pas d'exigences pour les flux de log sinon qu'il doit implémenter
-une méthode ``write``. Cette méthode ``write`` doit prendre deux paramètres,
+Alors que CakePHP n'a pas d'exigences pour les flux de Log sinon qu'il doit
+implémenter une méthode ``write``, en étendant la classe ``BaseLog`` a
+quelques bénéfices.
+
+- Il gère automatiquement le scope et type argument casting.
+- Il intègre la méthode ``config()`` qui est requise pour faire le travail du
+ scope de logging.
+
+Chaque méthode ``write`` doit prendre deux paramètres,
dans l'ordre ``$type, $message``.``$type`` est le type de chaîne du message
logué, les valeurs de noyau sont ``error``, ``warning``, ``info`` et ``debug``.
De plus vous pouvez définir vos propres types par leur utilisation en appelant
@@ -75,7 +83,7 @@ De plus vous pouvez définir vos propres types par leur utilisation en appelant
.. versionadded:: 2.4
-Depuis 2.4 le moteur de ``FileLog`` a quelques nouvelles configurations::
+Depuis 2.4 le moteur de ``FileLog`` a quelques nouvelles configurations:
* ``size`` Utilisé pour implémenter la rotation de fichier de journal basic.
Si la taille d'un fichier de log atteint la taille spécifiée, le fichier
@@ -190,9 +198,7 @@ les écritures ou utiliser un stockage complètement différent pour vos logs.
Utiliser syslog est à peu près comme utiliser le moteur par défaut FileLog,
vous devez juste spécifier `Syslog` comme moteur à utiliser pour la
journalisation. Le bout de configuration suivant va remplacer le logger
-par défaut avec syslog, ceci va être fait dans le fichier `bootstrap.php`.
-
-::
+par défaut avec syslog, ceci va être fait dans le fichier `bootstrap.php`::
CakeLog::config('default', array(
'engine' => 'Syslog'
@@ -234,11 +240,19 @@ interne CakeLog::write()::
$this->log("Quelque chose qui ne fonctionne pas!", 'debug');
Tous les flux de log configurés sont écrits séquentiellement à chaque fois
-que :php:meth:`CakeLog::write()` est appelée. Vous n'avez pas besoin de
-configurer un flux pour utiliser la journalisation. Si il n'y a pas de flux
-configuré quand le log est écrit, un flux par ``défaut`` utilisant la classe
-de noyau ``FileLog`` sera configuré pour envoyer en sortie vers
-``app/tmp/logs/`` juste comme CakeLog le faisait dans les précédentes versions.
+que :php:meth:`CakeLog::write()` est appelée.
+
+.. versionchanged:: 2.5
+
+CakeLog ne s'auto-configure plus lui-même. En résultat, les fichiers de log,
+ne seront plus auto-créés si aucun flux n'est écouté. Assurez-vous que vous
+ayez au moins un flux ``default`` configuré si vous souhaitez écouter tous
+les types et les niveaux. Habituellement, vous pouvez juste définir la classe
+``FileLog`` du coeur pour le sortir dans ``app/tmp/logs/``::
+
+ CakeLog::config('default', array(
+ 'engine' => 'File'
+ ));
.. _logging-scopes:
diff --git a/fr/core-utility-libraries/file-folder.rst b/fr/core-utility-libraries/file-folder.rst
index 04ae31ae28..8db4bd5404 100644
--- a/fr/core-utility-libraries/file-folder.rst
+++ b/fr/core-utility-libraries/file-folder.rst
@@ -70,10 +70,16 @@ API de Folder
Retourne $path avec $element ajouté, avec le bon slash entre-deux::
- copy(array(
- 'from' => '/path/to/copy/from', // va causer un cd() to occur
'to' => '/path/to/new/folder',
+ 'from' => '/path/to/copy/from', // va entraîner l'execution de cd()
'mode' => 0755,
'skip' => array('skip-me.php', '.git'),
- 'scheme' => Folder::SKIP // Skip directories/files qui existe déjà.
+ 'scheme' => Folder::SKIP // Passe les répertoires/fichiers qui existent déjà.
));
y a 3 schémas supportés:
@@ -589,7 +595,16 @@ L'API de File
:rtype: mixed
Récupère le mimetype du Fichier, retourne false en cas d'échec.
-
+
+.. php:method:: replaceText( $search, $replace )
+
+ :rtype: boolean
+
+ Remplace le texte dans un fichier. Retourne false en cas d'échec et true en cas de succès.
+
+ .. versionadded::
+ 2.5 ``File::replaceText()``
+
.. meta::
:title lang=fr: Folder & File
:description lang=fr: Les utilitaires Folder et File sont des classes pratiques pour aider à la lecture, l'écriture; et l'ajout de fichiers; Lister les fichiers d'un dossier et autres tâches habituelles liées aux répertoires.
diff --git a/fr/core-utility-libraries/hash.rst b/fr/core-utility-libraries/hash.rst
index e6b784ac08..6cd775d0b2 100644
--- a/fr/core-utility-libraries/hash.rst
+++ b/fr/core-utility-libraries/hash.rst
@@ -46,9 +46,9 @@ Types d'expression
Tous les éléments d'expression supportent toutes les méthodes. En plus des
éléments d'expression, vous pouvez utiliser les attributs qui matchent avec
-certaines méthodes. Il y a ``extract()``,
-``combine()``, ``format()``, ``check()``, ``map()``, ``reduce()``,
-``apply()``, ``sort()`` et ``nest()``.
+certaines méthodes. Il y a ``extract()``, ``combine()``, ``format()``,
+``check()``, ``map()``, ``reduce()``, ``apply()``, ``sort()``, ``insert()``,
+``remove()`` et ``nest()``.
Les Types d'Attribut Correspondants
-----------------------------------
@@ -80,6 +80,9 @@ Les Types d'Attribut Correspondants
| | à l'intérieur de ``...``. |
+--------------------------------+--------------------------------------------+
+.. versionchanged:: 2.5
+ Le support des matcher a été ajouté dans ``insert()`` et ``remove()``.
+
.. php:staticmethod:: get(array $data, $path)
:rtype: mixed
@@ -110,8 +113,7 @@ Les Types d'Attribut Correspondants
:rtype: array
- Insère $values dans un tableau tel que défini dans $path. Cette méthode
- supporte **seulement** les types d'expression de :ref:`hash-path-syntax`::
+ Insère $data dans un tableau tel que défini dans ``$path``::
$a = array(
'pages' => array('name' => 'page')
@@ -136,13 +138,15 @@ Les Types d'Attribut Correspondants
$users = $this->User->find('all');
$users = Set::insert($users, '{n}.User.new', 'value');
+ .. versionchanged:: 2.5
+ Depuis 2.5.0, les expressions matchant l'attribut fonctionnent avec
+ insert().
+
.. php:staticmethod:: remove(array $data, $path = null)
:rtype: array
- Retire tous les éléments d'un tableau qui matche avec $path. Cette
- méthode supporte **seulement** tous les éléments d'expression de
- :ref:`hash-path-syntax`::
+ Retire tous les éléments d'un tableau qui matche avec $path.::
$a = array(
'pages' => array('name' => 'page'),
@@ -163,6 +167,10 @@ Les Types d'Attribut Correspondants
L'utilisation de ``{n}`` et ``{s}`` vous autorisera à retirer les valeurs
multiples en une fois.
+ .. versionchanged:: 2.5
+ Depuis 2.5.0, les expressions matchant l'attribut fonctionnenent avec
+ remove()
+
.. php:staticmethod:: combine(array $data, $keyPath = null, $valuePath = null, $groupPath = null)
:rtype: array
@@ -634,6 +642,14 @@ Les Types d'Attribut Correspondants
les résultats. Vous pouvez utiliser les deux, expression et le matching
d'éléments avec cette méthode.
+ //appel de la fonction noop $this->noop() sur chaque element de $data
+ $result = Hash::map($data, "{n}", array($this, 'noop'));
+
+ function noop($array) {
+ //fait des trucs au tableau et retourne les résultats
+ return $array;
+ }
+
.. php:staticmethod:: reduce(array $data, $path, $function)
Crée une valeur unique, en extrayant $path, et en réduisant les résultats
diff --git a/fr/core-utility-libraries/httpsocket.rst b/fr/core-utility-libraries/httpsocket.rst
index 6ad3d4f810..da1f82411c 100755
--- a/fr/core-utility-libraries/httpsocket.rst
+++ b/fr/core-utility-libraries/httpsocket.rst
@@ -61,7 +61,8 @@ les différentes méthodes HTTP.
.. php:method:: delete($uri, $query, $request)
- La méthode put fait une requête simple HTTP PUT retournant les résultats.
+ La méthode delete fait une requête simple HTTP DELETE retournant les
+ résultats.
Les paramètres pour la méthode ``delete`` sont les mêmes que pour la
méthode :php:meth:`~HttpSocket::get()`. Le paramètre ``$query`` peut soit
@@ -385,7 +386,7 @@ le proxy dans la même classe d'authentification. Par exemple::
.. note::
Pour utiliser un proxy, vous devez appeler ``HttpSocket::configProxy()``
- semblalble à ``HttpSocket::configAuth()``.
+ semblable à ``HttpSocket::configAuth()``.
diff --git a/fr/core-utility-libraries/number.rst b/fr/core-utility-libraries/number.rst
index 29a124a929..8f1386c4d4 100644
--- a/fr/core-utility-libraries/number.rst
+++ b/fr/core-utility-libraries/number.rst
@@ -52,11 +52,11 @@ automatiqement la sortie dans la vue.
+---------------------+----------------------------------------------------+
| $currency | 1234.56, formaté par le type courant |
+=====================+====================================================+
- | EUR | €1.234,56 |
+ | EUR | €1.234,56 |
+---------------------+----------------------------------------------------+
- | GBP | £1,234.56 |
+ | GBP | £1,234.56 |
+---------------------+----------------------------------------------------+
- | USD | $1,234.56 |
+ | USD | $1,234.56 |
+---------------------+----------------------------------------------------+
Le troisième paramètre est un tableau d'options pour définir la sortie. Les
@@ -161,35 +161,36 @@ automatiqement la sortie dans la vue.
des formats de monnaie.::
// appelé par NumberHelper
- $this->Number->addFormat('BRR', array('before' => 'R$ '));
+ $this->Number->addFormat('BRL', array('before' => 'R$', 'thousands' => '.', 'decimals' => ','));
// appelé par CakeNumber
App::uses('CakeNumber', 'Utility');
- CakeNumber::addFormat('BRR', array('before' => 'R$ '));
+ CakeNumber::addFormat('BRL', array('before' => 'R$', 'thousands' => '.', 'decimals' => ','));
- Vous pouvez maintenant utiliser `BRR` de manière courte quand vous
+ Vous pouvez maintenant utiliser `BRL` de manière courte quand vous
formattez les montants de monnaie::
// appelé par NumberHelper
- echo $this->Number->currency($value, 'BRR');
+ echo $this->Number->currency($value, 'BRL');
// appelé par CakeNumber
App::uses('CakeNumber', 'Utility');
- echo CakeNumber::currency($value, 'BRR');
+ echo CakeNumber::currency($value, 'BRL');
Les formats ajoutés sont fusionnés avec les formats par défaut suivants::
array(
'wholeSymbol' => '',
'wholePosition' => 'before',
- 'fractionSymbol' => '',
+ 'fractionSymbol' => false,
'fractionPosition' => 'after',
'zero' => 0,
'places' => 2,
'thousands' => ',',
'decimals' => '.',
'negative' => '()',
- 'escape' => true
+ 'escape' => true,
+ 'fractionExponent' => 2
)
.. php:method:: precision(mixed $number, int $precision = 3)
diff --git a/fr/core-utility-libraries/security.rst b/fr/core-utility-libraries/security.rst
index f3f7743810..32e015f6ca 100644
--- a/fr/core-utility-libraries/security.rst
+++ b/fr/core-utility-libraries/security.rst
@@ -22,8 +22,10 @@ L'API de Security
// Plus tard, déchiffrez votre mot de passe secret
$nosecret = Security::cipher($secret, 'my_key');
- ``cipher()`` utilise un cipher XOR **faible** et **ne** doit **pas** être
- utilisé pour des données importantes ou sensibles.
+ .. warning::
+
+ ``cipher()`` utilise un cipher XOR **faible** et **ne** doit **pas**
+ être utilisé pour des données importantes ou sensibles.
.. php:staticmethod:: rijndael($text, $key, $mode)
@@ -51,6 +53,53 @@ L'API de Security
.. versionadded:: 2.2
``Security::rijndael()`` a été ajoutée pour la version 2.2.
+.. php:staticmethod:: encrypt($text, $key, $hmacSalt = null)
+
+ :param string $plain: La valeur à chiffrer.
+ :param string $key: La clé 256 bit/32 byte à utiliser en clé cipher.
+ :param string $hmacSalt: Le sel à utiliser pour le processus HMAC. Laissez null pour utiliser Security.salt.
+
+ Chiffre ``$text`` en utilisant AES-256. La ``$key`` devrait être une valeur
+ avec beaucoup de différence dans les données un peu comme un bon mot de
+ passe. Le résultat retourné sera la valeur chiffrée avec un checksum HMAC.
+
+ Cette méthode **ne** devrait **jamais** être utilisée pour stocker des mots
+ de passe. A la place, vous devriez utiliser la manière de hasher les mots
+ de passe fournie par :php:meth:`~Security::hash()`.
+ Un exemple d'utilisation serait::
+
+ // En supposant que la clé est stockée quelque part, elle peut être
+ // réutilisée pour le déchiffrement plus tard.
+ $key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
+ $result = Security::encrypt($value, $key);
+
+ Les valeurs chiffrés peuvent être déchiffrées en utilisant
+ :php:meth:`Security::decrypt()`.
+
+ .. versionadded:: 2.5
+
+.. php:staticmethod:: decrypt($cipher, $key, $hmacSalt = null)
+
+ :param string $cipher: Le ciphertext à déchiffrer.
+ :param string $key: La clé 256 bit/32 byte à utiliser pour une clé cipher.
+ :param string $hmacSalt: Le sel à utiliser pour un processus HMAC. Laissez null pour utiliser Security.salt.
+
+ Déchiffre une valeur chiffrée au préalable. Les paramètres ``$key`` et
+ ``$hmacSalt`` doivent correspondre aux valeurs utilisées pour chiffrer ou
+ alors le déchiffrement sera un échec. Un exemple d'utilisation serait::
+
+ // En supposant que la clé est stockée quelque part, elle peut être
+ // réutilisée pour le déchiffrement plus tard.
+ $key = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
+
+ $cipher = $user['User']['secrets'];
+ $result = Security::decrypt($cipher, $key);
+
+ Si la valeurne peut pas être déchiffrée à cause de changements dans la
+ clé ou le sel HMAC à ``false`` sera retournée.
+
+ .. versionadded:: 2.5
+
.. php:staticmethod:: generateAuthKey( )
:rtype: string
@@ -105,17 +154,6 @@ L'API de Security
.. versionchanged:: 2.3
Le support pour bcrypt a été ajouté dans la version 2.3.
-
-.. php:staticmethod:: inactiveMins( )
-
- :rtype: integer
-
- Pour avoir les minutes d'inactivité autorisées basée sur le niveau de
- sécurité.::
-
- $mins = Security::inactiveMins();
- // Si votre config Security.level est défini à 'medium' alors $mins sera égal 100.
-
.. php:staticmethod:: setHash( $hash )
:rtype: void
diff --git a/fr/core-utility-libraries/set.rst b/fr/core-utility-libraries/set.rst
index aedae62af2..f4aa478386 100644
--- a/fr/core-utility-libraries/set.rst
+++ b/fr/core-utility-libraries/set.rst
@@ -117,7 +117,7 @@ quelles options sont disponibles.
.. php:staticmethod:: classicExtract($data, $path = null)
- :rtype: array
+ :rtype: mixed
Récupère une valeur d'un tableau ou d'un objet qui est contenu dans un
chemin donné en utilisant un tableau en une syntaxe de tableau, par ex:
@@ -707,7 +707,7 @@ quelles options sont disponibles.
.. php:staticmethod:: extract($path, $data=null, $options=array())
- :rtype: array
+ :rtype: mixed
Set::extract utilise la syntaxe basique XPath 2.0 pour retourner les
sous-ensembles de vos données à partir d'un fin ou d'un find all. Cette
@@ -771,7 +771,7 @@ quelles options sont disponibles.
testExtract() dans ``/lib/Cake/Test/Case/Utility/SetTest.php``.
-.. php:staticmethod:: filter($var, $isArray=null)
+.. php:staticmethod:: filter($var)
:rtype: array
diff --git a/fr/core-utility-libraries/xml.rst b/fr/core-utility-libraries/xml.rst
index a9d1b7fe6e..6c1f59ce5f 100644
--- a/fr/core-utility-libraries/xml.rst
+++ b/fr/core-utility-libraries/xml.rst
@@ -21,6 +21,9 @@ cela retournera un objet SimpleXMLElement ou DOMDocument (selon votre paramètre
options - par défault SimpleXMLElement). Ci-dessous les échantillons sur la
façon d'importer des données depuis une URL::
+ //D'abord charger la Classe Utility
+ App::uses('Xml', 'Utility');
+
// Vieille méthode:
$xml = new Xml('http://bakery.cakephp.org/articles.rss');
diff --git a/fr/development/debugging.rst b/fr/development/debugging.rst
index 9ee187074c..7b2ab87441 100644
--- a/fr/development/debugging.rst
+++ b/fr/development/debugging.rst
@@ -61,7 +61,7 @@ Utiliser la Classe Debugger
Pour utiliser le debugger, assurez-vous d'abord que Configure::read('debug')
est défini à une valeur supérieure à 0.
-.. php:staticmethod:: Debugger::dump($var)
+.. php:staticmethod:: Debugger::dump($var, $depth = 3)
Dump prints out the contents of a variable. Elle affiche toutes les
propriétés et méthodes (si il y en a) de la variable fournie::
@@ -96,7 +96,10 @@ est défini à une valeur supérieure à 0.
Dans 2.1 forward, la sortie a été modifiée pour la lisibilité. Regardez
:php:func:`Debugger::exportVar()`.
-.. php:staticmethod:: Debugger::log($var, $level = 7)
+ .. versionchanged:: 2.5.0
+ Le paramètre ``depth`` a été ajouté.
+
+.. php:staticmethod:: Debugger::log($var, $level = 7, $depth = 3)
Crée un stack trace log détaillé au moment de l'invocation. La
méthode log() affiche les données identiques à celles faites par
@@ -105,6 +108,9 @@ est défini à une valeur supérieure à 0.
être ouvert en écriture par le serveur web pour que le
log() fonctionne correctement.
+ .. versionchanged:: 2.5.0
+ Le paramètre ``depth`` a été ajouté.
+
.. php:staticmethod:: Debugger::trace($options)
Retourne le stack trace courant. Chaque ligne des traces inlut la méthode
diff --git a/fr/development/dispatch-filters.rst b/fr/development/dispatch-filters.rst
index ae0596a057..a12dc5ff08 100644
--- a/fr/development/dispatch-filters.rst
+++ b/fr/development/dispatch-filters.rst
@@ -111,6 +111,23 @@ d'utiliser une façon plus avancée/rapide pour servir les thèmes les assets
de plugin ou si vous ne souhaitez pas utiliser la mise en cache intégrée
de la page entière, ou pour juste implémenter le votre.
+Si vous avez besoin de passer des paramètres ou des configurations au
+constructeur à vos classes de dispatch filter, vous pouvez le faire en
+fournissant un tableau de paramètres::
+
+ Configure::write('Dispatcher.filters', array(
+ 'MyAssetFilter' => array('service' => 'google.com')
+ ));
+
+Quand la clé filter est un nom de classe valide, la valeur peut être un tableau
+de paramètres qui sont passés au dispatch filter. Par défaut, la classe de base
+va assigner ces paramètres à la propriété ``$settings`` après les avoir
+fusionnés avec les valeurs par défaut dans la classe.
+
+.. versionchanged:: 2.5
+ Vous pouvez maintenant fournir des paramètres au constructeur pour
+ dispatcher les filtres dans 2.5.
+
Classes Filter
==============
diff --git a/fr/development/rest.rst b/fr/development/rest.rst
index 8e6e9bf572..3d296f3d49 100644
--- a/fr/development/rest.rst
+++ b/fr/development/rest.rst
@@ -206,6 +206,8 @@ devez définir *toutes* les valeurs par défaut que vous voulez utiliser::
En écrivant par dessus la ressource map par défaut, les appels futurs à
``mapResources()`` vont utiliser les nouvelles valeurs.
+.. _custom-rest-routing:
+
Routing REST Personnalisé
=========================
@@ -216,6 +218,17 @@ vous permet de définir un certain nombre d'options différentes pour une URL
donnée. Regardez la section sur :ref:`route-conditions` pour plus
d'informations.
+.. versionadded:: 2.5
+
+Vous pouvez fournir la clé ``connectOptions`` dans le tableau ``$options`` pour
+:php:meth:`Router::mapResources()` pour fournir un paramètre personnalisé
+utilisé par :php:meth:`Router::connect()`::
+
+ Router::mapResources('books', array(
+ 'connectOptions' => array(
+ 'routeClass' => 'ApiRoute',
+ )
+ ));
.. meta::
:title lang=fr: REST
diff --git a/fr/development/testing.rst b/fr/development/testing.rst
index f02ce6ba4b..aeea608bcf 100755
--- a/fr/development/testing.rst
+++ b/fr/development/testing.rst
@@ -20,10 +20,12 @@ ce qui suit::
pear upgrade PEAR
pear config-set auto_discover 1
- pear install pear.phpunit.de/PHPUnit
+ pear install pear.phpunit.de/PHPUnit-3.7.32
.. note::
+ PHPUnit 4 n'est pas compatible avec les Tests Unitaires de CakePHP.
+
Selon la configuration de votre système, vous devrez lancer les commandes
précédentes avec ``sudo``.
@@ -370,7 +372,9 @@ Crée un fichier nommé ``ArticleFixture.php`` dans votre répertoire
class ArticleFixture extends CakeTestFixture {
- /* Optionel. Définir cette propriété pour charger les fixtures dans une source de données de test différente */
+ // Optionel
+ // Définir cette propriété pour charger les fixtures dans une source
+ // de données de test différente
public $useDbConfig = 'test';
public $fields = array(
'id' => array('type' => 'integer', 'key' => 'primary'),
@@ -582,6 +586,22 @@ en utilisant :php:meth:`CakeTestCase::loadFixtures()`::
}
}
+Depuis 2.5.0, vous pouvez charger les fixtures dans les sous-répertoires.
+Utiliser plusieurs répertoires peut faciliter l'organisation de vos fixtures si
+vous avez une application plus grande. Pour charger les fixtures dans les
+sous-répertoires, incluez simplement le nom du sous-répertoire dans le nom de
+la fixture::
+
+ class ArticleTest extends CakeTestCase {
+ public $fixtures = array('app.blog/article', 'app.blog/comment');
+ }
+
+Dans l'exemple ci-dessus, les deux fixtures seront chargés à partir de
+``App/Test/Fixture/blog/``.
+
+.. versionchanged:: 2.5
+ Depuis 2.5.0 vous pouvez charger les fixtures dans des sous-répertoires.
+
Tester les Models
=================
@@ -706,6 +726,8 @@ tester les méthodes comme :php:meth:`~Controller::redirect()`.
Disons que vous avez un controller typique Articles, et son model
correspondant. Le code du controller ressemble à ceci::
+ App::uses('AppController', 'Controller');
+
class ArticlesController extends AppController {
public $helpers = array('Form', 'Html');
@@ -789,6 +811,8 @@ redirection. La raison pour cela est que ``redirect()`` est mocked dans les
tests, et n'échappe pas comme à la normale. Et à la place de votre code
existant, il va continuer de lancer le code suivant le redirect. Par exemple::
+ App::uses('AppController', 'Controller');
+
class ArticlesController extends AppController {
public function add() {
if ($this->request->is('post')) {
@@ -804,6 +828,8 @@ Quand vous testez le code ci-dessus, vous allez toujours lancer
``// plus de code`` même si le redirect est atteint. A la place, vous
devriez écrire le code comme ceci::
+ App::uses('AppController', 'Controller');
+
class ArticlesController extends AppController {
public function add() {
if ($this->request->is('post')) {
@@ -1070,7 +1096,7 @@ dans notre component. Nous créons le fichier
App::uses('PagematronComponent', 'Controller/Component');
// Un faux controller pour tester against
- class TestPagematronController extends Controller {
+ class PagematronControllerTest extends Controller {
public $paginate = null;
}
@@ -1085,7 +1111,7 @@ dans notre component. Nous créons le fichier
$this->PagematronComponent = new PagematronComponent($Collection);
$CakeRequest = new CakeRequest();
$CakeResponse = new CakeResponse();
- $this->Controller = new TestPagematronController($CakeRequest, $CakeResponse);
+ $this->Controller = new PagematronControllerTest($CakeRequest, $CakeResponse);
$this->PagematronComponent->startup($this->Controller);
}
diff --git a/fr/getting-started/cakephp-folder-structure.rst b/fr/getting-started/cakephp-folder-structure.rst
index ec0845f9f7..366180732c 100755
--- a/fr/getting-started/cakephp-folder-structure.rst
+++ b/fr/getting-started/cakephp-folder-structure.rst
@@ -27,9 +27,9 @@ Vous remarquerez trois dossiers principaux :
Le dossier App
==============
-Le répertoire app de CakePHP est l'endroit où vous réaliserez la majorité
-du développement de votre application. Regardons de plus près le contenu de
-ce répertoire.
+Le répertoire *app* de CakePHP est l'endroit où vous réaliserez la majorité
+du développement de votre application. Regardons de plus près les dossier à
+l'intérieur de *app*.
Config
Contient les (quelques) fichiers de configuration utilisés par CakePHP.
@@ -44,7 +44,7 @@ Console
Controller
Contient vos Controllers et leurs Components.
Lib
- Contient les librairies internes qui ne proviennent pas de librairies
+ Contient les librairies qui ne proviennent pas de librairies
externes. Cela vous permet de séparer les librairies internes de votre
organisme des librairies externes.
Locale
@@ -75,7 +75,7 @@ Vendor
Toute classe ou librairie tierce doit être mise ici, de sorte qu'il
sera facile d'y accéder par la fonction App::import('vendor','name'). Les
observateurs avisés noteront que cela semble redondant avec le répertoire
- "vendors" à la racine de l'arborescence. Nous aborderons les différences
+ *vendors* à la racine de l'arborescence. Nous aborderons les différences
entre les deux lorsque nous discuterons de la gestion multi-applications
et des configurations systèmes plus complexes.
diff --git a/fr/getting-started/cakephp-structure.rst b/fr/getting-started/cakephp-structure.rst
index e7eff903bb..5e44abb368 100644
--- a/fr/getting-started/cakephp-structure.rst
+++ b/fr/getting-started/cakephp-structure.rst
@@ -82,8 +82,7 @@ enregistrements issus de sources différentes : plutôt que d'être limité à d
jointures SQL, les Sources de Données vous permettent de dire à votre model
LDAP qu'il est associé à plusieurs événements iCal.
-Tout comme les controllers, les models sont également caractérisés par des
-fonctions de rappel (callbacks) :
+Tout comme les controllers, les models ont des callbacks:
- beforeFind()
- afterFind()
diff --git a/fr/index.rst b/fr/index.rst
index e3e9d2faa8..5e1be2b51d 100644
--- a/fr/index.rst
+++ b/fr/index.rst
@@ -45,14 +45,14 @@ plus sur les :doc:`/controllers`.
Views (vues)
------------
-Les vues (views) sont la représentation graphique des données dans CakePHP.
+Les views (vues) sont la représentation graphique des données dans CakePHP.
Elles permettent de convertir les données extraites de models, dans le format
de sortie demandé par le client. En savoir plus sur les :doc:`/views`.
Models (modèles)
----------------
-Les modèles (Models) sont le coeur de votre application, ils gèrent la
+Les models (Modèles) sont le coeur de votre application. Ils gèrent la
validation, le stockage et la récupération de vos données. En savoir plus
sur les :doc:`/models`.
diff --git a/fr/installation/advanced-installation.rst b/fr/installation/advanced-installation.rst
index 66fbb90273..7f63ac5268 100644
--- a/fr/installation/advanced-installation.rst
+++ b/fr/installation/advanced-installation.rst
@@ -43,7 +43,7 @@ application CakePHP ressemblerait à ce qui suit::
}
],
"require": {
- "pear-cakephp/cakephp": ">=2.4.0"
+ "cakephp/cakephp": ">=2.4.9"
},
"config": {
"vendor-dir": "Vendor/"
@@ -81,7 +81,7 @@ relatif::
define(
'CAKE_CORE_INCLUDE_PATH',
- ROOT . DS . APP_DIR . '/Vendor/pear-pear.cakephp.org/CakePHP'
+ ROOT . '/Vendor/pear-pear.cakephp.org/CakePHP'
);
.. note::
diff --git a/fr/installation/url-rewriting.rst b/fr/installation/url-rewriting.rst
index 766730dbd6..2a74604958 100644
--- a/fr/installation/url-rewriting.rst
+++ b/fr/installation/url-rewriting.rst
@@ -39,9 +39,8 @@ http://wiki.apache.org/httpd/DistrosDefaultLayout pour plus d'informations.
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
- Dans la plupart des systèmes, ceux-ci vont être commentés (en étant
- précédé par un #) par défaut, donc vous aurez juste besoin de retirer
- les symboles # du début.
+ Dans la plupart des systèmes, ceux-ci vont être commentés donc vous aurez
+ juste besoin de retirer les symboles # en début de ligne.
Après que vous avez fait des changements, re-démarrez Apache pour être sûr
que les paramètres soient actifs.
diff --git a/fr/models.rst b/fr/models.rst
index dc25b40084..8dfac99d5d 100644
--- a/fr/models.rst
+++ b/fr/models.rst
@@ -2,7 +2,7 @@ Models (Modèles)
################
Les Models sont les classes qui représentent la couche de logique dans votre
-application. Cela signifie qu'ils sont responsables de la gestion de presque
+application. Ils sont responsables de la gestion de presque
tout ce qui concerne les données, leur validité, les interactions et
l'évolution du flux d'informations dans votre domaine de travail.
@@ -11,11 +11,10 @@ utilisées dans les applications CakePHP pour l'accès aux données, plus
spécifiquement elles représentent une table de la base de données, mais elles
ne sont pas limitées à cela et peuvent être utilisées pour accéder à tout ce
qui manipule des données comme des fichiers, des services web externes, des
-évènements iCal ou des lignes dans un fichier CSV.
+évènements iCal.
Un model peut être associé avec d'autres models. Par exemple, une Recette
-peut être associé avec l'Auteur de la recette ainsi qu'à l'Ingredient dans
-la recette.
+peut être associée avec l'Auteur de la recette ainsi qu'à un Ingredient.
Cette section vous expliquera quelles fonctionnalités du model peuvent
être automatisées, comment outrepasser ces fonctionnalités, et quelles
@@ -27,7 +26,7 @@ Comprendre les Models
=====================
Un Model représente votre model de données. En programmation orientée objet, un model
-est un objet qui représente une "chose", comme une voiture, une
+est un objet qui représente une chose, comme une voiture, une
personne ou une maison. Un blog, par exemple, peut avoir plusieurs posts et
chaque post peut avoir plusieurs commentaires. Blog, Post et Commentaire sont
tous des exemples de models, chacun étant associé avec un autre.
@@ -46,10 +45,9 @@ classe Model de CakePHP, grâce à la magie de l'héritage. Le model Ingredient
étend le model de l'application AppModel, lequel étend la classe Model interne
de CakePHP. C'est cette classe Model du cœur qui fournit les fonctionnalités à
l'intérieur de votre model Ingredient. ``App::uses('AppModel', 'Model')``
-s'assure que le model est chargé sans effort pour chaque utilisation de
-l'instance.
+s'assure que le model est chargé sans effort quand cela est nécessaire.
-La classe intermédiaire AppModel est vide et si vous n'avez pas créé la vôtre,
+La classe intermédiaire AppModel est vide. Si vous n'avez pas créé la vôtre,
elle provient du répertoire du coeur de cakePHP. Ecraser AppModel vous permet
de définir des fonctionnalités qui doivent être rendues disponibles pour tous
les models de votre application. Pour faire cela, vous avez besoin de créer
@@ -61,23 +59,23 @@ fichier sera automatiquement créé pour vous.
Voir aussi :doc:`Behaviors ` pour plus d'informations sur la
façon d'appliquer la même logique pour de multiples models.
-Retournons à notre model Ingredient, pour que cela fonctionne, créez le
+Revenons-en à notre model Ingredient. Pour que cela fonctionne, créez le
fichier PHP dans le repertoire ``/app/Model/``. Par convention, il devra avoir
-le même nom que la classe; pour cet exemple ``Ingredient.php``.
+le même nom que la classe ce qui pour l'exemple sera ``Ingredient.php``.
.. note::
CakePHP créera dynamiquement un objet model pour vous si il ne peut
pas trouver un fichier correspondant dans /app/Model. Cela veut également
- dire que si votre fichier de model n'est pas nommé correctement (ex :
- ingredient.php ou ingredients.php) CakePHP utilisera une instance de
- AppModel, plutôt que votre fichier de model "manquant" (d'un point de
- vue CakePHP). Si vous essayez d'utiliser une méthode que vous avez définie
- dans votre model ou dans un comportement attaché à votre model et que
- vous obtenez des erreurs SQL qui indiquent le nom de la méthode que vous
- appelez, c'est une indication certaine que CakePHP ne peut pas trouver
- votre model et que vous devez, soit vérifier les noms de fichier, soit
- nettoyer les fichiers temporaires ou les deux.
+ dire que si votre fichier de model n'est pas nommé correctement (par ex si
+ il est nommé ingredient.php ou Ingredients.php plutôt que Ingredient.php)
+ CakePHP utilisera une instance de AppModel, plutôt que votre fichier de
+ model (qui sera manquant pour CakePHP). Si vous essayez d'utiliser une
+ méthode que vous avez définie dans votre model ou dans un comportement
+ attaché à votre model et que vous obtenez des erreurs SQL qui indiquent le
+ nom de la méthode que vous appelez, c'est une indication certaine que
+ CakePHP ne peut pas trouver votre model et que vous devez vérifier
+ les noms de fichier, nettoyer les fichiers temporaires ou les deux.
.. note::
diff --git a/fr/models/behaviors.rst b/fr/models/behaviors.rst
index f1a01febb6..7d4a843744 100644
--- a/fr/models/behaviors.rst
+++ b/fr/models/behaviors.rst
@@ -271,7 +271,7 @@ attachés et d'augmenter les paramètres ou de les accoler dans un behavior
supplémentaire.
Tous les callbacks des behaviors sont lancés **avant** les callbacks du
-model/behavior:
+model:
- ``beforeFind``
- ``afterFind``
diff --git a/fr/models/data-validation.rst b/fr/models/data-validation.rst
index 3729064848..fc66c4815f 100644
--- a/fr/models/data-validation.rst
+++ b/fr/models/data-validation.rst
@@ -1,4 +1,4 @@
-Validation des Donnnées
+Validation des Données
#######################
La validation des données est une partie importante de toute application,
@@ -910,7 +910,7 @@ complète de toutes les règles, illustrées par des exemples d'utilisation.
.. versionadded:: 2.3
Cette méthode a été ajoutée dans 2.3
-.. php:staticmethod:: inList(string $check, array $list, $strict = true)
+.. php:staticmethod:: inList(string $check, array $list, boolean $caseInsensitive = false)
Cette règle s'assurera que la valeur est dans un ensemble donné. Elle
nécessite un tableau des valeurs. Le champ est valide si sa valeur
@@ -927,6 +927,10 @@ complète de toutes les règles, illustrées par des exemples d'utilisation.
)
);
+ La comparaison est non sensible à la casse par défaut. Vous pouvez définir
+ ``$caseInsensitive`` à true si vous avez besoin d'une comparaison sensible
+ à la casse.
+
.. php:staticmethod:: ip(string $check, string $type = 'both')
Cette règle s'assurera qu'une adresse IPv4 ou IPv6 valide a été soumise.
@@ -978,11 +982,16 @@ complète de toutes les règles, illustrées par des exemples d'utilisation.
de la donnée". Faites attention car elle pourrait être plus grande
que le nombre de caractères en manipulant des caractères non-ASCII.
-.. php:staticmethod:: mimeType(mixed $check, array $mimeTypes)
+.. php:staticmethod:: mimeType(mixed $check, array|string $mimeTypes)
.. versionadded:: 2.2
- Cette règle vérifie la validité d'un mimeType.
+ Cette règle vérifie la validité d'un mimeType. La comparaison est sensible à
+ la casse.
+
+ .. versionchanged:: 2.5
+
+ Depuis 2.5 ``$mimeTypes`` peut être une chaîne regex.
::
@@ -991,6 +1000,10 @@ complète de toutes les règles, illustrées par des exemples d'utilisation.
'rule' => array('mimeType', array('image/gif')),
'message' => 'Invalid mime type.'
),
+ 'logo' => array(
+ 'rule' => array('mimeType', '#image/.+#'),
+ 'message' => 'Invalid mime type.'
+ ),
);
.. php:staticmethod:: minLength(string $check, integer $min)
@@ -1025,7 +1038,7 @@ complète de toutes les règles, illustrées par des exemples d'utilisation.
)
);
-.. php:staticmethod:: multiple(mixed $check, mixed $options = array())
+.. php:staticmethod:: multiple(mixed $check, mixed $options = array(), boolean $caseInsensitive = false)
Utilisez cette règle pour valider un champ select multiple. Elle
accepte les paramètres "in", "max" et "min".
@@ -1043,6 +1056,10 @@ complète de toutes les règles, illustrées par des exemples d'utilisation.
)
);
+ La comparaison est sensible à la casse par défaut. Vous pouvez définir
+ ``$caseInsensitive`` à true si vous avez besoin d'une comparaison insensible
+ à la casse.
+
.. php:staticmethod:: notEmpty(mixed $check)
La règle de base pour s'assurer qu'un champ n'est pas vide.::
diff --git a/fr/models/retrieving-your-data.rst b/fr/models/retrieving-your-data.rst
index 94f98562ee..52d848f581 100644
--- a/fr/models/retrieving-your-data.rst
+++ b/fr/models/retrieving-your-data.rst
@@ -703,8 +703,8 @@ Les fonctions findBy() retournent des résultats comme ``find('first')``.
``query(string $query)``
Les appels SQL que vous ne pouvez pas ou ne voulez pas faire grâce aux autres
-méthodes de model (attention, il y a très peu de circonstances où cela se
-vérifie), peuvent être exécutés en utilisant la méthode ``query()``.
+méthodes de model peuvent être exécutés en utilisant la méthode ``query()``
+(bien qu'il y ait très peu de circonstances où cela se vérifie).
Si vous utilisez cette méthode, assurez-vous d'échapper correctement tous les
paramètres en utilisant la méthode ``value()`` sur le driver de la base de
@@ -789,7 +789,7 @@ ce qui retourne::
Retourne la valeur d'un champ unique, spécifié par ``$name``, du premier
enregistrement correspondant aux $conditions ordonnées par $order. Si
-aucune condition n'est passée et que l'id du model est fixé, cela
+aucune condition n'est passée et que l'id du model est fixé, la fonction
retournera la valeur du champ pour le résultat de l'enregistrement actuel.
Si aucun enregistrement correspondant n'est trouvé cela retournera false.
@@ -854,6 +854,12 @@ convenablement chaque partie de la requête. Utiliser une syntaxe en tableau
permet aussi à CakePHP de sécuriser vos requêtes contre toute attaque
d'injection SQL.
+.. warning::
+
+ CakePHP échappe seulement les valeurs de tableau. Vous **ne** devriez
+ **jamais** mettre les données d'utilisateur dans les clés. Faire ceci vous
+ rendra vulnérable aux injections SQL.
+
Dans sa forme la plus simple, une requête basée sur un tableau ressemble à
ceci::
@@ -861,9 +867,9 @@ ceci::
// Exemple d'utilisation avec un model:
$this->Post->find('first', array('conditions' => $conditions));
-La structure ici est assez significative : Tous les posts dont le
-titre à pour valeur « Ceci est un post » sont cherchés. Nous aurions
-pu uniquement utiliser « titre » comme nom de champ, mais lorsque l'on
+La structure ici est assez significative : elle va trouver tous les posts où le
+titre à pour valeur « This is a post » et où l'id de l'auteur est égal à 1. Nous
+aurions pu uniquement utiliser « title » comme nom de champ, mais lorsque l'on
construit des requêtes, il vaut mieux toujours spécifier le nom du model.
Cela améliore la clarté du code, et évite des collisions futures, dans
le cas où vous devriez changer votre schéma.
diff --git a/fr/models/virtual-fields.rst b/fr/models/virtual-fields.rst
index 07e1a21e98..a66db65ed5 100644
--- a/fr/models/virtual-fields.rst
+++ b/fr/models/virtual-fields.rst
@@ -22,7 +22,7 @@ serait::
et avec PostgreSQL::
public $virtualFields = array(
- 'nom' => 'User.prenom || \' \' || User.nom_famille'
+ 'nom' => 'User.prenom || ' ' || User.nom_famille'
);
Par conséquent, avec les opérations find, les résultats de l'User
diff --git a/fr/plugins.rst b/fr/plugins.rst
index 3359350984..01f0bb8aab 100755
--- a/fr/plugins.rst
+++ b/fr/plugins.rst
@@ -61,8 +61,8 @@ ce qui aurait chargé seulement ces trois plugins, et pas le reste.
Au final, vous pouvez aussi spécifier un ensemble de valeurs dans defaults pour
loadAll qui s'applique à chaque plugin qui n'a pas de configuration spécifique.
-Chargez le fichier bootstrap à partir de tous les plugins, et les routes à
-partir du plugin Blog::
+Chargez le fichier bootstrap à partir de tous les plugins, et aussi les routes
+du plugin Blog::
CakePlugin::loadAll(array(
array('bootstrap' => true),
@@ -213,6 +213,14 @@ Merci de vous référer au chapitre
:doc:`/console-and-shells/code-generation-with-bake` si vous avez le moindre
problème avec l'utilisation de la ligne de commande.
+.. warning::
+
+ Les Plugins ne fonctionnent pas en namespace pour séparer le code.
+ A cause du manque de namespaces de PHP dans les versions plus vieilles, vous
+ ne pouvez pas avoir la même classe ou le même nom de fichier dans vos
+ plugins. Même si il s'agit de deux plugins différents. Donc utilisez des
+ classes et des noms de fichier uniques, en préfixant si possible la classe
+ et le nom de fichier par le nom du plugin.
Controllers du Plugin
=====================
diff --git a/fr/tutorials-and-examples/blog-auth-example/auth.rst b/fr/tutorials-and-examples/blog-auth-example/auth.rst
index 479d0cc584..1377feee5c 100644
--- a/fr/tutorials-and-examples/blog-auth-example/auth.rst
+++ b/fr/tutorials-and-examples/blog-auth-example/auth.rst
@@ -33,6 +33,8 @@ La prochaine étape est de créer notre model User, qui a la
responsablilité de trouver, sauvegarder et valider toute donnée d'user::
// app/Model/User.php
+ App::uses('AppModel', 'Model');
+
class User extends AppModel {
public $name = 'User';
public $validate = array(
@@ -224,7 +226,10 @@ Le hash du mot de passe n'est pas encore fait, ouvrez votre fichier de model
``app/Model/User.php`` et ajoutez ce qui suit::
// app/Model/User.php
+
+ App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
+
class User extends AppModel {
// ...
@@ -232,7 +237,9 @@ Le hash du mot de passe n'est pas encore fait, ouvrez votre fichier de model
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher();
- $this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']);
+ $this->data[$this->alias]['password'] = $passwordHasher->hash(
+ $this->data[$this->alias]['password']
+ );
}
return true;
}
@@ -245,16 +252,20 @@ juste un fichier template de vue pour la fonction de connexion:
.. code-block:: php
+ //app/View/Users/login.ctp
+
Vous pouvez maintenant inscrire un nouvel user en rentrant l'URL
@@ -383,7 +394,7 @@ Laissons la fonction s'exécuter::
// app/Model/Post.php
public function isOwnedBy($post, $user) {
- return $this->field('id', array('id' => $post, 'user_id' => $user)) === $post;
+ return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false;
}
diff --git a/fr/tutorials-and-examples/blog/part-two.rst b/fr/tutorials-and-examples/blog/part-two.rst
index 66c2ad3881..743d371982 100755
--- a/fr/tutorials-and-examples/blog/part-two.rst
+++ b/fr/tutorials-and-examples/blog/part-two.rst
@@ -26,8 +26,8 @@ de la base de données.
CakePHP créera dynamiquement un objet model pour vous, s'il ne trouve
pas le fichier correspondant dans /app/Model. Cela veut aussi dire que
si vous n'avez pas nommé correctement votre fichier (par ex. post.php ou
- posts.php). CakePHP ne reconnaîtra pas votre configuration et utilisera
- ses objets model par défaut.
+ posts.php au lieu de Post.php), CakePHP ne reconnaîtra pas votre
+ configuration et utilisera ses objets model par défaut.
Pour plus d'informations sur les models, comme les préfixes des tables,
les callbacks, et la validation, consultez le chapitre :doc:`/models` du
@@ -52,9 +52,9 @@ de base ::
Maintenant, ajoutons une action à notre controller. Les actions représentent
souvent une simple fonction ou une interface dans une application. Par exemple,
quand les utilisateurs requêtent www.exemple.com/posts/index (qui est
-également la même chose que www.exemple.com/posts/), ils pourraient s'attendre
-à voir une liste de posts. Le code pour cette action devrait ressembler à
-quelque chose comme ça ::
+la même chose que www.exemple.com/posts/), ils pourraient s'attendre à voir une
+liste de posts. Le code pour cette action devrait ressembler à quelque chose
+comme ça ::
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
@@ -65,7 +65,7 @@ quelque chose comme ça ::
}
En définissant la fonction ``index()`` dans notre PostsController, les
-utilisateurs peuvent maintenant accéder à cette logique en demandant
+utilisateurs peuvent accéder à cette logique en demandant
www.exemple.com/posts/index. De la même façon, si nous devions définir une
fonction appelée ``foobar()``, les utilisateurs pourrait y accéder en demandant
www.exemple.com/posts/foobar.
@@ -101,16 +101,16 @@ qui s'intègrent au sein d'un layout applicatif. Pour la plupart des
applications, elles sont un mélange de HTML et PHP, mais les vues peuvent aussi
être constituées de XML, CSV ou même de données binaires.
-Les Layouts sont du code de présentation, encapsulé autour d'une vue,
-ils peuvent être définis et interchangés, mais pour le moment,
-utilisons juste celui par défaut.
+Un Layout est un code de présentation, encapsulé autour d'une vue. Ils peuvent
+être définis et interchangés, mais pour le moment, utilisons juste celui par
+défaut.
Vous souvenez-vous, dans la dernière section, comment nous avions assigné
la variable 'posts' à la vue en utilisant la méthode ``set()`` ?
Cela devrait transmettre les données à la vue qui ressemblerait à quelque
chose comme cela ::
- // print_r($posts) sort:
+ // print_r($posts) affiche:
Array
(
@@ -155,6 +155,8 @@ un dossier appelé 'Posts' dans ce cas). Pour mettre en forme les données de
ces posts dans un joli tableau, le code de notre vue devrait ressembler à
quelque chose comme cela ::
+.. code-block:: php
+
Blog posts
@@ -180,8 +182,6 @@ quelque chose comme cela ::
-Bien entendu, cela donnera quelque chose de simple.
-
Vous avez sans doute remarqué l'utilisation d'un objet appelé ``$this->Html``.
C'est une instance de la classe CakePHP :php:class:`HtmlHelper`.
CakePHP est livré avec un ensemble de "helpers" (des assistants) pour les vues,
@@ -210,6 +210,7 @@ quelque chose s'est mal passé, soit en fait vous aviez déjà défini l'action,
auquel cas vous êtes vraiment sournois ! Sinon, nous allons la créer sans plus
tarder dans le Controller Posts ::
+ // File: /app/Controller/PostsController.php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
@@ -342,7 +343,7 @@ nous trouvons la fonction :php:func:`SessionHelper::flash` qui permet
d'afficher et de nettoyer la variable correspondante. La méthode
:php:meth:`Controller::redirect` du controller permet de rediriger vers une
autre URL. Le paramètre ``array('action' => 'index')`` sera traduit vers l'URL
-/posts, c'est à dire l'action "index" du controller "Posts" (PostsController).
+/posts (dans notre cas l'action "index" du controller "Posts").
Vous pouvez vous référer à la fonction :php:func:`Router::url()` dans
`l'API `_ pour voir les différents formats d'URL
acceptés dans les différentes fonctions de CakePHP.
@@ -351,8 +352,8 @@ L'appel de la méthode ``save()`` vérifiera les erreurs de validation et
interrompra l'enregistrement si une erreur survient. Nous verrons
la façon dont les erreurs sont traitées dans les sections suivantes.
-La raison pour laquelle nous appelons la méthode ``create()`` en premier est
-pour réinitialiser l'état du model pour sauvegarder les nouvelles informations.
+Nous appelons la méthode ``create()`` en premier afin
+de réinitialiser l'état du model pour sauvegarder les nouvelles informations.
Cela ne crée pas réellement un enregistrement dans la base de données mais
réinitialise Model::$id et définit Model::$data en se basant sur le champ par
défaut dans votre base de données.
@@ -383,7 +384,7 @@ Voici le code de notre vue "add" (ajout)
echo $this->Form->end('Sauvegarder le post');
?>
-Nous utilisons ici le :php:class:`FormHelper` pour générer la balise
+Nous utilisons le :php:class:`FormHelper` pour générer la balise
d'ouverture d'une formulaire HTML. Voici le code HTML généré par
``$this->Form->create()`` ::
diff --git a/fr/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.rst b/fr/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.rst
index 4cd353a5ad..aba9f37711 100644
--- a/fr/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.rst
+++ b/fr/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.rst
@@ -384,7 +384,7 @@ configuration de ``AuthComponent``. L'``AuthComponent`` doit être renseigné su
l'existence de ce nœud root, de sorte que lors des contrôles de l'ACL, le
component puisse utiliser le bon chemin de nœud lors de la recherche
controllers/actions. Dans l'``AppController``, assurez vous que le tableau
-``$components`` contient l'``actionPath`` défini avant.
+``$components`` contient l'``actionPath`` défini avant::
class AppController extends Controller {
public $components = array(
@@ -399,7 +399,6 @@ controllers/actions. Dans l'``AppController``, assurez vous que le tableau
Continuez à :doc:`part-two` pour continuer le tutoriel.
-
.. meta::
:title lang=fr: Application Simple contrôlée par Acl
:keywords lang=fr: librairies du coeur,incrémentation auto,programmation orientée objet,schéma de base de données,requêtes sql,classe php,version stable,génération de code,serveur de base de données,configuration du serveur,reins,contrôle d'accès,shells,mvc,authentification,serveur web,cakephp,serveurs,checkout,apache
diff --git a/fr/views.rst b/fr/views.rst
index a7d5ec850d..19041ada27 100644
--- a/fr/views.rst
+++ b/fr/views.rst
@@ -14,11 +14,11 @@ rendu les plus communs:
:doc:`views/json-and-xml-views`.
- Pour servir des fichiers protégés, ou générer des fichiers dynamiquement,
vous pouvez utiliser :ref:`cake-response-file`.
-- Pour créer des vues multiples par thème, vous pouvez utliser
+- Pour créer plusieurs vues pour un thème, vous pouvez utiliser
:doc:`views/themes`.
-Templates de Views
-==================
+Templates de Vues
+=================
La couche view de CakePHP c'est la façon dont vous parlez à vos utilisateurs.
La plupart du temps, vos vues afficheront des documents (X)HTML pour les
@@ -26,17 +26,18 @@ navigateurs, mais vous pourriez aussi avoir besoin de fournir des données AMF
à un objet Flash, répondre à une application distante via SOAP ou produire un
fichier CSV pour un utilisateur.
-Les fichiers de vues de CakePHP sont écrits en pur PHP et ont comme extension
-par défaut .ctp (Cakephp TemPlate). Ces fichiers contiennent toute la logique
+Les fichiers de vue de CakePHP sont écrits en pur PHP et ont par défaut .ctp
+(Cakephp TemPlate) comme extension. Ces fichiers contiennent toute la logique
de présentation nécessaire à l'organisation des données reçues du controller,
dans un format qui satisfasse l'audience que vous recherchez. Si vous préférez
utiliser un langage de template comme Twig, ou Smarty, une sous-classe de View
fera le pont entre votre language de template et CakePHP.
-Les fichiers de vues sont stockées dans ``/app/View/``, dans un dossier portant
-le nom du controller qui utilise ces fichiers et le nom de la vue
-correspondante. Par exemple, l'action "view()" du controller Produits devrait
-normalement se trouver dans ``/app/View/Products/view.ctp``.
+Un fichier de vue est stocké dans ``/app/View/``, dans un sous-dossier
+portant le nom du controller qui utilise ce fichier. Il a un nom de fichier
+correspondant à son action. Par exemple, le fichier de vue pour l'action
+"view()" du controller Products devra normalement se trouver dans
+``/app/View/Products/view.ctp``.
La couche vue de CakePHP peut être constituée d'un certain nombre de parties
différentes. Chaque partie a différent usages qui seront présentés dans ce
@@ -57,8 +58,8 @@ chapitre :
.. _extending-views:
-Views étendues
---------------
+Vues étendues
+-------------
.. versionadded:: 2.1
@@ -135,7 +136,7 @@ vue parente va récupérer le contenu de la vue précédente en tant que bloc
.. _view-blocks:
-Utiliser les blocs de vues
+Utiliser les Blocs de Vues
==========================
.. versionadded:: 2.1
@@ -212,7 +213,7 @@ enfant, le contenu par défaut avec la balise ``
`` sera écarté.
utilisé par CakePHP en interne pour étendre les vues, et le contenu des
vues dans le layout.
-Afficher les blocs
+Afficher les Blocs
------------------
.. versionadded:: 2.1
@@ -249,7 +250,7 @@ une valeur par défaut en utilisant le 2ème argument::
.. versionchanged:: 2.3
L'argument ``$default`` a été ajouté dans 2.3.
-Utiliser des blocks pour les fichiers de script et les CSS
+Utiliser des Blocks pour les Fichiers de Script et les CSS
----------------------------------------------------------
.. versionadded:: 2.1
@@ -310,7 +311,7 @@ ressembler::
-
+ fetch('title'); ?>
echo $this->fetch('meta');
@@ -526,7 +527,7 @@ en reprenant l'exemple du Post::
Et ensuite dans l'element, nous pouvons accéder au model des posts paginés.
Pour obtenir les cinq derniers posts dans une liste ordonnée, nous ferions
-ce qui suit::
+ce qui suit:
.. code-block:: php
@@ -672,9 +673,22 @@ Pour appeler toute méthode de view, utilisez ``$this->method()``
Ensuite dans votre fichier de layout la variable ``$activeMenuButton``
sera disponible et contiendra la valeur 'posts'.
+.. php:method:: get(string $var, $default = null)
+
+ Récupère la valeur d'une viewVar avec le nom de ``$var``.
+
+ Depuis 2.5 vous pouvez fournir une valeur par défaut dans le cas où la
+ variable n'est pas déjà définie.
+
+ .. versionchanged:: 2.5
+ L'argument ``$default`` a été ajouté dans 2.5.
+
.. php:method:: getVar(string $var)
- Récupère la valeur de viewVar avec le nom $var.
+ Récupère la valeur de viewVar avec le nom ``$var``.
+
+ .. deprecated:: 2.3
+ Utilisez :php:meth:`View::get()` à la place.
.. php:method:: getVars()
@@ -747,7 +761,7 @@ Pour appeler toute méthode de view, utilisez ``$this->method()``
.. php:method:: startIfEmpty($name)
- Commence un block sous conditions, seulement si il est vide. Tout le
+ Commence un block si il est vide. Tout le
contenu dans le block va être capturé et écarté si le block est déjà
défini.
diff --git a/ja/console-and-shells.rst b/ja/console-and-shells.rst
index 29fb1e31c1..c2fcfcff2e 100644
--- a/ja/console-and-shells.rst
+++ b/ja/console-and-shells.rst
@@ -1,77 +1,77 @@
-Console and Shells
+コンソールとシェル
##################
-CakePHP features not only a web framework but also a console framework
-for creating console applications. Console applications are ideal for handling
-a variety of background tasks such as maintenance, and completing work outside
-of the request-response cycle. CakePHP console applications allow you
-to reuse your application classes from the command line.
+CakePHPはWebのフレームワークとしてだけではなく、コンソールアプリケーション
+を開発するためのコンソールフレームワークとしての機能を合わせ持っています。
+コンソールアプリケーションはメンテナンスといった様々なバックグラウンド
+タスクを行ったり、リクエスト-レスポンスのサイクルの外側で何かを実行する
+ための仕組みです。CakePHPのコンソールアプリケーションでは、コマンドライン
+からあなたが作成したアプリケーションクラスを再利用できます。
-CakePHP comes with a number of console applications out of the box.
-Some of these applications are used in concert with other CakePHP
-features (like ACL or i18n), and others are for general use in
-getting you working faster.
+CakePHPには元々たくさんのコンソールアプリケーションが備わっています。
+これらの中には(ACLやi18nのように)他のCakePHPの機能と組合せて使うものも
+あれば、仕事をより早く片付けるための、より一般的なものもあります。
-The CakePHP console
+CakePHPのコンソール
===================
-This section provides an introduction into CakePHP at the
-command-line. If you’ve ever needed access to your CakePHP MVC
-classes in a cron job or other command-line script, this section is
-for you.
+このセクションでは、コマンドラインにおけるCakePHPのご紹介をします。もし
+過去にcronジョブやコマンドライン・スクリプトから自分のCakePHPのMVCクラスに
+アクセスできたら便利なのにと思ったことがあれば、このセクションがその道
+しるべとなるでしょう。
-PHP provides a CLI client that makes interfacing with your
-file system and applications much smoother. The CakePHP console
-provides a framework for creating shell scripts. The Console uses a
-dispatcher-type setup to load a shell or task, and hand it its
-parameters.
+PHPではファイルシステムやアプリケーションをより柔軟に使えるように、
+これらへのインターフェースを備えたCLIクライアント機能を提供しています。
+CakePHPコンソールでは、シェルスクリプト作成のためのフレームワークを提供
+しています。コンソールではディスパッチタイプのセットアップを使って
+シェルやタスクをロードし、それらへパラメータを渡します。
.. note::
- A command-line (CLI) build of PHP must be available on the system
- if you plan to use the Console.
+ コンソール機能を使う場合は、コマンドライン版(CLI)としてビルドされた
+ PHPがインストールされている必要があります。
-Before we get into specifics, let’s make sure we can run the
-CakePHP Console. First, you’ll need to bring up a system shell. The
-examples shown in this section will be in bash, but the CakePHP
-Console is Windows-compatible as well. Let’s execute the Console
-program from bash. This example assumes that the user is currently
-logged into a bash prompt and is currently at the root of a CakePHP
-application.
+詳細に入る前に、CakePHPコンソールがちゃんと動くことを確認しておきましょう。
+まずはシステムのシェルを起動する必要があります。このセクションで示している
+例はbashのものですが、ConsoleコンソールはWindows互換でもあります。それでは
+bashからコンソールプログラムを動かしてみましょう。これの例ではユーザがすでに
+bashプロンプトにログインしており、CakePHPアプリケーションのルートにいること
+を想定しています。
-CakePHP applications contain a ``Console`` directory that contains
-all the shells and tasks for an application. It also comes with an
-executable::
+CakePHPアプリケーションの中には ``Console`` というディレクトリがあり、
+この中にアプリケーションのためのすべてのシェルやタスクを格納します。
+またここには以下の実行ファイルがあります::
$ cd /path/to/cakephp/app
- $ Console/cake
+ $ ./Console/cake
-It's often wise to add the core cake executable to your system path
-so you can use the cake command anywhere. This comes in handy when you are
-creating new projects. See :ref:`adding-cake-to-your-path` for how to make ``cake``
-available systemwide.
+システムのパスの中にコアとなるcake実行ファイル(を含むディレクトリ)を
+追加するのもよいでしょう。これでどこにいてもcakeコマンドが使えるように
+なり、新しいプロジェクトを生成する際にも便利です。 ``cake`` をシステム全体
+で使えるようにするやり方は :ref:`adding-cake-to-your-path` にあります。
-Running the Console with no arguments produces this help message::
+引数なしでコンソールを起動すると、以下のメッセージが表示されます
+(訳注:便宜上、一部和訳しています)::
Welcome to CakePHP v2.0.0 Console
---------------------------------------------------------------
App : app
Path: /path/to/cakephp/app/
---------------------------------------------------------------
- Current Paths:
+ 現在のパス:
-app: app
-working: /path/to/cakephp/app
-root: /path/to/cakephp/
-core: /path/to/cakephp/core
- Changing Paths:
+ パスの変更:
- your working path should be the same as your application path
- to change your path use the '-app' param.
- Example: -app relative/path/to/cakephp/app or -app /absolute/path/to/cakephp/app
+ 作業パスは自分のアプリケーションパスと同じである必要があります。
+ パスを変更するには '-app' を使います。
+ 例: -app cakephpへの相対パス または -app /cakephpへの絶対パス
- Available Shells:
+ 利用できるシェル:
acl [CORE] i18n [CORE]
api [CORE] import [app]
@@ -79,63 +79,61 @@ Running the Console with no arguments produces this help message::
command_list [CORE] testsuite [CORE]
console [CORE] upgrade [CORE]
- To run a command, type 'cake shell_name [args]'
- To get help on a specific command, type 'cake shell_name help'
+ コマンドを実行するには 'cake シェル名 [引数]' にようにタイプします。
+ 'cake シェル名 help' で特定のコマンドに対するヘルプが表示されます。
-The first information printed relates to paths. This is especially
-helpful if you're running the console from different parts of the
-filesystem.
+先頭部分にはパスに関連する情報が表示されます。これはファイルシステム上の
+異なったところからコンソールを動かしている場合、特に有用です。
-Since many users add the CakePHP console to their system's path so it can
-be accessed easily. Printing out the working, root, app, and core
-paths allows you to see where the console will be making changes.
-To change the app folder you wish to work with, you can supply its
-path as the first argument to the cake command. This next example
-shows how to specify an app folder, assuming you’ve already added
-the console folder to your ``PATH``::
+CakePHPコンソールを自分のシステムパスに追加しているユーザが多ければ、cake
+コンソールには簡単にアクセスできます。表示されているのはworking, root,
+app, coreのパスで、それぞれコンソールの場所が変更されていてもその位置を
+確認できます。作業したいappフォルダをを変更するには単にそこへのパスをcake
+コマンドに知らせてやるだけです。次にappフォルダの設定例を示しますが、その際
+コンソールのフォルダをあなたの ``PATH`` に追加してあるとものとみなしています::
$ cake -app /path/to/cakephp/app
-The path supplied can be relative to the current working directory
-or supplied as an absolute path.
-
+指定するパスは、現在の作業ディレクトリへの相対パスでも絶対パスでも構いません。
.. _adding-cake-to-your-path:
-Adding cake to your system path
--------------------------------
+自分のシステムパスにcakeを追加する
+----------------------------------
+
+\*nixシステム(linux, MacOSX)をお使いの場合は、以下の手順によりcakeの
+実行ファイルへのパスをシステムパスに追加します。
-If you are on a \*nix system (linux, MacOSX) the following steps will let you add the
-cake executable to your system path.
+#. CakePHPがインストールされている場所にcakeの実行ファイルがあることを確認します。例えば、以下の場所になります::
-#. Locate where your CakePHP install, and cake executable are. For example
``/Users/mark/cakephp/lib/Cake/Console/cake``
-#. Edit your ``.bashrc`` or ``.bash_profile`` file in your home directory, and add the following::
+
+#. 自分のホームディレクトリにある ``.bashrc`` もしくは ``.bash_profile`` をエディタで開き、以下を追加します::
export PATH="$PATH:/Users/mark/cakephp/lib/Cake/Console"
-#. Reload the bash configuration or open a new terminal, and ``cake`` should work anywhere.
+#. bashの設定ファイルをリロードするか、もしくは新しい端末を開きます。どこにいても ``cake`` は動くはずです。
+
+Windows Vistaもしくは7をお使いの場合は、以下の手順に従ってください。
-If you are on Windows Vista or 7, you should follow the steps below.
+#. CakePHPがインストールされている場所にcakeの実行ファイルがあることを確認します。
-#. Locate where your CakePHP install and cake executable are. For example
``C:\xampp\htdocs\cakephp\lib\Cake\Console``
-#. Open System Properties window from My Computer. You want to try the shortcut Windows Key + Pause or Windows Key + Break. Or, from the Desktop, right-click My Computer, click Properties then click Advanced System Settings link in the left column
-#. Go under Advanced tab and click on Environment Variables button
-#. In the System Variables portion, reach Path variable and double-click on it to Edit
-#. Add the ``cake`` install path string followed by a semi colon. Result example::
+
+#. マイコンピュータからシステムのプロパティを開きます。ショートカットを使う場合は Windows キー + Pause もしくは Windows キー + Breakです。デスクトップからの場合はコンピュータで右クリックしてプロパティを開き、システムの詳細設定をクリックします。
+
+#. 詳細設定タブから環境変数を開き、システム環境変数の中のPathをダブルクリックして修正します。ここに ``cake`` のインストールパス文字列を;で区切って追加します。その結果は以下のようになります::
%SystemRoot%\system32;%SystemRoot%;C:\xampp\htdocs\cakephp\Cake\lib\Console;
-#. Click Ok and ``cake`` should work anywhere.
+#. これでOkをクリックすれば、 ``cake`` がどこからでも動くようになるはずです。
-Creating a shell
+シェルの作成
================
-Let's create a shell for use in the Console. For this example,
-we'll create a simple Hello world shell. In you applications
-``Console/Command`` directory create ``HelloShell.php``. Put the following
-code inside it::
+早速コンソールで動くシェルを作ってみましょう。この例ではシンプルなhello world
+シェルを作ります。お使いのアプリケーションの ``Console/Command`` ディレクトリで
+``HelloShell.php`` を作ってください。その中に以下のコードを書きます::
args``, this
-property contains an array of all the positional arguments provided to a command. You can
-also use switches or options on shell applications, these are available at ``$this->params``,
-but we'll cover that in a bit.
-
-When using a ``main()`` method you won't be able to use the positional arguments
-or parameters. This is because the first positional argument or option is
-interpreted as the command name. If you want to use arguments and options, you
-should use method names other than ``main``.
-
-Using Models in your shells
+このファイルを作って ``Console/cake hello hey_there あなたの名前`` を実行
+すると、ご自分の名前が表示されるはずです。publicとして定義された任意の
+メソッドのうち頭に ``_`` が付かないものは、コマンドラインから呼び出せます。
+直前の例の ``hey_there`` メソッドの中では ``$this->args`` を使っています。
+これはコマンドに対して与えられた(指定順序が意味を持つ)引数が、与えられた
+順に配列として保持されています。シェルアプリケーションではスイッチや
+オプションを使うこともでき、これらは ``$this->params`` として参照可能ですが、
+ここではプロパティ名を示すに留めます。
+
+``main()`` メソッドを使っている場合、位置引数は参照できません。これは
+第一引数として指定された引数またはオプションが、コマンド名と解釈される
+からです。引数やオプションを使いたい場合は、 ``main`` ではない
+何か他のメソッド名を使う必要があります。
+
+シェルの中でモデルを使う
---------------------------
-You'll often need access to your application's business logic in shell utilities;
-CakePHP makes that super easy. By setting a ``$uses`` property, you can define an
-array of models you want to have access to in your shell. The defined models
-are loaded in as properties attached to your shell, just like a controller gets
-models attached to it::
+自作アプリケーションのビジネスロジックを、シェルユーティリティの中からアクセス
+する必要があることも少なくありません。CakePHPでは、これはいとも簡単に実現可能
+です。 ``$uses`` プロパティを設定することで、シェルからアクセスできるモデルの
+配列を定義できます。ちょうどコントローラからモデルに接続するのと同じように、
+定義されたモデルがロードされ、あなたのシェルにプロパティとして接続されます::
Sound->execute();
}
}
-You can also access tasks directly from the command line::
+コマンドラインからタスクを直接呼び出すこともできます::
$ cake sea sound
.. note::
- In order to access tasks directly from the command line, the task
- **must** be included in the shell class' $tasks property.
- Therefore, be warned that a method called “sound” in the SeaShell
- class would override the ability to access the functionality in the
- Sound task specified in the $tasks array.
+ コマンドラインからタスクを直接呼び出せるように、タスクは必ずシェルクラス
+ の$tasksプロパティに含まれている必要があります。このため、もしSeaShellに
+ "sound"という名前のメソッドがある場合は、$tasks配列で指定されたSoundタスク
+ にある機能を上書きするのでアクセスできなくなりますよという警告が出ます。
-Loading tasks on the fly with TaskCollection
---------------------------------------------
+TaskCollectionによる、必要な場所(on the fly)でのタスクのロード
+----------------------------------------------------------------
-You can load tasks on the fly using the Task collection object. You can load tasks that
-were not declared in $tasks this way::
+タスクコレクションオブジェクトを使って、タスクをその場でロードすることも
+できます。$tasksで宣言するのとはまた別のやり方です::
Tasks->load('Project');
-Would load and return a ProjectTask instance. You can load tasks from plugins using::
+これによりタスクをロードしてProjectTaskインスタンスを返します。
+プラグインからタスクをロードすることもできます::
Tasks->load('ProgressBar.ProgressBar');
.. _invoking-other-shells-from-your-shell:
-Invoking other shells from your shell
-=====================================
+自分のシェルから他のシェルを呼び出す
+====================================
-Shells no longer have direct access to the ShellDispatcher any more through `$this->Dispatch`.
-There are still many cases where you will want to invoke one shell from another though.
-`Shell::dispatchShell()` gives you the ability to call other shells by providing the
-`argv` for the sub shell. You can provide arguments and options either
-as var args or as a string::
+シェルからは、もはや `$this->Dispatch` を通したShellDispatcherへの直接の
+アクセスができません。あるシェルから他のシェルを呼び出したいケースは多々
+あると思います。他のシェルを呼び出すには `Shell::dispatchShell()` を使います。
+サブシェル側では引数を受け取るための `argv` が使えます。引数やオプションは
+引数リスト(配列)もしくは文字列として指定できます::
dispatchShell('schema create Blog --plugin Blog');
- // As an array
+ // 配列で渡す
$this->dispatchShell('schema', 'create', 'Blog', '--plugin', 'Blog');
-The above shows how you can call the schema shell to create the schema for a plugin
-from inside your plugin's shell.
+これらの例では自分のプラグインのシェルの中からプラグインのスキーマを
+作るためにschemaシェルを呼んでいます。
+
.. _shell-output-level:
-Console output levels
-=====================
+コンソール出力のレベル
+======================
-Shells often need different levels of verbosity. When running as cron jobs,
-most output is un-necessary. And there are times when you are not interested in
-everything that a shell has to say. You can use output levels to flag output
-appropriately. The user of the shell, can then decide what level of detail
-they are interested in by setting the correct flag when calling the shell.
-:php:meth:`Shell::out()` supports 3 types of output by default.
+シェルでは往々にして異なったレベルの冗長出力が必要になります。cronジョブ
+として動いている場合はほとんどの出力は不要です。また、シェルが出力する
+メッセージを見たくないというケースもあるでしょう。このような場合、出力を
+適切に制御するための出力レベルが使えます。シェルの利用者は、シェルを
+呼び出す際に正しいフラグをセットすることで、自分が見たい詳細レベルの設定
+ができます。 :php:meth:`Shell::out()` ではデフォルトで3種類の出力を
+サポートしています。
-* QUIET - Only absolutely important information should be marked for quiet output.
-* NORMAL - The default level, and normal usage
-* VERBOSE - Mark messages that may be too noisy for everyday use, but helpful
- for debugging as VERBOSE
+* QUIET - 必須のメッセージであり、静かな(必要最小限の)出力モードでも表示される
+* NORMAL - 通常利用におけるデフォルトのレベル
+* VERBOSE - 通常利用では冗長につき表示不要。ただデバッグ時には有用
-You can mark output as follows::
+以下のように出力を指定できます::
out('Quiet message', 1, Shell::QUIET);
- // would not appear when quiet output is toggled
+ // 「静かな」出力の際には表示されません
$this->out('normal message', 1, Shell::NORMAL);
$this->out('loud message', 1, Shell::VERBOSE);
- // would only appear when verbose output is enabled.
+ // 冗長出力の場合にのみ表示されます
$this->out('extra message', 1, Shell::VERBOSE);
-You can control the output level of shells, by using the ``--quiet`` and ``--verbose``
-options. These options are added by default, and allow you to consistently control
-output levels inside your CakePHP shells.
+シェルの実行時に ``--quiet`` や ``--verbose`` を使うことで出力を制御できます。
+これらのオプションはデフォルトで組み込まれていて、いつでもシェルの中で
+出力レベルを制御できるように考慮されています。
-Styling output
+出力のスタイル
==============
-Styling output is done by including tags - just like html - in your output.
-ConsoleOutput will replace these tags with the correct ansi code sequence, or
-remove the tags if you are on a console that doesn't support ansi codes. There
-are several built in styles, and you can create more. The built in ones are
+ちょうどHTMLのようにタグを埋め込むことで、出力のスタイルを変更することが
+できます。ConsoleOutputはこれらのタグを正しいansiコードシーケンスに変換
+したり、ansiコードをサポートしないコンソールではタグを除去したりします。
+スタイルはいくつかビルトインされたものがありますが、自分で作成することも
+可能です。ビルトインされたものは以下の通りです。
-* ``error`` Error messages. Red underlined text.
-* ``warning`` Warning messages. Yellow text.
-* ``info`` Informational messages. Cyan text.
-* ``comment`` Additional text. Blue text.
-* ``question`` Text that is a question, added automatically by shell.
+* ``error`` エラーメッセージ。赤いアンダーライン。
+* ``warning`` 警告メッセージ。黄色いテキスト。
+* ``info`` 情報メッセージ。水色のテキスト
+* ``comment`` 追加情報。青字のテキスト
+* ``question`` 質問事項。シェルが自動的に追加する。
-You can create additional styles using `$this->stdout->styles()`. To declare a
-new output style you could do::
+`$this->stdout->styles()` を使ってさらに多くのスタイルを追加できます。
+新しいスタイルを追加するには以下のようにします::
stdout->styles('flashy', array('text' => 'magenta', 'blink' => true));
-This would then allow you to use a ```` tag in your shell output, and if ansi
-colours are enabled, the following would be rendered as blinking magenta text
-``$this->out('Whoooa Something went wrong');``. When defining
-styles you can use the following colours for the `text` and `background` attributes:
+これで ```` というタグが有効になり、ansiカラーが有効な端末であれば、
+``$this->out('うわ! 何か変になった');`` の場合の表示は
+色がマゼンタでブリンクになります。スタイルを定義する際は `text` と `background`
+属性として以下の色が指定できます:
* black
* red
@@ -370,61 +375,62 @@ styles you can use the following colours for the `text` and `background` attribu
* cyan
* white
-You can also use the following options as boolean switches, setting them to a
-truthy value enables them.
+さらに以下のオプションをブール型のスイッチとして指定できます。
+値が真の場合に有効になります。
* bold
* underline
* blink
* reverse
-Adding a style makes it available on all instances of ConsoleOutput as well,
-so you don't have to redeclare styles for both stdout and stderr objects.
-Turning off colouring
----------------------
+スタイルを追加するとConsoleOutputのすべてのインスタンスでも有効になります。
+なのでstdoutとstderr両方のオブジェクトでこれらを再定義する必要はありません。
-Although colouring is pretty awesome, there may be times when you want to turn it off,
-or force it on::
+カラー表示を無効にする
+----------------------
+
+カラー表示はなかなか綺麗ですが、オフにしたい場合や強制的にオンにしたい場合も
+あるでしょう::
output->outputAs(ConsoleOutput::RAW);
-The above will put the output object into raw output mode. In raw output mode,
-no styling is done at all. There are three modes you can use.
+これはRAW(生の)出力モードにします。RAW出力モードではすべてのスタイルが
+無効になります。モードには3種類あります。
+
-* ``ConsoleOutput::RAW`` - Raw output, no styling or formatting will be done.
- This is a good mode to use if you are outputting XML or, want to debug why
- your styling isn't working.
-* ``ConsoleOutput::PLAIN`` - Plain text output, known style tags will be stripped
- from the output.
-* ``ConsoleOutput::COLOR`` - Output with color escape codes in place.
+* ``ConsoleOutput::RAW`` - RAW出力、スタイルや書式設定は行われない。
+ これはXMLを出力する場合や、スタイルのデバッグを行う際に役立ちます。
+* ``ConsoleOutput::PLAIN`` - プレーンテキストモード。既知のスタイルタグが
+ 出力から取り除かれます。
+* ``ConsoleOutput::COLOR`` - カラーエスケープコードを出力します。
-By default on \*nix systems ConsoleOutput objects default to colour output.
-On windows systems, plain output is the default unless the ``ANSICON`` environment
-variable is present.
+デフォルトでは\*nixシステムにおけるConsoleOutputのデフォルトはカラー出力
+モードです。Windowsでは ``ANSICON`` 環境変数がセットされている場合を除き、
+プレーンテキストモードがデフォルトです。
-Configuring options and generating help
-=======================================
+オプションの構成とヘルプの生成
+==============================
.. php:class:: ConsoleOptionParser
-Console option parsing in CakePHP has always been a little bit different
-from everything else on the command line. In 2.0 ``ConsoleOptionParser``
-helps provide a more familiar command line option and argument parser.
+CakePHPにおけるオプションのパースは、コマンドラインのそれに比べて少しずつ
+変わってきています。2.0では親しみやすいコマンドラインオプションや引数パーサ
+の提供を ``ConsoleOptionParser`` が助けてくれます。
-OptionParsers allow you to accomplish two goals at the same time.
-First they allow you to define the options and arguments, separating
-basic input validation and your code. Secondly, it allows you to provide
-documentation, that is used to generate well formatted help file.
+OptionParsersは同時に2つのことを実現します。1つ目は、基本的なバリデー
+ションと独自のコードにより、オプションと引数を定義することです。2つ目は、
+きれいにフォーマットされたヘルプファイルを生成するためのドキュメントの
+提供です。
-The console framework gets your shell's option parser by calling
-``$this->getOptionParser()``. Overriding this method allows you to
-configure the OptionParser to match the expected inputs of your shell.
-You can also configure subcommand option parsers, which allow you to
-have different option parsers for subcommands and tasks.
-The ConsoleOptionParser implements a fluent interface and includes
-methods for easily setting multiple options/arguments at once.::
+コンソールのフレームワークは ``$this->getOptionParser()`` を呼び出すことにより
+あなたのシェルのオプションパーサを取得します。このメソッドをオーバーライド
+することで、オプションパーサがあなたのシェルの期待する入力にマッチするように
+なります。さらにサブコマンドオプションパーサを設定すると、サブコマンドと
+タスクについて異なったオプションパーサを定義できます。ConsoleOptionParser
+は柔軟なインターフェースを実装しており、また複数のオプション/引数を一度に
+簡単に設定できるようなメソッドを備えています::
addArgument('type', array(
- 'help' => 'Either a full path or type of class.'
+ 'help' => 'フルパスもしくはクラスの型のいずれか。'
))->addArgument('className', array(
- 'help' => 'A CakePHP core class name (e.g: Component, HtmlHelper).'
+ 'help' => 'CakePHPコアのクラス名(Component, HtmlHelper等)。'
))->addOption('method', array(
'short' => 'm',
'help' => __('The specific method you want help on.')
))->description(__('Lookup doc block comments for classes in CakePHP.'));
-The methods that allow chaining are:
+連結できるのは以下のメソッドです:
- description()
- epilog()
@@ -463,104 +469,98 @@ The methods that allow chaining are:
.. php:method:: description($text = null)
-Gets or sets the description for the option parser. The description
-displays above the argument and option information. By passing in
-either an array or a string, you can set the value of the description.
-Calling with no arguments will return the current value::
+オプションパーサの説明文を取得または設定します。説明文は引数やオプション
+の上に表示されます。配列または文字列を渡すことで説明文の値を設定できます。
+引数がない場合は現在の値を返します::
description(array('line one', 'line two'));
+ // 一度に複数行を設定
+ $parser->description(array('1行目', '2行目'));
- // read the current value
+ // 現在の値を取得する
$parser->description();
.. php:method:: epilog($text = null)
-Gets or sets the epilog for the option parser. The epilog
-is displayed after the argument and option information. By passing in
-either an array or a string, you can set the value of the epilog.
-Calling with no arguments will return the current value::
+オプションパーサのエピローグを取得または設定します。エピローグは引数
+またはオプション情報の後に表示されます。配列または文字列を渡すことで
+エピローグの値を設定できます。引数がない場合は現在の値を返します::
epilog(array('line one', 'line two'));
+ // 一度に複数行を設定
+ $parser->epilog(array('1行目', '2行目'));
- // read the current value
+ // 現在の値を取得する
$parser->epilog();
-Adding arguments
-----------------
+引数の追加
+----------
.. php:method:: addArgument($name, $params = array())
-Positional arguments are frequently used in command line tools,
-and ``ConsoleOptionParser`` allows you to define positional
-arguments as well as make them required. You can add arguments
-one at a time with ``$parser->addArgument();`` or multiple at once
-with ``$parser->addArguments();``::
+コマンドラインツールにおいて、指定順序が意味を持つ引数はよく使われます。
+``ConsoleOptionParser`` では指定順序が意味を持つ引数を要求するだけでなく
+定義することもできます。指定する際は``$parser->addArgument();``で一度に
+ひとつずつ設定するか、 ``$parser->addArguments();`` で複数個を同時に
+指定するかを選べます。::
addArgument('model', array('help' => 'The model to bake'));
-You can use the following options when creating an argument:
+引数を作成する際は以下のオプションが指定できます:
-* ``help`` The help text to display for this argument.
-* ``required`` Whether this parameter is required.
-* ``index`` The index for the arg, if left undefined the argument will be put
- onto the end of the arguments. If you define the same index twice the
- first option will be overwritten.
-* ``choices`` An array of valid choices for this argument. If left empty all
- values are valid. An exception will be raised when parse() encounters an
- invalid value.
+* ``help`` この引数に対して表示するヘルプ
+* ``required`` この引数が必須かどうか
+* ``index`` 引数のインデックス。設定されない場合は引数リストの末尾に位置づけられます。同じインデックスを2回指定すると、最初に指定したオプションは上書きされます。
+* ``choices`` この引数について有効な選択肢。指定しない場合はすべての値が有効となります。parse()が無効な値を検出すると、例外が発生します。
-Arguments that have been marked as required will throw an exception when
-parsing the command if they have been omitted. So you don't have to
-handle that in your shell.
+必須であると指定された引数が省略された場合、コマンドのパースにおいて
+例外が発生します。これにより、引数のチェックをシェルの中で行う必要が
+なくなります。
.. php:method:: addArguments(array $args)
-If you have an array with multiple arguments you can use ``$parser->addArguments()``
-to add multiple arguments at once.::
+複数の引数を1個の配列で持つ場合、 ``$parser->addArguments()`` により
+一度に複数の引数を追加できます::
addArguments(array(
- 'node', array('help' => 'The node to create', 'required' => true),
- 'parent' => array('help' => 'The parent node', 'required' => true)
+ 'node', array('help' => '生成するノード', 'required' => true),
+ 'parent' => array('help' => '親ノード', 'required' => true)
));
-As with all the builder methods on ConsoleOptionParser, addArguments
-can be used as part of a fluent method chain.
+ConsoleOptionParser上のすべてのビルダーメソッドと同様に、addArguments
+も柔軟なメソッドチェインの一部として使えます。
-Validating arguments
---------------------
+引数の検証
+----------
-When creating positional arguments, you can use the ``required`` flag, to
-indicate that an argument must be present when a shell is called.
-Additionally you can use ``choices`` to force an argument to
-be from a list of valid choices::
+指定順序が意味を持つ引数を定義する場合、 ``required`` フラグを指定できます。
+これはシェルが呼ばれた時、その引数が存在しなければならないことを意味します。
+さらに``choices``を使うことで、その引数が取りうる有効な値の選択肢を制限
+できます::
addArgument('type', array(
- 'help' => 'The type of node to interact with.',
+ 'help' => 'これとやり取りするノードの型',
'required' => true,
'choices' => array('aro', 'aco')
));
-The above will create an argument that is required and has validation
-on the input. If the argument is either missing, or has an incorrect
-value an exception will be raised and the shell will be stopped.
+この例では、必須でかつ入力時に値の正当性チェックが行われるような引数を
+作成します。引数が指定されないか、または無効な値が指定された場合は例外が
+発生してシェルが停止します。
-Adding Options
---------------
+オプションの追加
+----------------
.. php:method:: addOption($name, $options = array())
-Options or flags are also frequently used in command line tools.
-``ConsoleOptionParser`` supports creating options
-with both verbose and short aliases, supplying defaults
-and creating boolean switches. Options are created with either
-``$parser->addOption()`` or ``$parser->addOptions()``.::
+コマンドラインツールでは、オプションやフラグもまたよく使われます。
+``ConsoleOptionParser`` では長い名称と短い別名の両方を持つオプション、
+デフォルト値の設定やブール型スイッチの作成などをサポートしています。
+オプションは ``$parser->addOption()`` または ``$parser->addOptions()``
+により追加します。::
addOption('connection', array(
@@ -569,52 +569,49 @@ and creating boolean switches. Options are created with either
'default' => 'default'
));
-The above would allow you to use either ``cake myshell --connection=other``,
-``cake myshell --connection other``, or ``cake myshell -c other``
-when invoking the shell. You can also create boolean switches, these switches do not
-consume values, and their presence just enables them in the
-parsed parameters.::
+この例の場合、シェルを起動する際に ``cake myshell --connection=other``,
+``cake myshell --connection other``, ``cake myshell -c other``
+のいずれかで引数を指定できます。またブール型のスイッチも作れますが、
+これらのスイッチは値を消費せず、またその存在はパースされた引数の中
+だけとなります。::
addOption('no-commit', array('boolean' => true));
-With this option, when calling a shell like ``cake myshell --no-commit something``
-the no-commit param would have a value of true, and 'something'
-would be a treated as a positional argument.
-The built-in ``--help``, ``--verbose``, and ``--quiet`` options
-use this feature.
+このオプション指定の場合、 ``cake myshell --no-commit something`` のように
+コールされるとno-commit引数が真になり、'something'は位置引数と見なされます。
+ビルトインオプションの ``--help``, ``--verbose``, ``--quiet`` もこの
+仕組みを利用しています。
-When creating options you can use the following options to
-define the behavior of the option:
+オプションを作成する場合、オプションの振る舞いを定義するのに以下の
+オプションが使えます:
-* ``short`` - The single letter variant for this option, leave undefined for none.
-* ``help`` - Help text for this option. Used when generating help for the option.
-* ``default`` - The default value for this option. If not defined the default will be true.
-* ``boolean`` - The option uses no value, it's just a boolean switch.
- Defaults to false.
-* ``choices`` An array of valid choices for this option. If left empty all
- values are valid. An exception will be raised when parse() encounters an invalid value.
+* ``short`` - このオプションを表す1文字の別名。未定義の場合はなしになります。
+* ``help`` - このオプションのヘルプ文字列。オプションのヘルプを生成する際に参照されます。
+* ``default`` - このオプションのデフォルト値。未定義の場合、デフォルト値は真となります。
+* ``boolean`` - 値を持たない単なるブール型のスイッチ。デフォルト値は偽です。
+* ``choices`` - このオプションで取りうる有効な選択肢。未指定の場合はすべての値を有効とします。parse()が無効な値を検出すると、例外が発生します。
.. php:method:: addOptions(array $options)
-If you have an array with multiple options you can use ``$parser->addOptions()``
-to add multiple options at once.::
+複数のオプションが1個の配列に入っている場合、 ``$parser->addOptions()``
+を使って複数のオプションを一度に設定できます。::
addOptions(array(
- 'node' => array('short' => 'n', 'help' => 'The node to create'),
- 'parent' => array('short' => 'p', 'help' => 'The parent node')
+ 'node' => array('short' => 'n', 'help' => '生成するノード'),
+ 'parent' => array('short' => 'p', 'help' => '親ノード')
));
-As with all the builder methods on ConsoleOptionParser, addOptions is can be used
-as part of a fluent method chain.
+ConsoleOptionParser上のビルダーメソッドと同様に、addOptionsも強力な
+メソッドチェーンの一部として使えます。
-Validating options
-------------------
+オプションの検証
+----------------
-Options can be provided with a set of choices much like positional arguments
-can be. When an option has defined choices, those are the only valid choices
-for an option. All other values will raise an ``InvalidArgumentException``::
+オプションでは位置引数と同様に、値の選択肢を指定できます。あるオプションが
+選択肢が指定されている場合、それらがそのオプションで取りうる有効な値です。
+これ以外の値が指定されると ``InvalidArgumentException`` が発生します::
addOption('accept', array(
@@ -622,43 +619,45 @@ for an option. All other values will raise an ``InvalidArgumentException``::
'choices' => array('working', 'theirs', 'mine')
));
-Using boolean options
----------------------
+ブール型オプションを使う
+------------------------
+
+フラグのオプションを作りたい場合、オプションをブール型として指定できます。
+デフォルト値を持つオプションのように、ブール型のオプションもパース済み引数
+の中に常に自分自身を含んでいます。フラグが存在する場合それらは真にセットされ、
+存在しない場合は偽になります::
-Options can be defined as boolean options, which are useful when you need to create
-some flag options. Like options with defaults, boolean options always include
-themselves into the parsed parameters. When the flags are present they are set
-to true, when they are absent false::
addOption('verbose', array(
- 'help' => 'Enable verbose output.',
+ 'help' => '冗長出力を有効にする.',
'boolean' => true
));
-The following option would result in ``$this->params['verbose']`` always
-being available. This lets you omit ``empty()`` or ``isset()``
-checks for boolean flags::
+以下の例のように ``$this->params['verbose']`` の結果が常に参照可能です。
+これにより、ブール型のフラグをチェックする際に ``empty()`` や ``isset()`` に
+よるチェックをする必要がありません。::
params['verbose']) {
// do something
}
-Since the boolean options are always defined as ``true`` or
-``false`` you can omit additional check methods.
+これは、ブール型のオプションは常に ``true`` または ``false`` として定義されて
+いるからです。そのためそれ以上のチェックメソッドを省略できます。
-Adding subcommands
+サブコマンドの追加
------------------
.. php:method:: addSubcommand($name, $options = array())
-Console applications are often made of subcommands, and these subcommands
-may require special option parsing and have their own help. A perfect
-example of this is ``bake``. Bake is made of many separate tasks that all
-have their own help and options. ``ConsoleOptionParser`` allows you to
-define subcommands and provide command specific option parsers so the
-shell knows how to parse commands for its tasks::
+コンソールアプリケーションはサブコマンドから構成されることも多いのですが、
+サブコマンド側で特別なオプション解析や独自ヘルプを持ちたいこともあります。
+この完全な例が ``bake`` です。Bakeは多くの別々のタスクから構成されますが、
+各タスクはそれぞれ独自のヘルプとオプションを持っています。
+``ConsoleOptionParser`` を使ってサブコマンドを定義し、それらに固有のオプション
+パーサを提供できるので、シェルはそれぞれのタスクについてコマンドをどう
+解析すればよいのかを知ることができます::
addSubcommand('model', array(
@@ -666,36 +665,35 @@ shell knows how to parse commands for its tasks::
'parser' => $this->Model->getOptionParser()
));
-The above is an example of how you could provide help and a specialized
-option parser for a shell's task. By calling the Task's ``getOptionParser()``
-we don't have to duplicate the option parser generation, or mix concerns
-in our shell. Adding subcommands in this way has two advantages.
-First it lets your shell easily document its subcommands in the
-generated help, and it also allows easy access to the subcommand
-help. With the above subcommand created you could call
-``cake myshell --help`` and see the list of subcommands, and
-also run ``cake myshell model --help`` to view the help for
-just the model task.
+上の例では、シェルのタスクに対してヘルプやそれに特化したオプションパーサ
+を提供方法を示しています。タスクの ``getOptionParser()`` を呼ぶことで、
+オプションパーサの複製をしたり、シェル内の関係を調整する必要がなくなります。
+この方法でサブコマンドを追加することには2つの利点があります。
+まず生成されたヘルプの中で簡単にサブコマンドを文書化できること、そして
+サブコマンドのヘルプに簡単にアクセスできることです。前述のやり方で生成
+したサブコマンドを使って ``cake myshell --help`` とやると、サブコマンドの
+一覧が出ます。また ``cake myshell model --help`` とやると、modelタスクだけの
+ヘルプが表示されます。
-When defining a subcommand you can use the following options:
+サブコマンドを定義する際は、以下のオプションが使えます:
-* ``help`` - Help text for the subcommand.
-* ``parser`` - A ConsoleOptionParser for the subcommand. This allows you
- to create method specific option parsers. When help is generated for a
- subcommand, if a parser is present it will be used. You can also
- supply the parser as an array that is compatible with
- :php:meth:`ConsoleOptionParser::buildFromArray()`
+* ``help`` - サブコマンドのヘルプテキスト
+* ``parser`` - サブコマンドのConsoleOptionParser。これによりメソッド固有の
+ オプションパーサを生成します。サブコマンドに関するヘルプが生成される際、
+ もしパーサが存在すればそれが使われます。パーサを配列として指定することも
+ できます。その場合は :php:meth:`ConsoleOptionParser::buildFromArray()` と
+ 互換です。
-Adding subcommands can be done as part of a fluent method chain.
+サブコマンドの追加も強力なメソッドチェーンの一部として使えます。
-Building a ConsoleOptionParser from an array
---------------------------------------------
+配列からConsoleOptionParserを構成する
+-------------------------------------
.. php:method:: buildFromArray($spec)
-As previously mentioned, when creating subcommand option parsers,
-you can define the parser spec as an array for that method. This can help
-make building subcommand parsers easier, as everything is an array::
+前述のように、サブコマンドのオプションパーサを作成する際は、そのメソッド
+に対するパーサの仕様を配列として定義できます。これによりすべてが配列として
+扱えるので、サブコマンドパーサの構築が容易になります::
addSubcommand('check', array(
@@ -714,12 +712,12 @@ make building subcommand parsers easier, as everything is an array::
)
));
-Inside the parser spec, you can define keys for ``definition``,
-``arguments``, ``options``, and ``epilog``. You cannot define
-subcommands inside an array style builder. The values for
-arguments, and options, should follow the format that
-:php:func:`ConsoleOptionParser::addArguments()` and :php:func:`ConsoleOptionParser::addOptions()`
-use. You can also use buildFromArray on its own, to build an option parser::
+パーサの仕様の中では ``definition``, ``arguments``, ``options``, ``epilog``
+のためのキーを定義できます。配列形式ビルダーの内部にはサブコマンドは定義
+できません。argumentsとoptionsの値は
+:php:func:`ConsoleOptionParser::addArguments()` と
+:php:func:`ConsoleOptionParser::addOptions()` が利用する書式に準じてください。
+自分自身に対してbuildFromArrayを使ってオプションパーサを構築することも可能です::
+シェル/CLIにおけるルーティング
+===============================
-Shell API
+コマンドライン・インターフェース(CLI)、特にあなたのシェルやタスクでは、
+``env('HTTP_HOST')`` やその他のWebブラウザ固有の変数がセットされていません。
+
+``Router::url()`` を使ってレポートを作成したりeメールを送ったりする場合、
+それらにはデフォルトホスト ``http://localhost/`` が構成に含まれており、
+そのため結果として無効なURLとなってしまいます。こういったケースでは、
+ドメインを手作業で設定してやらなければなりません。これを、たとえばブート
+ストラップまたはconfigで、コンフィグ値 ``App.fullBaseURL`` を使って
+設定できます。
+
+eメールを送る場合は、CakeEmailクラスでメールを送る際のホストを指定する
+必要があります::
+
+ $Email = new CakeEmail();
+ $Email->domain('www.example.org');
+
+これにより生成されるメッセージIDは有効で、また送信元ドメイン名にも合致
+したものになります。
+
+シェルAPI
=========
.. php:class:: AppShell
- AppShell can be used as a base class for all your shells. It should extend
- :php:class:`Shell`, and be located in ``Console/Command/AppShell.php``
+ AppShellはあなたのすべてのシェルの基底クラスとして使えます。これは
+ :php:class:`Shell` を継承し、また ``Console/Command/AppShell.php``
+ として置かれている必要があります。
.. php:class:: Shell($stdout = null, $stderr = null, $stdin = null)
- Shell is the base class for all shells, and provides a number of functions for
- interacting with user input, outputting text a generating errors.
+ Shellはすべてのシェルの基底クラスであり、ユーザの入力と対話するための
+ 多くの関数を提供し、また生成されたエラーをテキストとして出力します。
.. php:attr:: tasks
- An array of tasks you want loaded for this shell/task.
+ このシェル/タスクでロードしたいタスクの配列
.. php:attr:: uses
- An array of models that should be loaded for this shell/task.
+ このシェル/タスクでロードしたいモデルの配列
.. php:method:: clear()
- Clears the current output being displayed.
+ 出力バッファの中身をクリアする
.. php:method:: createFile($path, $contents)
- :param string $path: Absolute path to the file you want to create.
- :param string $contents: Contents to put in the file.
+ :param string $path: 生成したいファイルへの絶対パス
+ :param string $contents: ファイルに出力したいコンテンツ
- Creates a file at a given path. If the Shell is interactive, a warning will be
- generated, and the user asked if they want to overwrite the file if it already exists.
- If the shell's interactive property is false, no question will be asked and the file
- will simply be overwritten.
+ 与えられたパスでファイルを生成します。ファイルが存在する場合、会話的
+ シェルであれば警告が発せられ、上書きするかどうか聞かれます。シェルの
+ 会話モードが偽であれば質問は行われず、単にファイルは上書きされます。
.. php:method:: dispatchShell()
- Dispatch a command to another Shell. Similar to
- :php:meth:`Controller::requestAction()` but intended for running shells
- from other shells.
+ コマンドから別のシェルに制御を移します。
+ :php:meth:`Controller::requestAction()` と似ていますが、他のシェルから
+ シェルを起動することを目的としています。
- See :ref:`invoking-other-shells-from-your-shell`.
+ 参照 :ref:`invoking-other-shells-from-your-shell`.
.. php:method:: err($message = null, $newlines = 1)
- :param string $method: The message to print.
- :param integer $newlines: The number of newlines to follow the message.
+ :param string $method: 表示するメッセージ
+ :param integer $newlines: メッセージの後の改行する数
- Outputs a method to ``stderr``, works similar to :php:meth:`Shell::out()`
+ ``stderr`` へ出力するメソッド。 :php:meth:`Shell::out()` のように動作する。
.. php:method:: error($title, $message = null)
- :param string $title: Title of the error
- :param string $message: An optional error message
+ :param string $title: エラーのタイトル
+ :param string $message: オプションのエラーメッセージ
- Displays a formatted error message and exits the application with status
- code 1
+ 整形されたエラーメッセージを表示し、ステータスコード 1 でアプリケーション
+ を終了する。
.. php:method:: getOptionParser()
- Should return a :php:class:`ConsoleOptionParser` object, with any
- sub-parsers for the shell.
+ :php:class:`ConsoleOptionParser` オブジェクトを、シェルのサブ・パーサが
+ あればそれと共に返すべきである。
.. php:method:: hasMethod($name)
- Check to see if this shell has a callable method by the given name.
+ シェルに与えられた名前を持つ呼び出し可能なメソッドがあるかどうかを調べる。
.. php:method:: hasTask($task)
- Check to see if this shell has a task with the provided name.
+ シェルに与えられた名前を持つタスクがあるかどうかを調べる。
.. php:method:: hr($newlines = 0, $width = 63)
- :param int $newlines: The number of newlines to precede and follow the line.
- :param int $width: The width of the line to draw.
+ :param int $newlines: 線を引く前に置くべき改行の数
+ :param int $width: 線の長さ
- Create a horizontal line preceded and followed by a number of newlines.
+ いくつかの改行の後に水平線を引きます。
.. php:method:: in($prompt, $options = null, $default = null)
- :param string $prompt: The prompt to display to the user.
- :param array $options: An array of valid choices the user can pick from.
- Picking an invalid option will force the user to choose again.
- :param string $default: The default option if there is one.
+ :param string $prompt: 利用者に表示するプロンプト
+ :param array $options: 入力の選択肢。利用者がこの中から選ぶ。無効なオプションを選んだ場合、再度の入力が求められる。
+ :param string $default: もしあれば、これをデフォルトのオプションとする
- This method helps you interact with the user, and create interactive shells.
- It will return the users answer to the prompt, and allows you to provide a
- list of valid options the user can choose from::
+ このメソッドはユーザとの会話を助ける、会話的なシェルを作成します。
+ プロンプトに対するユーザの入力値を返し、またユーザに有効な選択肢を提示します::
in('Red or Green?', array('R', 'G'), 'R');
- The selection validation is case-insensitive.
+ 入力値の検査では、大文字小文字は区別されない。
.. php:method:: initialize()
- Initializes the Shell acts as constructor for subclasses allows
- configuration of tasks prior to shell execution.
+ シェルを初期化し、サブクラスのコンストラクタとして動作する。
+ またシェルの実行に先立って、タスクの設定を行う。
.. php:method:: loadTasks()
- Loads tasks defined in public :php:attr:`Shell::$tasks`
+ :php:attr:`Shell::$tasks` でpublicとして定義されているタスクをロードする。
.. php:method:: nl($multiplier = 1)
- Outputs a number of newlines.
+ :param int $multiplier 改行動作を繰り返す回数
+
+ 指定数の改行を出力します。
.. php:method:: out($message = null, $newlines = 1, $level = Shell::NORMAL)
- :param string $method: The message to print.
- :param integer $newlines: The number of newlines to follow the message.
- :param integer $level: The highest :ref:`shell-output-level` this message
- should display at.
+ :param string $method: 表示するメッセージ
+ :param integer $newlines: メッセージの後に出力する改行の数
+ :param integer $level: このメッセージを表示するべき :ref:`shell-output-level` の最大値
- The primary method for generating output to the user. By using levels, you
- can limit how verbose a shell is. out() also allows you to use colour formatting
- tags, which will enable coloured output on systems that support it. There are
- several built in styles for colouring text, and you can define your own.
+ ユーザへの出力を生成するためのもっとも普通のやり方です。
+ レベルを指定することで、シェルの出力の度合いを制限できます。
+ out()ではカラー出力タグも出力できますので、お使いのシステムが
+ サポートしていれば色付きの出力が行えます。テキストのカラーリング
+ のためにいくつか組み込みのスタイルを持っており、また自分でスタイルを
+ 定義することもできます。
- * ``error`` Error messages.
- * ``warning`` Warning messages.
- * ``info`` Informational messages.
- * ``comment`` Additional text.
- * ``question`` Magenta text used for user prompts
+ * ``error`` エラーメッセージ
+ * ``warning`` 警告メッセージ
+ * ``info`` 情報メッセージ
+ * ``comment`` 追加メッセージ
+ * ``question`` マゼンタのテキスト。ユーザへのプロンプトに使われます。
- By formatting messages with style tags you can display styled output::
+ スタイルタグでメッセージを書式化することにより、スタイルを適用した
+ 出力が行えます::
out('This will remove data from the filesystems.');
+ $this->out('これはファイルシステムからデータを消去します.');
- By default on \*nix systems ConsoleOutput objects default to colour output.
- On windows systems, plain output is the default unless the ``ANSICON`` environment
- variable is present.
+ \*nixシステムのデフォルトでは、ConsoleOutputオブジェクトのデフォルトは
+ カラー出力です。Windowsシステムでは、 ``ANSICON`` 環境変数が存在しない
+ 限りはプレインテキスト出力がデフォルトです。
.. php:method:: runCommand($command, $argv)
- Runs the Shell with the provided argv.
+ 指定された引数によりシェルを実行する。
- Delegates calls to Tasks and resolves methods inside the class. Commands
- are looked up with the following order:
+ タスクへの呼び出しを代行し、クラス内部のメソッドを解決します。
+ コマンドは以下の順序で検索されます:
- - Method on the shell.
- - Matching task name.
- - main() method.
+ - シェル上のメソッド
+ - タスク名とのマッチング
+ - main()メソッド
- If a shell implements a main() method, all missing method calls will be
- sent to main() with the original method name in the argv.
+ シェルがmain()メソッドを実装していれば、メソッドの呼び出しに失敗した
+ ものはすべて、argvに元々のメソッド名を入れた形でmain()に送られます。
.. php:method:: shortPath($file)
- Makes absolute file path easier to read.
+ ファイルの絶対パスを読みやすくする。
.. php:method:: startup()
- Starts up the Shell and displays the welcome message. Allows for checking
- and configuring prior to command or main execution
+ シェルを開始してウェルカムメッセージを表示する。コマンドやmainの実行に
+ 先立ってチェックや設定を可能とする。
- Override this method if you want to remove the welcome information, or
- otherwise modify the pre-command flow.
+ ウェルカム情報を出力したくない場合は、このメソッドをオーバーライドします。
+ そうしない場合、そこまでのコマンドの流れを変更します。
.. php:method:: wrapText($text, $options = array())
- Wrap a block of text. Allows you to set the width, and indenting on a
- block of text.
+ テキストブロックを折り返す。幅とインデント文字列を設定できる。
- :param string $text: The text to format
+ :param string $text: 整形するテキスト
:param array $options:
- * ``width`` The width to wrap to. Defaults to 72
- * ``wordWrap`` Only wrap on words breaks (spaces) Defaults to true.
- * ``indent`` Indent the text with the string provided. Defaults to null.
+ * ``width`` 折り返し幅。デフォルトは72。
+ * ``wordWrap`` 単語の区切り(スペース)のみで折り返す。デフォルトは真。
+ * ``indent`` 指定された文字列でインデントする。デフォルトはnull。
-More topics
-===========
+さらなるトピック
+================
.. toctree::
:maxdepth: 1
diff --git a/ja/contributing/cakephp-coding-conventions.rst b/ja/contributing/cakephp-coding-conventions.rst
index c1365f7f74..a289c77d72 100644
--- a/ja/contributing/cakephp-coding-conventions.rst
+++ b/ja/contributing/cakephp-coding-conventions.rst
@@ -12,8 +12,8 @@ Cakeの開発者は以下のコーディング規約を使います。
新しい機能の追加
================
-新しい機能は、そのテストが無い限り、追加してはなりません。
-このテストはレポジトリにコミットされる前に合格する必要があります。
+新しい機能は、そのテストが無い限り、追加してはいけません。
+このテストはレポジトリにコミットされる前にパスする必要があります。
インデント
==========
@@ -31,11 +31,11 @@ Cakeの開発者は以下のコーディング規約を使います。
または::
$booleanVariable = true;
- $stringVariable = "大鹿";
+ $stringVariable = '大鹿';
if ($booleanVariable) {
- echo "真偽値はtrueです";
- if ($stringVariable == "大鹿") {
- echo "大鹿に遭遇しました";
+ echo '真偽値はtrueです';
+ if ($stringVariable === '大鹿') {
+ echo '大鹿に遭遇しました';
}
}
@@ -55,7 +55,7 @@ Cakeの開発者は以下のコーディング規約を使います。
* 制御構造では1個の空白が最初の丸括弧の前に、1個の空白が最後の丸括弧と開き中括弧の間にある必要があります。
* 制御構造では、必要でなくとも常に中括弧を使います。
- これはコードの可読性を高め、論理エラーが稀になります。
+ これはコードの可読性を高め、論理エラーが発生しにくくなります。
* 開き中括弧は制御構造と同じ行に置かれる必要があります。
閉じ中括弧は新しい行に置かれ、制御構造と同じレベルのインデントがされている必要があります。
中括弧内に含まれているステートメントは新しい行で始まり、その中に含まれるコードは、新しいレベルのインデントが付けられる必要があります。
@@ -101,6 +101,49 @@ Cakeの開発者は以下のコーディング規約を使います。
//ネストされた三項はダメ
$variable = isset($options['variable']) ? isset($options['othervar']) ? true : false : false;
+
+ビューファイル
+--------------
+
+ビューファイル(拡張子が .ctp のファイル)内では、開発者は、キーワードの制御構造を使用する必要があります。
+キーワードの制御構造を使うと、複雑なビューファイルが読みやすくなります。
+制御構造は、大きいPHPブロック内、または別々のPHPタグに含めることができます::
+
+ You are the admin user.';
+ endif;
+ ?>
+
The following is also acceptable:
+
+
You are the admin user.
+
+
+
+比較
+====
+
+値の比較は、常に可能な限り厳密に行うようにしてください。もし厳格でないテストが意図的なものであれば、
+混乱を避けるためにコメントを残しておいたほうがいいかもしれません。
+
+変数がnullかどうかのテストの場合は、厳密なチェックを使用することを推奨します::
+
+ if ($value === null) {
+ // ...
+ }
+
+チェック対象の値は右側に配置してください::
+
+ // 非推奨
+ if (null === $this->foo()) {
+ // ...
+ }
+
+ // 推奨
+ if ($this->foo() === null) {
+ // ...
+ }
+
関数の呼び出し
==============
@@ -114,9 +157,9 @@ Cakeの開発者は以下のコーディング規約を使います。
メソッドの定義
==============
-関数の定義の例::
+メソッドの定義の例::
- function someFunction($arg1, $arg2 = '') {
+ public function someFunction($arg1, $arg2 = '') {
if (expr) {
statement;
}
@@ -126,7 +169,7 @@ Cakeの開発者は以下のコーディング規約を使います。
デフォルトを用いた引数は、関数の定義の最後に置く必要があります。
関数は何かを、少なくともtrueかfalseを、関数呼び出しが成功したかどうかを判定できるように、返すように作ってみてください::
- function connection($dns, $persistent = false) {
+ public function connection($dns, $persistent = false) {
if (is_array($dns)) {
$dnsInfo = $dns;
} else {
@@ -134,13 +177,52 @@ Cakeの開発者は以下のコーディング規約を使います。
}
if (!($dnsInfo) || !($dnsInfo['phpType'])) {
- return $this=>addError();
+ return $this->addError();
}
return true;
}
イコール記号の両サイドには空白を置きます。
+タイプヒンティング
+------------------
+
+オブジェクトや配列を期待する引数はタイプヒンティングを指定することができます。
+しかしながらタイプヒンティングはコストフリーではないので、publicメソッドにだけ指定します::
+
+ /**
+ * メソッドの説明。
+ *
+ * @param Model $Model 使用するモデル。
+ * @param array $array 配列。
+ * @param boolean $boolean 真偽値。
+ */
+ public function foo(Model $Model, array $array, $boolean) {
+ }
+
+ここで ``$Model`` は ``Model`` のインスタンスで、また ``$array`` は ``array`` でなければなりません。
+
+ちなみに、もし ``$array`` が ``ArrayObject`` のインスタンスでも受け付けるようにしたい場合は、
+``array`` のタイプヒントを指定してプリミティブ型だけを受け入れるようにするべきではありません。::
+
+ /**
+ * メソッドの説明。
+ *
+ * @param array|ArrayObject $array 配列。
+ */
+ public function foo($array) {
+ }
+
+メソッドチェーン
+================
+
+メソッドチェーンは複数の行にまたがる複数のメソッドとなり、単一のタブでインデントする必要があります::
+
+ $email->from('foo@example.com')
+ ->to('bar@example.com')
+ ->subject('A great message')
+ ->send();
+
コードのコメント
================
@@ -148,7 +230,6 @@ Cakeの開発者は以下のコーディング規約を使います。
コメントは以下の `phpDocumentor `_ タグを含めることができます:
-* `@access `_
* `@author `_
* `@copyright `_
* `@deprecated `_
@@ -167,6 +248,7 @@ PhpDocタグはJavaのJavaDocタグによく似ています。
/**
* タグの例。
+ *
* @author このタグは解析されますが、この@versionは無視されます
* @version 1.0 このタグも解析されます
*/
@@ -177,12 +259,16 @@ PhpDocタグはJavaのJavaDocタグによく似ています。
* インラインphpDocタグの例。
*
* この関数は世界征服のためにfoo()を使って身を粉にして働きます。
+ *
+ * @return void
*/
function bar() {
}
/**
- * Foo function
+ * Foo function.
+ *
+ * @return void
*/
function foo() {
}
@@ -192,6 +278,16 @@ PhpDocタグはJavaのJavaDocタグによく似ています。
ファイルの読み込み
==================
+``include`` 、 ``require`` 、 ``include_once`` そして ``require_once`` は括弧を付けません::
+
+ // 間違い = 括弧あり
+ require_once('ClassFileName.php');
+ require_once ($class);
+
+ // よろしい = 括弧なし
+ require_once 'ClassFileName.php';
+ require_once $class;
+
クラスまたはライブラリを伴うファイルを読み込む場合、
`require\_once `_
関数のみを常に使用してください。
@@ -199,7 +295,7 @@ PhpDocタグはJavaのJavaDocタグによく似ています。
PHPタグ
=======
-常にショートタグ( ?>)の代わりに、ロングタグ(````)を使ってください。
+常にショートタグ(`` ?>``)の代わりに、ロングタグ(````)を使ってください。
命名規約
========
@@ -225,7 +321,7 @@ PHPタグ
変数名はできる限り説明的に、しかしできる限り短くもしてください。
通常の変数は小文字で始まり、複数の単語の場合はキャメルバックで書く必要があります。
-オブジェクトを含む変数は大文字で始まり、何らかの方法で変数がオブジェクトとなっているクラスに関連したものになるべきです。
+オブジェクトを参照する変数は大文字で始まり、何らかの方法で変数がオブジェクトとなっているクラスに関連したものになるべきです。
例::
$user = 'John';
@@ -237,7 +333,7 @@ PHPタグ
--------------------------------
メソッドと変数の為の、PHP5のprivateとprotectedキーワードを使用してください。
-加えて、protectedなメソッドまたは変数の名前は単一のアンダースコア("\_")から始まります。
+加えて、protectedなメソッドまたは変数の名前は単一のアンダースコア(``_``)から始まります。
例::
class A {
@@ -248,7 +344,7 @@ PHPタグ
}
}
-privateなメソッドまたは変数の名前は二つののアンダースコア("\_\_")から始まります。
+privateなメソッドまたは変数の名前は二つののアンダースコア(``__``)から始まります。
例::
class A {
@@ -263,17 +359,6 @@ privateなメソッドまたは変数を回避し、protectedなそれらを用
後者はサブクラスからアクセスや修正が可能です。一方で、privateでは拡張や再利用ができません。
privateは、テストの実施もより難しくなります。
-
-メソッドチェーン
-----------------
-
-メソッドチェーンは複数の行にまたがる複数のメソッドとなり、単一のタブでインデントする必要があります::
-
- $email->from('foo@example.com')
- ->to('bar@example.com')
- ->subject('A great message')
- ->send();
-
アドレスの例示
--------------
@@ -284,14 +369,12 @@ privateは、テストの実施もより難しくなります。
* WWW: `http://www.example.com `_
* FTP: `ftp://ftp.example.com `_
-``example.com`` ドメインはこの(:rfc:`2606` をみてください)為に予約されており、ドキュメント中か例として使うことが推奨されています。
+"example.com" ドメインはこの(:rfc:`2606` をみてください)為に予約されており、ドキュメント内の説明や例として使うことが推奨されています。
ファイル
--------
-クラスを含まないファイルの名前は、小文字でアンダースコア化される必要があります。例:
-
-::
+クラスを含まないファイルの名前は、小文字でアンダースコア化される必要があります。例::
long_file_name.php
@@ -304,34 +387,60 @@ privateは、テストの実施もより難しくなります。
説明
mixed
未定義(または複数)の型の変数。
-integer
+int
Integer型の変数(整数)。
float
Float型(小数点数)。
-boolean
+bool
論理型(trueまたはfalse)。
string
文字列型(""か' 'に入る値)。
+null
+ Null型。他の型と一緒に使用することが多いでしょう。
array
配列型。
object
- オブジェクト型。
+ オブジェクト型。可能なら特定のクラス名を指定するべきです。
resource
リソース型(例えばmysql\_connect()による返り値)。
型をmixedに指定する場合、不明(*unknown*)なのか、取りうる型が何なのかを指し示すべきということを覚えていてください。
+callable
+ 呼び出し可能な関数。
+
+パイプ文字によって複数の型を指定することができます。::
+
+ int|bool
+
+ふたつ以上の型の場合は ``mixed`` を指定するのが良いでしょう。
+
+キャスト
+--------
+
+次のキャストを使用します:
+
+型
+ 説明
+(bool)
+ booleanにキャスト。
+(int)
+ integerにキャスト。
+(float)
+ floatにキャスト。
+(string)
+ stringにキャスト。
+(array)
+ arrayにキャスト。
+(object)
+ objectにキャスト。
定数
----
-定数は大文字で定義する必要があります。
-
-::
+定数は大文字で定義する必要があります。::
define('CONSTANT', 1);
もし定数の名前が複数の単語でできている場合は、アンダースコア文字によって分割する必要があります。
-例:
-
-::
+例::
define('LONG_NAMED_CONSTANT', 2);
diff --git a/ja/controllers.rst b/ja/controllers.rst
index 3434f15375..15ec7bfff8 100755
--- a/ja/controllers.rst
+++ b/ja/controllers.rst
@@ -184,13 +184,7 @@ CakePHPのコントローラは、リクエストのライフサイクル周り
You have selected icing for the cake.
:php:meth:`~Controller::set()` メソッドは最初のパラメータに連想配列も指定できます。
- この方法はデータのかたまりを簡単にビューに割り当てる方法としてよく使われます。
-
- .. versionchanged:: 1.3
- 配列のキーは、ビューに渡される時に単語変化しなくなりました。
- ('underscored\_key' は 'underscoredKey' とはなりません):
-
- ::
+ この方法はデータのかたまりを簡単にビューに割り当てる方法としてよく使われます。 ::
$data = array(
'color' => 'pink',
diff --git a/ja/core-libraries/helpers/html.rst b/ja/core-libraries/helpers/html.rst
index bcc181eaf3..f0943a7bfe 100644
--- a/ja/core-libraries/helpers/html.rst
+++ b/ja/core-libraries/helpers/html.rst
@@ -948,7 +948,7 @@ HtmlHelper を使ったパンくずリストの作成
以下のコードを加えたとします。::
$this->Html->addCrumb('ユーザー', '/users');
- $this->Html->addCrumb('ユーザーの追加', '/users/add');
+ $this->Html->addCrumb('ユーザーの追加', array('controller' => 'users', 'action' => 'add'));
すると、レイアウトで ``getCrumbs`` を書いたたところに、
"**Home > ユーザー > ユーザーの追加**" というパンくずリストが追加されます。
diff --git a/ja/core-utility-libraries/security.rst b/ja/core-utility-libraries/security.rst
index 899ba09f52..f64376952a 100644
--- a/ja/core-utility-libraries/security.rst
+++ b/ja/core-utility-libraries/security.rst
@@ -76,15 +76,6 @@ Security API
//デフォルトのハッシュアルゴリズムを利用する場合
$hash = Security::hash('CakePHP Framework');
-.. php:staticmethod:: inactiveMins( )
-
- :rtype: integer
-
- セキュリティレベルに基づいた未操作の許容時間(単位:分)を返します。\ ::
-
- $mins = Security::inactiveMins();
- // Security.level を 'medium' にしていた場合、$mins は 100 となります。
-
.. php:staticmethod:: setHash( $hash )
:rtype: void
diff --git a/ja/core-utility-libraries/set.rst b/ja/core-utility-libraries/set.rst
index 5343d47e43..99543d7a08 100755
--- a/ja/core-utility-libraries/set.rst
+++ b/ja/core-utility-libraries/set.rst
@@ -746,7 +746,7 @@ Set互換のパス記法
より詳しくSet::extract()について学ぶには、``/lib/Cake/Test/Case/Utility/SetTest.php`` の中のtextExcract()関数を参照してください。
-.. php:staticmethod:: filter($var, $isArray = null)
+.. php:staticmethod:: filter($var)
:rtype: array
diff --git a/ja/development/testing.rst b/ja/development/testing.rst
index 4ad48868cb..af84a9366b 100644
--- a/ja/development/testing.rst
+++ b/ja/development/testing.rst
@@ -298,7 +298,7 @@ CakePHPはフィクスチャに基づいたテストケースを実行するに
フィクスチャを作成するときは主にふたつのことを定義します。ひとつはどのようなフィールドを持った
テーブルを作成するか、もうひとつは初期状態でどのようなレコードをテーブルに配置するかです。
それでは最初のフィクスチャを作成してみましょう。この例ではArticleモデルのフィクスチャを作成します。
-``app/Test/Fixture`` というディレクトリに ``app/Test/Fixture`` という名前のファイルを作成し、
+``app/Test/Fixture`` というディレクトリに ``ArticleFixture.php`` という名前のファイルを作成し、
以下のとおりに記述してください。::
class ArticleFixture extends CakeTestFixture {
diff --git a/ja/installation/advanced-installation.rst b/ja/installation/advanced-installation.rst
index 1d1511006c..3f44333013 100644
--- a/ja/installation/advanced-installation.rst
+++ b/ja/installation/advanced-installation.rst
@@ -38,7 +38,7 @@ CakePHPアプリケーションのための composer.json ファイルは次の
}
],
"require": {
- "pear-cakephp/cakephp": ">=2.3.4"
+ "cakephp/cakephp": ">=2.4.9"
},
"config": {
"vendor-dir": "Vendor/"
@@ -73,7 +73,7 @@ composerの実行が終わると、ディレクトリ構造は次のようにな
define(
'CAKE_CORE_INCLUDE_PATH',
- ROOT . DS . APP_DIR . '/Vendor/pear-pear.cakephp.org/CakePHP'
+ ROOT . '/Vendor/pear-pear.cakephp.org/CakePHP'
);
composerで他のライブラリをインストールしている場合は、
diff --git a/ja/models/virtual-fields.rst b/ja/models/virtual-fields.rst
index 6c8a61b2df..e6b4f62010 100644
--- a/ja/models/virtual-fields.rst
+++ b/ja/models/virtual-fields.rst
@@ -44,7 +44,7 @@
PostgreSQLだと、以下のようになります。 ::
public $virtualFields = array(
- 'name' => 'User.first_name || \' \' || User.last_name'
+ 'name' => 'User.first_name || ' ' || User.last_name'
);
..
diff --git a/ja/tutorials-and-examples/blog-auth-example/auth.rst b/ja/tutorials-and-examples/blog-auth-example/auth.rst
index c891d57af7..4bcf5b12ae 100644
--- a/ja/tutorials-and-examples/blog-auth-example/auth.rst
+++ b/ja/tutorials-and-examples/blog-auth-example/auth.rst
@@ -202,6 +202,8 @@ AuthComponentに認証されていないユーザーがusersのadd関数にア
``app/Model/User.php`` のモデルファイルを開いて、以下のものを追加してください::
// app/Model/User.php
+
+ App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
@@ -272,7 +274,7 @@ AuthComponentに認証されていないユーザーがusersのadd関数にア
}
}
-Authコンポーネントの ``users()`` 関数は現在ログインしているユーザーから全てのカラムを返します。
+Authコンポーネントの ``user()`` 関数は現在ログインしているユーザーから全てのカラムを返します。
このメソッドを使って、保存されるリクエストデータにそのデータを追加します。
誰かが他の著者の投稿を編集したり削除したりするのを防ぐように、アプリケーションをセキュアにしましょう。
@@ -337,7 +339,7 @@ PostsControllerに追加しようとしているルールは投稿の作成を
// app/Model/Post.php
public function isOwnedBy($post, $user) {
- return $this->field('id', array('id' => $post, 'user_id' => $user)) === $post;
+ return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false;
}
これはシンプルな認証と承認のチュートリアルのまとめとなります。
diff --git a/ja/tutorials-and-examples/blog/part-two.rst b/ja/tutorials-and-examples/blog/part-two.rst
index 299f39a1aa..032c132ed8 100644
--- a/ja/tutorials-and-examples/blog/part-two.rst
+++ b/ja/tutorials-and-examples/blog/part-two.rst
@@ -174,6 +174,7 @@ http://www.example.com/posts/index
もしそういう表示が出ない場合には、何かおかしくなってしまったか、もうすでにあなたがその定義作業をしてしまったから(仕事がハヤイ!)か、のどちらかです。
そうでないなら、これからPostsControllerの中に作ってみましょう::
+ // File: /app/Controller/PostsController.php
class PostsController extends AppController {
public $helpers = array('Html', 'Form');
diff --git a/pt/controllers/scaffolding.rst b/pt/controllers/scaffolding.rst
index b7ff5163fb..bc2eb461fb 100644
--- a/pt/controllers/scaffolding.rst
+++ b/pt/controllers/scaffolding.rst
@@ -130,7 +130,7 @@ pode criar templates. Continuamos a não recomendar o uso desta técnica para
aplicações em produção, mas tal customização pode ser útil durante o período de
prototipação.
-A customização é feita criando templates de view::
+A customização é feita criando templates de view:
Views de `scaffold` customizadas para um controller específico (PostsController
neste example) devem ser colocadas no diretório das views desta maneira::
diff --git a/pt/getting-started/cakephp-structure.rst b/pt/getting-started/cakephp-structure.rst
index 78c9aff1cc..a664326f88 100644
--- a/pt/getting-started/cakephp-structure.rst
+++ b/pt/getting-started/cakephp-structure.rst
@@ -19,8 +19,8 @@ incluir mudanças válidas por toda a aplicação. As classes AppController
``/app/Model/AppModel.php``) são excelentes lugares para colocar métodos que
você quer compartilhar entre todos os controllers, helpers ou models.
-Embora não sejam classes ou arquivos, as rotas desempenhar um papel na
-requisição feita para o CakePHP. Definições de rotas dizem ao CakePHP como
+Embora rotas não sejam classes ou arquivos, elas desempenham um papel nas
+requisições feitas ao CakePHP. Definições de rotas dizem ao CakePHP como
mapear URLs para as ações de controllers. O comportamento padrão assume que a
URL ``/controller/action/var1/var2`` deve ser mapeada para o método
Controller::action($var1, $var2), mas você pode usar as rotas para customizar as
diff --git a/pt/tutorials-and-examples.rst b/pt/tutorials-and-examples.rst
index 4859599cd3..e90436794a 100644
--- a/pt/tutorials-and-examples.rst
+++ b/pt/tutorials-and-examples.rst
@@ -10,7 +10,6 @@ plugins para o CakePHP `CakePackages `_ ou a
existentes.
.. toctree::
- :glob:
:maxdepth: 1
tutorials-and-examples/blog/blog
diff --git a/ro/cakephp-overview/ what-is-cakephp-why-use-it.rst b/ro/cakephp-overview/what-is-cakephp-why-use-it.rst
similarity index 100%
rename from ro/cakephp-overview/ what-is-cakephp-why-use-it.rst
rename to ro/cakephp-overview/what-is-cakephp-why-use-it.rst
diff --git a/ro/index.rst b/ro/index.rst
index 30841322f1..8771781325 100644
--- a/ro/index.rst
+++ b/ro/index.rst
@@ -16,11 +16,12 @@ corecții la documentație.
.. container:: offline-download
-**Citiți cartea oriunde**
+ **Citiți cartea oriunde**
+
+ Bucurați-vă de documentația CakePHP aproape oriunde. Fiind disponibilă atât ca
+ un PDF cat și ca EPUB, o puteți citi acum pe mai multe dispozitive și chiar
+ offline.
-Bucurați-vă de documentația CakePHP aproape oriunde. Fiind disponibilă atât ca
-un PDF cat și ca EPUB, o puteți citi acum pe mai multe dispozitive și chiar
-offline.
- `PDF <../_downloads/en/CakePHPCookbook.pdf>`_
- `EPUB <../_downloads/en/CakePHPCookbook.epub>`_
- `Sursa originala `_
diff --git a/ro/installation.rst b/ro/installation.rst
index 23065c9c46..fef2380a1f 100644
--- a/ro/installation.rst
+++ b/ro/installation.rst
@@ -23,7 +23,7 @@ baze de date:
- Microsoft SQL Server
- SQLite
-.. atentie::
+.. note::
Toate driverele incluse in distributiile de servere necesita PDO.
Prin urmare ar trebui sa va asigurati ca aveti instalate extensiile
diff --git a/ru/controllers/components.rst b/ru/controllers/components.rst
index c3946ca25e..e758ff18b0 100644
--- a/ru/controllers/components.rst
+++ b/ru/controllers/components.rst
@@ -88,7 +88,7 @@ options each component provides.
Необходимо проследить чтобы Компонент и Модель имели разные имена.
Загрузка компонентов 'на лету'
------------------------------
+------------------------------
Часто бывает, что Компонент не требуется в каждом контроллере. В данной ситуации
вы можете загрузить компонент 'на лету' используя
diff --git a/sr/_static/img/basic_mvc.png b/sr/_static/img/basic_mvc.png
new file mode 100644
index 0000000000..099d13461e
Binary files /dev/null and b/sr/_static/img/basic_mvc.png differ
diff --git a/sr/_static/img/code-coverage.png b/sr/_static/img/code-coverage.png
new file mode 100644
index 0000000000..5eff05469a
Binary files /dev/null and b/sr/_static/img/code-coverage.png differ
diff --git a/sr/_static/img/typical-cake-request.png b/sr/_static/img/typical-cake-request.png
new file mode 100644
index 0000000000..f951d36196
Binary files /dev/null and b/sr/_static/img/typical-cake-request.png differ
diff --git a/sr/appendices.rst b/sr/appendices.rst
new file mode 100644
index 0000000000..fa818df38c
--- /dev/null
+++ b/sr/appendices.rst
@@ -0,0 +1,71 @@
+Appendices
+##########
+
+Appendices contain information regarding the new features
+introduced in 2.x, and the migration path from 1.3 to 2.0.
+
+2.4 Migration Guide
+===================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/2-4-migration-guide
+
+2.3 Migration Guide
+===================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/2-3-migration-guide
+
+2.2 Migration Guide
+===================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/2-2-migration-guide
+
+2.1 Migration Guide
+===================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/2-1-migration-guide
+ appendices/new-features-in-cakephp-2-1
+
+2.0 Migration Guide
+===================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/2-0-migration-guide
+ appendices/new-features-in-cakephp-2-0
+ appendices/phpunit-migration-hints
+
+Migration from 1.2 to 1.3
+=========================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/migrating-from-cakephp-1-2-to-1-3
+ appendices/new-features-in-cakephp-1-3
+
+General Information
+===================
+
+.. toctree::
+ :maxdepth: 1
+
+ appendices/cakephp-development-process
+ appendices/glossary
+
+
+.. meta::
+ :title lang=en: Appendices
+ :keywords lang=en: migration guide,migration path,new features,glossary
diff --git a/sr/appendices/2-0-migration-guide.rst b/sr/appendices/2-0-migration-guide.rst
new file mode 100644
index 0000000000..4e079c23f8
--- /dev/null
+++ b/sr/appendices/2-0-migration-guide.rst
@@ -0,0 +1,1292 @@
+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 :ref:`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
+https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md. 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
+===================================
+
+:php:func:`__()` (Double underscore shortcut function) always returns the translation
+(not echo anymore).
+
+If you want to echo the result of the translation, use::
+
+ echo __('My Message');
+
+This change includes all shortcut translation methods::
+
+ __()
+ __n()
+ __d()
+ __dn()
+ __dc()
+ __dcn()
+ __c()
+
+Alongside this, if you pass additional parameters, the translation will call
+`sprintf `_ with these
+parameters before returning. For example::
+
+ // 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 `_ 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::
+
+ 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::
+
+ 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::
+
+ 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::
+
+ $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 :doc:`/core-libraries/components/authentication` guide.
+
+EmailComponent
+--------------
+
+The EmailComponent has been deprecated and has created a new library class to
+send e-mails. See :doc:`/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
+:doc:`/development/exceptions` and :doc:`/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::
+
+ 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
+:php:meth:`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 :php:meth:`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 :php:meth:`App::uses()` when migrating from
+:php:meth:`App::import()`::
+
+ 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::
+
+ 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 :php:meth:`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
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+:php:meth:`App::build()` will not merge app paths with core paths anymore.
+
+Examples::
+
+ 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 :php:class:`CakeLogInterface`. Exceptions will be raised
+ if a configured logger does not.
+
+Cache
+-----
+
+- :php:class:`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.
+
+::
+
+ 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::
+
+ 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::
+
+ 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
+ :ref:`loading-configuration-files` for more information.
+- ``Configure::store()`` now writes values to a given Cache configuration. Read
+ :ref:`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 :php:class:`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 :doc:`see the session section for more
+information `
+
+HttpSocket
+----------
+
+- HttpSocket doesn't change the header keys. Following other places in core,
+ the HttpSocket does not change the headers. :rfc:`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 :php:class:`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::
+
+ 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
+:doc:`/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 :php:class:`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::
+
+ $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::
+
+ $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 :doc:`/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. :php:meth:`Controller::paginate()` still
+exists, and serves as a convenience method for loading and using the
+:php:class:`PaginatorComponent`.
+
+For more information on the new features offered by pagination in 2.0, see the
+:doc:`/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 :php:class:`Helper`
+- ``View::$modelId`` has been removed. This behavior is now on
+ :php:class:`Helper`
+- ``View::$association`` has been removed. This behavior is now on
+ :php:class:`Helper`
+- ``View::$fieldSuffix`` has been removed. This behavior is now on
+ :php:class:`Helper`
+- ``View::entity()`` has been removed. This behavior is now on
+ :php:class:`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 :php:class:`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::
+
+ 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. :doc:`Read more about those
+changes `.
+
+CacheHelper decoupled
+---------------------
+
+In previous versions there was a tight coupling between :php:class:`CacheHelper`
+and :php:class:`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::
+
+ 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
+-----------------
+
+:php:func:`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.5. 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.
+
+Models
+======
+
+Model relationships are now lazy loaded. You can run into a situation where
+assigning a value to a nonexistent model property will throw errors::
+
+ $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::
+
+ $Post->nonexistentProperty = array();
+ $Post->nonexistentProperty[] = 'value';
+
+Or just declare the property in the model class::
+
+ 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::
+
+ public function execute($sql, $params = array(), $options = array())
+
+ became::
+
+ 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::
+
+ $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::
+
+ public $actsAs = array(
+ 'Acl' => 'Controlled',
+ 'Tree' => 'nested'
+ );
+
+ became::
+
+ 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::
+
+ 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::
+
+ 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::
+
+ public $default = array(
+ 'datasource' => 'Database/Mysql',
+ 'persistent' => false,
+ 'host' => 'localhost',
+ 'login' => 'root',
+ 'password' => 'root',
+ 'database' => 'cake',
+ );
+
+
+.. meta::
+ :title lang=en: 2.0 Migration Guide
+ :description lang=en: 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.
+ :keywords lang=en: cakephp upgrade,cakephp migration,migration guide,1.3 to 2.0,update cakephp,backwards compatibility,api changes,x versions,directory structure,new features
diff --git a/sr/appendices/2-1-migration-guide.rst b/sr/appendices/2-1-migration-guide.rst
new file mode 100644
index 0000000000..759be4a36c
--- /dev/null
+++ b/sr/appendices/2-1-migration-guide.rst
@@ -0,0 +1,363 @@
+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::
+
+ // 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 :php:attr:`Model::$useDbConfig` you should also
+ modify ``schemaName`` or use :php:meth:`Model::setDataSource()` method which
+ handles this for you.
+
+CakeSession
+-----------
+
+.. versionchanged:: 2.1.1
+ CakeSession no longer sets the P3P header, as this is the responsibility of your application.
+ More info see ticket `#2515 `_ in lighthouse
+
+Behaviors
+=========
+
+TranslateBehavior
+-----------------
+
+- :php:class:`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
+--------
+
+- :php:func:`Debugger::getType()` has been added. It can be used to get the type of
+ variables.
+- :php:func:`Debugger::exportVar()` has been modified to create more readable
+ and useful output.
+
+debug()
+-------
+
+`debug()` now uses :php:class:`Debugger` internally. This makes it consistent
+with Debugger, and takes advantage of improvements made there.
+
+Set
+---
+
+- :php:func:`Set::nest()` has been added. It takes in a flat array and returns a nested array
+
+File
+----
+
+- :php:meth:`File::info()` includes filesize & mimetype information.
+- :php:meth:`File::mime()` was added.
+
+Cache
+-----
+
+- :php:class:`CacheEngine` has been moved into a separate file.
+
+Configure
+---------
+
+- :php:class:`ConfigReaderInterface` has been moved into a separate file.
+
+App
+---
+
+- :php:meth:`App::build()` now has the ability to register new packages using
+ ``App::REGISTER``. See :ref:`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 :ref:`connecting-routes` for
+ more information.
+- :php:meth:`Router::resourceMap()` was added.
+- :php:meth:`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 :php:meth:`CakeResponse::cookie()` for setting cookies.
+- Added a number of methods for :ref:`cake-response-caching`
+
+Controller
+==========
+
+Controller
+----------
+
+- :php:attr:`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
+-------------
+
+- :php:meth:`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
+------------
+
+- :php:class:`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``.
+- :php:class:`DbAcl` has been moved into a separate file.
+- :php:class:`IniAcl` has been moved into a separate file.
+- :php:class:`AclInterface` has been moved into a separate file.
+
+Helpers
+=======
+
+TextHelper
+----------
+
+- :php:meth:`TextHelper::autoLink()`, :php:meth:`TextHelper::autoLinkUrls()`,
+ :php:meth:`TextHelper::autoLinkEmails()` now HTML escape their input by
+ default. You can control this with the ``escape`` option.
+
+HtmlHelper
+----------
+
+- :php:meth:`HtmlHelper::script()` had a ``block`` option added.
+- :php:meth:`HtmlHelper::scriptBlock()` had a ``block`` option added.
+- :php:meth:`HtmlHelper::css()` had a ``block`` option added.
+- :php:meth:`HtmlHelper::meta()` had a ``block`` option added.
+- The ``$startText`` parameter of :php:meth:`HtmlHelper::getCrumbs()` can now be
+ an array. This gives more control and flexibility over the first crumb link.
+- :php:meth:`HtmlHelper::docType()` now defaults to HTML5.
+- :php:meth:`HtmlHelper::image()` now has a ``fullBase`` option.
+- :php:meth:`HtmlHelper::media()` has been added. You can use this method to
+ create HTML5 audio/video elements.
+- :term:`plugin syntax` support has been added for
+ :php:meth:`HtmlHelper::script()`, :php:meth:`HtmlHelper::css()`, :php:meth:`HtmlHelper::image()`.
+ You can now easily link to plugin assets using ``Plugin.asset``.
+- :php:meth:`HtmlHelper::getCrumbList()` had the ``$startText`` parameter added.
+
+
+View
+====
+
+- :php:attr:`View::$output` is deprecated.
+- ``$content_for_layout`` is deprecated. Use ``$this->fetch('content');``
+ instead.
+- ``$scripts_for_layout`` is deprecated. Use the following instead::
+
+ echo $this->fetch('meta');
+ echo $this->fetch('css');
+ echo $this->fetch('script');
+
+ ``$scripts_for_layout`` is still available, but the :ref:`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 :php:meth:`~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 :php:class:`JsonView`
+and :php:class:`XmlView` allow you to easily generate XML and JSON views. You
+can learn more about these classes in the section on
+:doc:`/views/json-and-xml-views`
+
+Extending views
+---------------
+
+:php:class:`View` has a new method allowing you to wrap or 'extend' a
+view/element/layout with another file. See the section on
+:ref:`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 :ref:`view-blocks` for more information.
+
+
+Helpers
+=======
+
+New callbacks
+-------------
+
+Two new callbacks have been added to Helpers.
+:php:meth:`Helper::beforeRenderFile()` and :php:meth:`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 :php:class:`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 :php:meth:`FormHelper::button()` can be removed now. It still
+ defaults to 'submit'.
+- :php:meth:`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
+---------------
+
+- :php:meth:`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/sr/appendices/2-2-migration-guide.rst b/sr/appendices/2-2-migration-guide.rst
new file mode 100644
index 0000000000..441eb6cfe9
--- /dev/null
+++ b/sr/appendices/2-2-migration-guide.rst
@@ -0,0 +1,327 @@
+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-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::
+
+ // 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
+:php:const:`LOG_ERROR` to :php:const:`LOG_ERR`::
+
+ 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
+ :php:class:`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 :php:class:`NotImplementedException` was added.
+
+
+Core
+====
+
+Configure
+---------
+
+- :php:meth:`Configure::dump()` was added. It is used to persist configuration
+ data in durable storage like files. Both :php:class:`PhpReader` and
+ :php:class:`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 :php:attr:`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 `_ 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 :php:meth:`Security::rijndael()` documentation.
+
+Pagination
+==========
+
+- Paginating custom finders will now return correct counts, see Model changes
+ for more info.
+
+
+Network
+=======
+
+CakeEmail
+---------
+
+- :php:meth:`CakeEmail::charset()` and :php:meth:`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.
+- :php:meth:`CakeEmail::theme()` was added.
+- :php:meth:`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 :php:class:`Set` class is now deprecated, and replaced by the :php:class:`Hash` class.
+ Set will not be removed until 3.0.
+- :php:meth:`Set::expand()` was added.
+
+Hash
+----
+
+The :php:class:`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 :doc:`/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.
+- :php:meth:`CakeTime::timeAgoInWords()` had the ``accuracy`` option added.
+ This option allows you to specify how accurate formatted times should be.
+
+- New methods added:
+
+ * :php:meth:`CakeTime::toServer()`
+ * :php:meth:`CakeTime::timezone()`
+ * :php:meth:`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.
+- :php:meth:`FormHelper::radio()` now supports an ``empty`` which works similar
+ to the empty option on ``select()``.
+- Added :php:meth:`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.
+- :php:meth:`TimeHelper::timeAgoInWords()` has the ``element`` option added.
+ This allows you to specify an HTML element to wrap the formatted time.
+
+HtmlHelper
+----------
+
+- :php:meth:`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
+ :doc:`/development/dispatch-filters`
+- With the addition of :doc:`/development/dispatch-filters` you'll need to
+ update ``app/Config/bootstrap.php``. See
+ :ref:`required-steps-to-upgrade-2-2`.
+
+Router
+------
+
+- :php:meth:`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
+`_ 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::
+
+ 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 :php:meth:`Cache::clearGroup()` class method was added. It takes the group
+name and deletes all entries labeled with the same string.
+
+Log
+===
+
+Changes in :php:class:`CakeLog` now require, some additional configuration in
+your ``app/Config/bootstrap.php``. See :ref:`required-steps-to-upgrade-2-2`,
+and :doc:`/core-libraries/logging`.
+
+- The :php:class:`CakeLog` class now accepts the same log levels as defined in
+ `RFC 5424 `_. Several convenience
+ methods have also been added:
+
+ * :php:meth:`CakeLog::emergency($message, $scope = array())`
+ * :php:meth:`CakeLog::alert($message, $scope = array())`
+ * :php:meth:`CakeLog::critical($message, $scope = array())`
+ * :php:meth:`CakeLog::error($message, $scope = array())`
+ * :php:meth:`CakeLog::warning($message, $scope = array())`
+ * :php:meth:`CakeLog::notice($message, $scope = array())`
+ * :php:meth:`CakeLog::info($message, $scope = array())`
+ * :php:meth:`CakeLog::debug($message, $scope = array())`
+
+- A third argument ``$scope`` has been added to :php:meth:`CakeLog::write`.
+ See :ref:`logging-scopes`.
+- A new log engine: :php:class:`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 :doc:`/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:
+
+ * :php:meth:`Validation::naturalNumber()`
+ * :php:meth:`Validation::mimeType()`
+ * :php:meth:`Validation::uploadError()`
+
diff --git a/sr/appendices/2-3-migration-guide.rst b/sr/appendices/2-3-migration-guide.rst
new file mode 100644
index 0000000000..2c47db0d9c
--- /dev/null
+++ b/sr/appendices/2-3-migration-guide.rst
@@ -0,0 +1,326 @@
+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 :php:const:`CACHE` and :php:const:`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.
+
+- :php:meth:`AuthComponent::redirect()` has been deprecated.
+ Use :php:meth:`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
+-----------------------
+
+- :php:meth:`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
+---------------
+
+- :php:meth:`CookieComponent::check()` was added. This method works the same as
+ :php:meth:`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
+----------
+
+- :php:meth:`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
+---------
+
+- :php:meth:`Configure::check()` was added. This method works the same as
+ :php:meth:`CakeSession::check()` does.
+
+- :php:meth:`ConfigReaderInterface::dump()` was added. Please ensure any custom readers you have now
+ implement a ``dump()`` method.
+
+- The ``$key`` parameter of :php:meth:`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
+-----------
+
+- :php:meth:`CakeRequest::onlyAllow()` was added.
+- :php:meth:`CakeRequest::query()` was added.
+
+CakeResponse
+------------
+
+- :php:meth:`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
+ :php:meth:`CakeEmail::attachments()`. This allows you to disable the
+ Content-Disposition header added to attached files.
+
+HttpSocket
+----------
+
+- :php:class:`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
+ :ref:`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 :php:meth:`Router::url()`.
+
+View
+====
+
+- MediaView is deprecated, and you can use new features in
+ :php:class:`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.
+- :php:meth:`View::fetch()` now has a ``$default`` argument. This argument can
+ be used to provide a default value should a block be empty.
+- :php:meth:`View::prepend()` has been added to allow prepending content to
+ existing block.
+- :php:class:`XmlView` now uses the ``_rootNode`` view variable to customize the
+ top level XML node.
+- :php:meth:`View::elementExists()` was added. You can use this method to check
+ if elements exist before using them.
+- :php:meth:`View::element()` had the ``ignoreMissing`` option added. You can
+ use this to suppress the errors triggered by missing view elements.
+- :php:meth:`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
+----------
+
+- :php:meth:`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.
+- :php:meth:`FormHelper::postLink()` now accepts a ``method`` key. This allows
+ you to create link forms using HTTP methods other than POST.
+- When creating inputs with :php:meth:`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.
+- :php:meth:`FormHelper::input()` now generates input elements of type ``tel``
+ and ``email`` based on field names if ``type`` option is not specified.
+
+HtmlHelper
+----------
+
+- :php:meth:`HtmlHelper::getCrumbList()` now has the ``separator``,
+ ``firstClass`` and ``lastClass`` options. These allow you to better control
+ the HTML this method generates.
+
+TextHelper
+----------
+
+- :php:meth:`TextHelper::tail()` was added to truncate text starting from the end.
+- `ending` in :php:meth:`TextHelper::truncate()` is deprecated in favor of `ellipsis`
+
+PaginatorHelper
+---------------
+
+- :php:meth:`PaginatorHelper::numbers()` now has a new option ``currentTag`` to
+ allow specifying extra tag for wrapping current page number.
+- For methods: :php:meth:`PaginatorHelper::prev()` and :php:meth:`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.
+- :php:meth:`CakeTestCase::getMockForModel()` was added. This simplifies getting
+ mock objects for models.
+
+Utility
+=======
+
+CakeNumber
+----------
+
+- :php:meth:`CakeNumber::fromReadableSize()` was added.
+- :php:meth:`CakeNumber::formatDelta()` was added.
+- :php:meth:`CakeNumber::defaultCurrency()` was added.
+
+Folder
+------
+
+- :php:meth:`Folder::copy()` and :php:meth:`Folder::move()` now support the
+ ability to merge the target and source directories in addition to
+ skip/overwrite.
+
+
+String
+------
+
+- :php:meth:`String::tail()` was added to truncate text starting from the end.
+- `ending` in :php:meth:`String::truncate()` is deprecated in favor of `ellipsis`
+
+Debugger
+--------
+
+- :php:meth:`Debugger::exportVar()` now outputs private and protected properties
+ in PHP >= 5.3.0.
+
+Security
+--------
+
+- Support for `bcrypt `_
+ was added. See the :php:class:`Security::hash()` documentation for more
+ information on how to use bcrypt.
+
+Validation
+----------
+
+- :php:meth:`Validation::fileSize()` was added.
+
+ObjectCollection
+----------------
+
+- :php:meth:`ObjectCollection::attached()` was deprecated in favor of the new
+ method :php:meth:`ObjectCollection::loaded()`. This unifies the access to the
+ ObjectCollection as load()/unload() already replaced attach()/detach().
diff --git a/sr/appendices/2-4-migration-guide.rst b/sr/appendices/2-4-migration-guide.rst
new file mode 100644
index 0000000000..73094f212a
--- /dev/null
+++ b/sr/appendices/2-4-migration-guide.rst
@@ -0,0 +1,294 @@
+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
+------
+
+- :php:meth:`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 :php:attr:`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 :php:class:`AuthComponent` page.
+- Property :php:attr:`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 :ref:`hashing-passwords` for more info.
+
+DbAcl
+-----
+
+- DbAcl now uses ``INNER`` joins instead of ``LEFT`` joins. This improves
+ performance for some database vendors.
+
+Model
+=====
+
+Models
+------
+
+- :php:meth:`Model::save()`, :php:meth:`Model::saveField()`, :php:meth:`Model::saveAll()`,
+ :php:meth:`Model::saveAssociated()`, :php:meth:`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.
+- :php:meth:`Model::clear()` was added.
+
+Datasource
+----------
+
+- Mysql, Postgres, and SQLserver now support a 'settings' array in the
+ connection definition. This key => value pair will be issued as ``SET`` commands when the
+ connection is created.
+- Mysql driver now supports SSL options.
+
+
+View
+====
+
+JsonView
+--------
+
+- JSONP support has been added to :php:class:`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 :php:meth:`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 :php:meth:`HtmlHelper::link()` to control
+ escaping of only link title and not attributes.
+
+TextHelper
+----------
+
+- :php:meth:`TextHelper::autoParagraph()` has been added. It allows to
+ automatically convert text into HTML paragraphs.
+
+PaginatorHelper
+---------------
+
+- :php:meth:`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 :php:meth:`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
+-----------
+
+- :php:meth:`CakeRequest::param()` has been added.
+- :php:meth:`CakeRequest::is()` has been modified to support an array of types and will return true if the request matches any type.
+- :php:meth:`CakeRequest::isAll()` has been added to check that a request matches all the given types.
+
+CakeResponse
+------------
+
+- :php:meth:`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.
+- :php:meth:`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.
+- :php:meth:`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
+----------
+
+- :php:meth:`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 :ref:`FileLog ` engine.
+- In debug mode missing directories will now be automatically created to avoid unnecessary errors thrown.
+
+SyslogLog
+---------
+
+- The new logging engine :ref:`SyslogLog ` 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
+-------
+
+- :php:func:`pr()` no longer outputs HTML when running in cli mode.
+
+Sanitize
+--------
+
+- ``Sanitize`` class has been deprecated.
+
+Validation
+----------
+
+- :php:meth:`Validation::date()` now supports the ``y`` and ``ym`` formats.
+- The country code of :php:meth:`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
+ :php:meth:`CakeNumber::currency()`.
+
+CakeTime
+--------
+
+- :php:meth:`CakeTime::isPast()` and :php:meth:`CakeTime::isFuture()` were
+ added.
+- :php:meth:`CakeTime::timeAgoInWords()` has two new options to customize the output strings:
+ ``relativeString`` (defaults to ``%s ago``) and ``absoluteString`` (defaults to ``on %s``).
+- :php:meth:`CakeTime::timeAgoInWords()` uses fuzzy terms when time is below thresholds.
+
+
+Xml
+---
+
+- New option ``pretty`` has been added to :php:meth:`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
+------
+
+- :php:meth:`Router::fullBaseUrl()` was added together with ``App.fullBaseUrl`` Configure value. They replace
+ :php:const:`FULL_BASE_URL` which is now deprecated.
+- :php:meth:`Router::parse()` now parses query string arguments.
+
+
diff --git a/sr/appendices/cakephp-development-process.rst b/sr/appendices/cakephp-development-process.rst
new file mode 100644
index 0000000000..a2fc2f09b9
--- /dev/null
+++ b/sr/appendices/cakephp-development-process.rst
@@ -0,0 +1,56 @@
+CakePHP Development Process
+###########################
+
+Here we attempt to explain the process we use when developing the
+CakePHP framework. We rely heavily on community interaction through
+tickets and IRC chat. IRC is the best place to find members of the
+`development team `_ and discuss
+ideas, the latest code, and make general comments. If something more
+formal needs to be proposed or there is a problem with a release, the
+ticket system is the best place to share your thoughts.
+
+We currently maintain 4 versions of CakePHP.
+
+- **stable** : Tagged releases intended for production where stability
+ is more important than features. Issues filed against these releases
+ will be fixed in the related branch, and be part of the next release.
+- **maintenance branch** : Development branches become maintenance
+ branches once a stable release point has been reached. Maintenance
+ branches are where all bugfixes are committed before making their way
+ into a stable release. Maintenance branches have the same name as the
+ major version they are for example *1.2*. If you are using a stable
+ release and need fixes that haven't made their way into a stable
+ release check here.
+- **development branches** : Development branches contain leading edge
+ fixes and features. They are named after the version number they are
+ for example *1.3*. Once development branches have reached a stable
+ release point they become maintenance branches, and no further new
+ features are introduced unless absolutely necessary.
+- **feature branches** : Feature branches contain unfinished or
+ possibly unstable features and are recommended only for power users
+ interested in the most advanced feature set and willing to contribute
+ back to the community. Feature branches are named with the following
+ convention *version-feature*. An example would be *1.3-router* Which
+ would contain new features for the Router for 1.3.
+
+Hopefully this will help you understand what version is right for you.
+Once you pick your version you may feel compelled to contribute a bug
+report or make general comments on the code.
+
+- If you are using a stable version or maintenance branch, please submit
+ tickets or discuss with us on IRC.
+- If you are using the development branch or feature branch, the first
+ place to go is IRC. If you have a comment and cannot reach us in IRC
+ after a day or two, please submit a ticket.
+
+If you find an issue, the best answer is to write a test. The best
+advice we can offer in writing tests is to look at the ones included in
+the core.
+
+As always, if you have any questions or comments, visit us at #cakephp
+on irc.freenode.net.
+
+
+.. meta::
+ :title lang=en: CakePHP Development Process
+ :keywords lang=en: maintenance branch,community interaction,community feature,necessary feature,stable release,ticket system,advanced feature,power users,feature set,chat irc,leading edge,router,new features,members,attempt,development branches,branch development
diff --git a/sr/appendices/glossary.rst b/sr/appendices/glossary.rst
new file mode 100644
index 0000000000..80ff5cefc1
--- /dev/null
+++ b/sr/appendices/glossary.rst
@@ -0,0 +1,70 @@
+Glossary
+########
+
+.. glossary::
+
+ routing array
+ An array of attributes that are passed to :php:meth:`Router::url()`.
+ They typically look like::
+
+ array('controller' => 'posts', 'action' => 'view', 5)
+
+ HTML attributes
+ An array of key => values that are composed into HTML attributes. For example::
+
+ // 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::
+
+ // 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::
+
+ 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.
+
+
+.. meta::
+ :title lang=en: Glossary
+ :keywords lang=en: html attributes,array class,array controller,glossary glossary,target blank,dot notation,routing configuration,forgery,replay,router,syntax,config,submissions
diff --git a/sr/appendices/migrating-from-cakephp-1-2-to-1-3.rst b/sr/appendices/migrating-from-cakephp-1-2-to-1-3.rst
new file mode 100644
index 0000000000..5c49c43bd8
--- /dev/null
+++ b/sr/appendices/migrating-from-cakephp-1-2-to-1-3.rst
@@ -0,0 +1,778 @@
+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.
+
+::
+
+ 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::
+
+ 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.
+
+
+#. Move the required layout files into app/views/elements
+#. Rename the $content\_for\_layout variable to $message
+#. 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::
+
+ 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::
+
+ //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-_+]+/``::
+
+ 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::
+
+ 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::
+
+ 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.
+
+::
+
+ // 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 :doc:`/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
+:doc:`/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:
+
+::
+
+ 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 ``