From 9781eada1e906c61a9d0a21bb1a20137466e5669 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Mon, 30 May 2016 15:27:44 +0200 Subject: [PATCH 01/19] Add Middleware chapter to the docs. I think middleware is important enough to be featured as a top level menu item. This means I needed to shift all the menu items down by one. --- en/contents.rst | 1 + en/controllers/middleware.rst | 4 +++ es/contents.rst | 1 + es/controllers/middleware.rst | 15 +++++++++ fr/contents.rst | 1 + fr/controllers/middleware.rst | 17 ++++++++++ ja/controllers/middleware.rst | 17 ++++++++++ pt/contents.rst | 1 + pt/controllers/middleware.rst | 13 ++++++++ themes/cakephp/static/css/default.css | 48 +++++++++++++-------------- tr/controllers/middleware.rst | 13 ++++++++ zh/controllers/middleware.rst | 17 ++++++++++ 12 files changed, 124 insertions(+), 24 deletions(-) create mode 100644 en/controllers/middleware.rst create mode 100644 es/controllers/middleware.rst create mode 100644 fr/controllers/middleware.rst create mode 100644 ja/controllers/middleware.rst create mode 100644 pt/controllers/middleware.rst create mode 100644 tr/controllers/middleware.rst create mode 100644 zh/controllers/middleware.rst diff --git a/en/contents.rst b/en/contents.rst index f578fa6473..637fc8eb69 100644 --- a/en/contents.rst +++ b/en/contents.rst @@ -20,6 +20,7 @@ Contents development/configuration development/routing controllers/request-response + controllers/middleware controllers views orm diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst new file mode 100644 index 0000000000..3605054203 --- /dev/null +++ b/en/controllers/middleware.rst @@ -0,0 +1,4 @@ +Middleware +########## + +TODO write outline. diff --git a/es/contents.rst b/es/contents.rst index 844aa260ac..63e95c0257 100644 --- a/es/contents.rst +++ b/es/contents.rst @@ -20,6 +20,7 @@ Contenidos development/configuration development/routing controllers/request-response + controllers/middleware controllers views orm diff --git a/es/controllers/middleware.rst b/es/controllers/middleware.rst new file mode 100644 index 0000000000..4a5c32d003 --- /dev/null +++ b/es/controllers/middleware.rst @@ -0,0 +1,15 @@ +Middleware +########## + +.. note:: + La documentación no es compatible actualmente con el idioma español en esta página. + + Por favor, siéntase libre de enviarnos un pull request en + `Github `_ o utilizar el botón **Improve this Doc** para proponer directamente los cambios. + + Usted puede hacer referencia a la versión en Inglés en el menú de selección superior + para obtener información sobre el tema de esta página. + +.. meta:: + :title lang=es: Middleware + :keywords lang=es middleware diff --git a/fr/contents.rst b/fr/contents.rst index 1a770febea..513493c083 100644 --- a/fr/contents.rst +++ b/fr/contents.rst @@ -20,6 +20,7 @@ Contenu development/configuration development/routing controllers/request-response + controllers/middleware controllers views orm diff --git a/fr/controllers/middleware.rst b/fr/controllers/middleware.rst new file mode 100644 index 0000000000..498a834e61 --- /dev/null +++ b/fr/controllers/middleware.rst @@ -0,0 +1,17 @@ +Middleware +########## + +.. note:: + The documentation is not currently supported in French language for this + page. + + Please feel free to send us a pull request on + `Github `_ or use the **Improve This Doc** + button to directly propose your changes. + + You can referer to the english version in the select top menu to have + information about this page's topic. + +.. meta:: + :title lang=fr Middleware + :keywords lang=fr middleware diff --git a/ja/controllers/middleware.rst b/ja/controllers/middleware.rst new file mode 100644 index 0000000000..8556c72f23 --- /dev/null +++ b/ja/controllers/middleware.rst @@ -0,0 +1,17 @@ +Middleware +########## + +.. note:: + The documentation is not currently supported in Japanese language for this + page. + + Please feel free to send us a pull request on + `Github `_ or use the **Improve This Doc** + button to directly propose your changes. + + You can referer to the english version in the select top menu to have + information about this page's topic. + +.. meta:: + :title lang=ja: Middleware + :keywords lang=ja: middleware diff --git a/pt/contents.rst b/pt/contents.rst index 615dab23e5..121d32ae80 100644 --- a/pt/contents.rst +++ b/pt/contents.rst @@ -20,6 +20,7 @@ Conteúdo development/configuration development/routing controllers/request-response + controllers/middleware controllers views orm diff --git a/pt/controllers/middleware.rst b/pt/controllers/middleware.rst new file mode 100644 index 0000000000..43d680b1ba --- /dev/null +++ b/pt/controllers/middleware.rst @@ -0,0 +1,13 @@ +Middleware +########## + +.. note:: + A documentação não é atualmente suportada pela lingua portuguesa nesta + página. + + Por favor, sinta-se a vontade para nos enviar um pull request no + `Github `_ ou use o botão + **Improve This Doc** para propor suas mudanças diretamente. + + Você pode referenciar-se à versão inglesa no menu de seleção superior + para obter informações sobre o tópico desta página. diff --git a/themes/cakephp/static/css/default.css b/themes/cakephp/static/css/default.css index ec5b655f9f..4b697f2187 100644 --- a/themes/cakephp/static/css/default.css +++ b/themes/cakephp/static/css/default.css @@ -222,9 +222,9 @@ dl.docutils { padding-top: 1.3em; } #sidebar-navigation > ul > li:nth-of-type(5):last-child:after, -#sidebar-navigation > ul > li:nth-of-type(12):last-child:after, -#sidebar-navigation > ul > li:nth-of-type(31):last-child:after, -#sidebar-navigation > ul > li:nth-of-type(42):last-child:after { +#sidebar-navigation > ul > li:nth-of-type(14):last-child:after, +#sidebar-navigation > ul > li:nth-of-type(33):last-child:after, +#sidebar-navigation > ul > li:nth-of-type(44):last-child:after { content: " "; display: block; margin-bottom: 1em; @@ -272,67 +272,67 @@ dl.docutils { #sidebar-navigation > ul > li:lang(tr):nth-of-type(6):before { content: "Getting Started"; } -#sidebar-navigation > ul > li:nth-of-type(13):before { +#sidebar-navigation > ul > li:nth-of-type(14):before { content: "General Topics"; } -#sidebar-navigation > ul > li:lang(fr):nth-of-type(13):before { +#sidebar-navigation > ul > li:lang(fr):nth-of-type(14):before { content: "Généralités"; } -#sidebar-navigation > ul > li:lang(es):nth-of-type(13):before { +#sidebar-navigation > ul > li:lang(es):nth-of-type(14):before { content: "General Topics"; } -#sidebar-navigation > ul > li:lang(pt):nth-of-type(13):before { +#sidebar-navigation > ul > li:lang(pt):nth-of-type(14):before { content: "Tópicos Gerais"; } -#sidebar-navigation > ul > li:lang(ja):nth-of-type(13):before { +#sidebar-navigation > ul > li:lang(ja):nth-of-type(14):before { content: "一般的なトピック"; } -#sidebar-navigation > ul > li:lang(zh):nth-of-type(13):before { +#sidebar-navigation > ul > li:lang(zh):nth-of-type(14):before { content: "General Topics"; } -#sidebar-navigation > ul > li:lang(tr):nth-of-type(13):before { +#sidebar-navigation > ul > li:lang(tr):nth-of-type(14):before { content: "General Topics"; } -#sidebar-navigation > ul > li:nth-of-type(32):before { +#sidebar-navigation > ul > li:nth-of-type(33):before { content: "Utility Classes"; } -#sidebar-navigation > ul > li:lang(fr):nth-of-type(32):before { +#sidebar-navigation > ul > li:lang(fr):nth-of-type(33):before { content: "Utilitaires"; } -#sidebar-navigation > ul > li:lang(es):nth-of-type(32):before { +#sidebar-navigation > ul > li:lang(es):nth-of-type(33):before { content: "Utility Classes"; } -#sidebar-navigation > ul > li:lang(pt):nth-of-type(32):before { +#sidebar-navigation > ul > li:lang(pt):nth-of-type(33):before { content: "Classes utilitárias"; } -#sidebar-navigation > ul > li:lang(ja):nth-of-type(32):before { +#sidebar-navigation > ul > li:lang(ja):nth-of-type(33):before { content: "ユーティリティ"; } -#sidebar-navigation > ul > li:lang(zh):nth-of-type(32):before { +#sidebar-navigation > ul > li:lang(zh):nth-of-type(33):before { content: "Utility Classes"; } -#sidebar-navigation > ul > li:lang(tr):nth-of-type(32):before { +#sidebar-navigation > ul > li:lang(tr):nth-of-type(33):before { content: "Utility Classes"; } -#sidebar-navigation > ul > li:nth-of-type(43):before { +#sidebar-navigation > ul > li:nth-of-type(44):before { content: "Other"; } -#sidebar-navigation > ul > li:lang(fr):nth-of-type(43):before { +#sidebar-navigation > ul > li:lang(fr):nth-of-type(44):before { content: "Divers"; } -#sidebar-navigation > ul > li:lang(es):nth-of-type(43):before { +#sidebar-navigation > ul > li:lang(es):nth-of-type(44):before { content: "Other"; } -#sidebar-navigation > ul > li:lang(pt):nth-of-type(43):before { +#sidebar-navigation > ul > li:lang(pt):nth-of-type(44):before { content: "Diversos"; } -#sidebar-navigation > ul > li:lang(ja):nth-of-type(43):before { +#sidebar-navigation > ul > li:lang(ja):nth-of-type(44):before { content: "その他"; } -#sidebar-navigation > ul > li:lang(zh):nth-of-type(43):before { +#sidebar-navigation > ul > li:lang(zh):nth-of-type(44):before { content: "Other"; } -#sidebar-navigation > ul > li:lang(tr):nth-of-type(43):before { +#sidebar-navigation > ul > li:lang(tr):nth-of-type(44):before { content: "Other"; } diff --git a/tr/controllers/middleware.rst b/tr/controllers/middleware.rst new file mode 100644 index 0000000000..4153216c9e --- /dev/null +++ b/tr/controllers/middleware.rst @@ -0,0 +1,13 @@ +Middleware +########## + +.. note:: + Bu belge şu anda bu sayfa için Türkçe dilinde desteklenmemektedir. + + Yapmak istediğiniz değişiklikleri göndermek için, Github üzerinden istek yollayın ya da bu sayfanın üzerinde bulunan "Improve This Doc" butonuna tıklamaktan lütfen çekinmeyin. + + Bu sayfanın konusu hakkındaki İngilizce kaynağa erişmek için üst taraftaki seçim menüsünü kullanabilirsiniz. + +.. meta:: + :title lang=tr: Middleware + :keywords lang=tr: middleware diff --git a/zh/controllers/middleware.rst b/zh/controllers/middleware.rst new file mode 100644 index 0000000000..272e4f8683 --- /dev/null +++ b/zh/controllers/middleware.rst @@ -0,0 +1,17 @@ +Middleware +########## + +.. note:: + The documentation is not currently supported in Chinese language for this + page. + + Please feel free to send us a pull request on + `Github `_ or use the **Improve This Doc** + button to directly propose your changes. + + You can referer to the english version in the select top menu to have + information about this page's topic. + +.. meta:: + :title lang=zh: Middleware + :keywords lang=zh: middleware From b45d937d3957cf4ac06a3e76de6ab3fea12ddb79 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Mon, 30 May 2016 15:28:52 +0200 Subject: [PATCH 02/19] Deprecate dispatch filters and reorganize the migration guide. --- en/appendices/3-3-migration-guide.rst | 80 +++++++++++++++++---------- en/development/dispatch-filters.rst | 4 ++ 2 files changed, 55 insertions(+), 29 deletions(-) diff --git a/en/appendices/3-3-migration-guide.rst b/en/appendices/3-3-migration-guide.rst index 051e9acfad..d221db9d39 100644 --- a/en/appendices/3-3-migration-guide.rst +++ b/en/appendices/3-3-migration-guide.rst @@ -21,6 +21,8 @@ Deprecations * ``header()`` use ``getHeaderLine()`` instead. * ``cookie()`` use ``getCookie()`` instead. * ``version()`` use ``getProtocolVersion()`` instead. +* Dispatcher Filters are now deprecated. Use :doc:`/controllers/middleware` + instead. Behavior Changes ================ @@ -35,6 +37,20 @@ behavior that may effect your application: when generating application local URLs. Previously string URLs would have the base path prepended to them, while array URLs would not. +PSR7 Middleware Support Added +============================= + +In tandem with the deprecation of Dispatcher Filters, support for PSR7 +middleware has been added. Middleware is part of the new HTTP stack that is an +opt-in component of CakePHP 3.3.0. By using the new HTTP stack, you can take +advantage of features like: + +* Using middleware from plugins, and libraries outside of CakePHP. +* Leverage the same response object methods in both the responses you get from + ``Http\Client`` and the responses your application generates. +* Be able to augment the response objects emitted by error handling and asset + delivery. + Http Client is now PSR7 Compatible ================================== @@ -43,34 +59,8 @@ and response objects now implement the `PSR7 interfaces `__. Several methods on ``Cake\Http\Client\Response`` are now deprecated, see above for more information. -Routing -======= - -* ``Router::parse()``, ``RouteCollection::parse()`` and ``Route::parse()`` had - a ``$method`` argument added. It defaults to 'GET'. This new parameter reduces - reliance on global state, and necessary for the PSR7 work integration to be done. -* When building resource routes, you can now define a prefix. This is useful - when defining nested resources as you can create specialized controllers for - nested resources. - -Console -======= - -* Shell tasks that are invoked directly from the CLI no longer have their - ``_welcome`` method invoked. They will also have the ``requested`` parameter - set now. -* ``Shell::err()`` will now apply the 'error' style to text. The default - styling is red text. - -Request -======= - -* ``Request::is()`` and ``Request::addDetector()`` now supports additional - arguments in detectors. This allows detector callables to operate on - additional parameters. - -ORM -=== +ORM Improvements +================ * Additional support has been added for mapping complex data types. This makes it easier to work with geo-spatial types, and data that cannot be represented @@ -99,8 +89,40 @@ Validation ``Validator::notEmpty()`` now accept a list of fields. This allows you to more concisely define the fields that are required. + +Other Enhancements +================== + +Routing +------- + +* ``Router::parse()``, ``RouteCollection::parse()`` and ``Route::parse()`` had + a ``$method`` argument added. It defaults to 'GET'. This new parameter reduces + reliance on global state, and necessary for the PSR7 work integration to be done. +* When building resource routes, you can now define a prefix. This is useful + when defining nested resources as you can create specialized controllers for + nested resources. +* Dispatcher Filters are now deprecated. Use :doc:`/controllers/middleware` + instead. + +Console +------- + +* Shell tasks that are invoked directly from the CLI no longer have their + ``_welcome`` method invoked. They will also have the ``requested`` parameter + set now. +* ``Shell::err()`` will now apply the 'error' style to text. The default + styling is red text. + +Request +------- + +* ``Request::is()`` and ``Request::addDetector()`` now supports additional + arguments in detectors. This allows detector callables to operate on + additional parameters. + Debugging Functions -=================== +------------------- * The ``pr()``, ``debug()``, and ``pj()`` functions now return the value being dumped. This makes them easier to use when values are being returned. diff --git a/en/development/dispatch-filters.rst b/en/development/dispatch-filters.rst index b13c176ecc..81a04fd0c0 100644 --- a/en/development/dispatch-filters.rst +++ b/en/development/dispatch-filters.rst @@ -1,6 +1,10 @@ Dispatcher Filters ################## +.. deprecated:: 3.3.0 + As of 3.3.0 Dispatcher Filters are deprecated. You should use + :doc:`/controllers/middleware` instead now. + There are several reasons to want a piece of code to be run before any controller code is executed or right before the response is sent to the client, such as response caching, header tuning, special authentication or just to From b450034a97de415723ae929ac1a61c181ca64670 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Mon, 30 May 2016 19:16:13 +0200 Subject: [PATCH 03/19] Start HTTP Server docs. --- en/appendices/3-3-migration-guide.rst | 4 + en/controllers/middleware.rst | 184 +++++++++++++++++++++++++- en/core-libraries/httpclient.rst | 2 +- 3 files changed, 188 insertions(+), 2 deletions(-) diff --git a/en/appendices/3-3-migration-guide.rst b/en/appendices/3-3-migration-guide.rst index d221db9d39..042b415c5a 100644 --- a/en/appendices/3-3-migration-guide.rst +++ b/en/appendices/3-3-migration-guide.rst @@ -51,6 +51,10 @@ advantage of features like: * Be able to augment the response objects emitted by error handling and asset delivery. +See the :doc:`/controllers/middleware` chapter and :ref:`adding-http-stack` +sections for more information and how to add the new HTTP stack to an existing +application. + Http Client is now PSR7 Compatible ================================== diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 3605054203..a20d80eb0f 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -1,4 +1,186 @@ Middleware ########## -TODO write outline. +Middleware give you the ability to 'wrap' your application in re-usable, +composable layers of Request handling, or response building logic. Middleware +are part of the new HTTP stack in CakePHP that leverages the PSR7 request and +response interfaces. By leveraging the PSR7 standard you can use any PSR7 +compatible middleware available on `The Packagist `__. + +CakePHP provides several middleware out of the box: + +* ``Cake\Error\Middleware\ErrorHandlerMiddleware`` traps exceptions from the + wrapped middleware and renders an error page using the + :doc:`/development/errors` Exception handler. +* ``Cake\Routing\AssetMiddleware`` checks whether the request is referring to a theme + or plugin asset file, such as a CSS, JavaScript or image file stored in either a + plugin's webroot folder or the corresponding one for a Theme. +* ``Cake\Routing\Middleware\RoutingMiddleware`` uses the ``Router`` to parse the + incoming URL and assign routing parameters to the request. +* ``Cake\I18n\Middleware\LocaleSelectorMiddleware`` enables automatic language + switching from the ``Accept-Language`` header sent by the browser. + +Using Middleware +================ + +You attach middleware in your ``App\Application`` class' ``middleware`` method. +If you don't have an ``App\Applicatino`` class, see the section on +:ref:`adding-http-stack` for more information. Your application's ``middleware`` +hook method will be called early in the request process, you can use the +``Middleware`` object to attach middleware:: + + namespace App; + + use Cake\Http\BaseApplication; + + class Application extends BaseApplication + { + public functin middleware($middleware) + { + $error = new \Cake\Error\Middleware\ErrorHandlerMiddleware(); + $middleware->push($error); + return $middleware; + } + } + +In addition to pushing onto the end of the ``MiddlewareStack`` you can do +a variety of operations:: + + $layer = new \App\Middleware\CustomMiddleware; + + // pushed middleware will be last in line. + $middleware->push($layer); + + // Prepended middleware will be first in line. + $middleware->prepend($layer); + + // insert in a specific slot. If the slot is out of + // bounds, it will be added to the end of the line. + $middleware->insertAt(2, $layer); + + // Insert before another middleware. + // If the named class cannot be found the new layer + // we be added to the end of the line. + $middleware->insertBefore( + 'Cake\Error\Middleware\ErrorHandlerMiddleware', + $layer + ); + + // Insert after another middleware. + $middleware->insertAfter( + 'Cake\Error\Middleware\ErrorHandlerMiddleware', + $layer + ); + +Adding Middleware from Plugins +------------------------------ + +After the middleware stack has been prepared by the application, the +``Server.buildMiddleware`` event is triggered. This event can be useful to add +middleware from plugins. Plugins can register listeners in their bootstrap +scripts, that add middleware:: + + // In ContactManager plugin bootstrap.php + use Cake\Event\EventManager; + + EventManager::instance()->on( + 'Server.buildMiddleware', + function ($event, $middleware) { + $middleware->push(new PluginMiddleware()); + }); + +PSR7 Requests and Responses +=========================== + +Middleware and the new HTTP stack are built on top of the `PSR7 Request +& Response Interfaces `__. While all +middleware will be exposed to these interfaces, your controllers, components, +and views will *not*. + +Interacting with Requests +------------------------- + +The ``RequestInterface`` provides methods for interacting with the headers, +method, URI, and body of a request. To interact with the headers, you can:: + + // Read a header as text + $value = $request->getHeaderLine(‘Content-Type’); + + // Read header as an array + $value = $request->getHeader(‘Content-Type’); + + // Read all the headers as an associative array. + $headers = $request->getHeaders(); + +Requests also give access to the cookies and uploaded files they contain:: + + // Get an array of cookie values. + $cookies = $request->getCookieParams(); + + // Get a list of UploadedFile objects + $files = $request->getUploadedFiles(); + + // Read the file data. + $files[0]->getStream(); + $files[0]->getSize(); + $files[0]->getClientFileName(); + + // Move the file. + $files[0]->moveTo($targetPath); + +Requests contain a URI object, which contains methods for interacting with the +requested URI:: + + // Get the URI + $uri = $request->getUri(); + + // Read data out of the URI. + $path = $uri->getPath(); + $query = $uri->getQuery(); + $host = $uri->getHost(); + +Lastly, you can interact with a request's 'attributes'. CakePHP uses these +attributes to carry framework specific request parameters. There are 3 important +attributes in any request handled by CakePHP: + +* ``base`` contains the base directory for your application if there is one. +* ``webroot`` contains the webroot directory for your application. +* ``params`` contains the results of route matching once routing rules have been + processed. + +Interacting with Responses +-------------------------- + +The methods available to create a server response are the same as those +available when interacting with :ref:`httpclient-response-objects`. While the +interface is the same the usage scenarios are different. + +When modifying the response, it is important to remember that responses are +**immutable**. You must always remember to store the results of any setter +method. For example:: + + // This does *not* change the response. As our new object + // is not stored. + $response->withHeader('Content-Type', 'application/json'); + + // This works! + $response = $response->withHeader('Content-Type', 'application/json'); + +Most often you'll be setting headers and response bodies on requests:: + + // Assign headers and a status code + $response = $response->withHeader('Content-Type', 'application/json') + ->withHeader('Pragma', 'no-cache') + ->withStatus(422); + + // Write to the body + $body = $response->getBody(); + $body->write(json_encode(['errno' => $errorCode])); + +Creating Middleware +=================== + +.. _adding-http-stack: + +Adding the new HTTP Stack to an Existing Application +==================================================== diff --git a/en/core-libraries/httpclient.rst b/en/core-libraries/httpclient.rst index f24fcaadd3..1e50fc8fd5 100644 --- a/en/core-libraries/httpclient.rst +++ b/en/core-libraries/httpclient.rst @@ -337,6 +337,7 @@ request's ``$options`` parameters:: 'cookies' => ['sessionid' => '123abc'] ]); +.. _httpclient-response-objects: Response Objects ================ @@ -453,7 +454,6 @@ Response objects provide a few methods for checking status codes:: // __get() helper $response->code; - .. meta:: :title lang=en: HttpClient :keywords lang=en: array name,array data,query parameter,query string,php class,string query,test type,string data,google,query results,webservices,apis,parameters,cakephp,meth,search results From dc152d430a57a068995f316b544ccdce7996ecea Mon Sep 17 00:00:00 2001 From: Mark Story Date: Mon, 30 May 2016 19:31:13 +0200 Subject: [PATCH 04/19] Round out more of the middleware docs. --- en/controllers/middleware.rst | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index a20d80eb0f..0baf015d16 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -180,6 +180,49 @@ Most often you'll be setting headers and response bodies on requests:: Creating Middleware =================== +Middleware can either be implemented as anonymous functions (Closures), or as +invokable classes. While Closures are suitable for smaller tasks they make +testing harder, and can create a complicated ``Application`` class. Like most +parts of CakePHP, middleware classes have a few conventions: + +* Middleware class files should be put in **src/Middleware**. For example: + **src/Middleware/CorsMiddleware.php** +* Helper classes should be suffixed with ``Middleware``. For example: + ``LinkMiddleware``. +* Middleware are expected to implement the middleware protocol. + +Middleware Protocol +------------------- + +While not a formal interface, Middleware do have a soft-interface or protocol. +The protocol is as follows: + +#. Middleware much implement ``__invoke($request, $response, $next)``. +#. Middleware must return a response. + +Middleware can return a response either by calling ``$next`` or by creating +their own response:: + + // Call $next() delegates control to then *next* middleware + // In your application's stack. + function __invoke($request, $response, $next) + { + // Do some things + $response = $next($request, $response); + // More things + return $response; + } + +Middleware can also short-circuit the dispatching process by returning a +response object:: + + function __invoke($request, $response, $next) + { + // By not invoking $next, this will be the last + // middleware to run. + return $response->withStatusCode(400); + } + .. _adding-http-stack: Adding the new HTTP Stack to an Existing Application From eb3ba4b1014eee43000c7dd72e68d4de355b314d Mon Sep 17 00:00:00 2001 From: Mark Story Date: Mon, 30 May 2016 19:38:46 +0200 Subject: [PATCH 05/19] Finish off the create a middleware example. --- en/controllers/middleware.rst | 51 +++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 0baf015d16..00ed3bd917 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -201,26 +201,49 @@ The protocol is as follows: #. Middleware must return a response. Middleware can return a response either by calling ``$next`` or by creating -their own response:: +their own response. We can see both options in our simple middleware:: - // Call $next() delegates control to then *next* middleware - // In your application's stack. - function __invoke($request, $response, $next) + // in src/Middleware/SimpleMiddleware.php + namespace App\Middleware; + + class SimpleMiddleware { - // Do some things - $response = $next($request, $response); - // More things - return $response; + function __invoke($request, $response, $next) + { + // If we find /simple/ in the URL return a simple response. + if (strpos($request->getUri()->getPath(), '/simple/') !== false) { + $body = $response->getBody(); + $body->write('A simple response'); + return $response->withStatus(200) + ->withHeader('Content-Type', 'text/plain') + ->withBody($body); + } + // Calling $next() delegates control to then *next* middleware + // In your application's stack. + $response = $next($request, $response); + + // We could further modify the response before returning it. + return $response; + } } -Middleware can also short-circuit the dispatching process by returning a -response object:: +Now that we've made a very simple middleware, lets attach it to our +application:: + + // in src/Application.php + namespace App; + + use App\Middleware\SimpleMiddleware; - function __invoke($request, $response, $next) + class Application { - // By not invoking $next, this will be the last - // middleware to run. - return $response->withStatusCode(400); + public function middleware($middleware) + { + // Other middleware + + $middleware->push(new SimpleMiddleware()); + return $middleware; + } } .. _adding-http-stack: From b33e7960710bf06689fb3933f8c3958eeb46fafa Mon Sep 17 00:00:00 2001 From: cake17 Date: Tue, 31 May 2016 09:27:43 +0200 Subject: [PATCH 06/19] small typos --- en/controllers/middleware.rst | 2 +- en/core-libraries/httpclient.rst | 2 +- ja/contents.rst | 1 + tr/contents.rst | 1 + zh/contents.rst | 1 + 5 files changed, 5 insertions(+), 2 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 00ed3bd917..1730496ca8 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -24,7 +24,7 @@ Using Middleware ================ You attach middleware in your ``App\Application`` class' ``middleware`` method. -If you don't have an ``App\Applicatino`` class, see the section on +If you don't have an ``App\Application`` class, see the section on :ref:`adding-http-stack` for more information. Your application's ``middleware`` hook method will be called early in the request process, you can use the ``Middleware`` object to attach middleware:: diff --git a/en/core-libraries/httpclient.rst b/en/core-libraries/httpclient.rst index 1e50fc8fd5..ae7ef51675 100644 --- a/en/core-libraries/httpclient.rst +++ b/en/core-libraries/httpclient.rst @@ -342,7 +342,7 @@ request's ``$options`` parameters:: Response Objects ================ -.. php:namepspace:: Cake\Http\Client +.. php:namespace:: Cake\Http\Client .. php:class:: Response diff --git a/ja/contents.rst b/ja/contents.rst index ea048d21a1..5eb7def245 100755 --- a/ja/contents.rst +++ b/ja/contents.rst @@ -20,6 +20,7 @@ development/configuration development/routing controllers/request-response + controllers/middleware controllers views orm diff --git a/tr/contents.rst b/tr/contents.rst index 6f1d998c44..15b8d67c2d 100644 --- a/tr/contents.rst +++ b/tr/contents.rst @@ -20,6 +20,7 @@ development/configuration development/routing controllers/request-response + controllers/middleware controllers views orm diff --git a/zh/contents.rst b/zh/contents.rst index 17476cab9d..e2c42aba3c 100644 --- a/zh/contents.rst +++ b/zh/contents.rst @@ -20,6 +20,7 @@ Contents development/configuration development/routing controllers/request-response + controllers/middleware controllers views orm From 1fb563ebf571b4df22a350f98ef907e909b57426 Mon Sep 17 00:00:00 2001 From: cake17 Date: Tue, 31 May 2016 09:30:37 +0200 Subject: [PATCH 07/19] [fr] start fr updates --- fr/development/dispatch-filters.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/fr/development/dispatch-filters.rst b/fr/development/dispatch-filters.rst index f2791cfb48..117df0d0b1 100644 --- a/fr/development/dispatch-filters.rst +++ b/fr/development/dispatch-filters.rst @@ -1,6 +1,10 @@ Filtres du Dispatcher ##################### +.. deprecated:: 3.3.0 + Depuis la version 3.3.0 , les Filtres de Dispatcher sont dépréciés. Vous + devriez maintenant utiliser le :doc:`/controllers/middleware` à la place. + Il y a plusieurs raisons de vouloir exécuter un bout de code avant que tout code de controller ne soit lancé ou juste avant que la réponse ne soit envoyée au client, comme la mise en cache de la réponse, le tunning de header, From c200516575d84ebcce0928ab4edf86ed80afd882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Tue, 31 May 2016 17:32:37 +0200 Subject: [PATCH 08/19] Unify comment capitalisation --- en/controllers/middleware.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 1730496ca8..bdc0bc216b 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -48,13 +48,13 @@ a variety of operations:: $layer = new \App\Middleware\CustomMiddleware; - // pushed middleware will be last in line. + // Pushed middleware will be last in line. $middleware->push($layer); // Prepended middleware will be first in line. $middleware->prepend($layer); - // insert in a specific slot. If the slot is out of + // Insert in a specific slot. If the slot is out of // bounds, it will be added to the end of the line. $middleware->insertAt(2, $layer); From b5ae480767f1a2c687002faacfce56245f343d50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Tue, 31 May 2016 18:01:27 +0200 Subject: [PATCH 09/19] Imply, that an official interface could come --- en/controllers/middleware.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index bdc0bc216b..9736bceb68 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -194,7 +194,7 @@ parts of CakePHP, middleware classes have a few conventions: Middleware Protocol ------------------- -While not a formal interface, Middleware do have a soft-interface or protocol. +While not a formal interface (yet), Middleware do have a soft-interface or protocol. The protocol is as follows: #. Middleware much implement ``__invoke($request, $response, $next)``. @@ -203,7 +203,7 @@ The protocol is as follows: Middleware can return a response either by calling ``$next`` or by creating their own response. We can see both options in our simple middleware:: - // in src/Middleware/SimpleMiddleware.php + // In src/Middleware/SimpleMiddleware.php namespace App\Middleware; class SimpleMiddleware From f97471219c28d117fe6e8d95752ded93d30b0a0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Tue, 31 May 2016 18:02:15 +0200 Subject: [PATCH 10/19] Typo --- en/controllers/middleware.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 9736bceb68..0da740e02a 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -197,7 +197,7 @@ Middleware Protocol While not a formal interface (yet), Middleware do have a soft-interface or protocol. The protocol is as follows: -#. Middleware much implement ``__invoke($request, $response, $next)``. +#. Middleware must implement ``__invoke($request, $response, $next)``. #. Middleware must return a response. Middleware can return a response either by calling ``$next`` or by creating From 7e28259d879456e61461dc113a1fe73b4c003f35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Tue, 31 May 2016 18:06:10 +0200 Subject: [PATCH 11/19] Whitespace --- en/controllers/middleware.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 0da740e02a..464031512d 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -218,6 +218,7 @@ their own response. We can see both options in our simple middleware:: ->withHeader('Content-Type', 'text/plain') ->withBody($body); } + // Calling $next() delegates control to then *next* middleware // In your application's stack. $response = $next($request, $response); From b1bf0ec4c96f7d62c4dde84188477ce157ef2c5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Tue, 31 May 2016 18:07:36 +0200 Subject: [PATCH 12/19] Bad apostrophe --- en/controllers/middleware.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 464031512d..f5c049a93a 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -228,10 +228,10 @@ their own response. We can see both options in our simple middleware:: } } -Now that we've made a very simple middleware, lets attach it to our +Now that we've made a very simple middleware, let's attach it to our application:: - // in src/Application.php + // In src/Application.php namespace App; use App\Middleware\SimpleMiddleware; From 86df8c0445c1a282692ff14df5bc4e0fb3f70a84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20W=C3=BCrth?= Date: Tue, 31 May 2016 18:11:07 +0200 Subject: [PATCH 13/19] Clarify comment --- en/controllers/middleware.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index f5c049a93a..09fc7d40e2 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -240,9 +240,11 @@ application:: { public function middleware($middleware) { - // Other middleware - + // Push your simple middleware onto the stack $middleware->push(new SimpleMiddleware()); + + // Push some more middleware onto the stack + return $middleware; } } From 829e29653f8918a04e6475c5d9babe2d4cad8eb0 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Tue, 31 May 2016 22:19:04 -0400 Subject: [PATCH 14/19] Incorporate feedback from review. --- en/controllers/middleware.rst | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 09fc7d40e2..4d4c20120e 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -1,7 +1,7 @@ Middleware ########## -Middleware give you the ability to 'wrap' your application in re-usable, +Middleware objects give you the ability to 'wrap' your application in re-usable, composable layers of Request handling, or response building logic. Middleware are part of the new HTTP stack in CakePHP that leverages the PSR7 request and response interfaces. By leveraging the PSR7 standard you can use any PSR7 @@ -55,18 +55,20 @@ a variety of operations:: $middleware->prepend($layer); // Insert in a specific slot. If the slot is out of - // bounds, it will be added to the end of the line. + // bounds, it will be added to the end. $middleware->insertAt(2, $layer); // Insert before another middleware. - // If the named class cannot be found the new layer - // we be added to the end of the line. + // If the named class cannot be found, + // an exception will be raised. $middleware->insertBefore( 'Cake\Error\Middleware\ErrorHandlerMiddleware', $layer ); // Insert after another middleware. + // If the named class cannot be found, the + // middleware will added to the end. $middleware->insertAfter( 'Cake\Error\Middleware\ErrorHandlerMiddleware', $layer @@ -86,7 +88,7 @@ scripts, that add middleware:: EventManager::instance()->on( 'Server.buildMiddleware', function ($event, $middleware) { - $middleware->push(new PluginMiddleware()); + $middleware->push(new ContactPluginMiddleware()); }); PSR7 Requests and Responses @@ -159,12 +161,12 @@ When modifying the response, it is important to remember that responses are **immutable**. You must always remember to store the results of any setter method. For example:: - // This does *not* change the response. As our new object - // is not stored. + // This does *not* modify $response. The new object was not + // assigned to a variable. $response->withHeader('Content-Type', 'application/json'); // This works! - $response = $response->withHeader('Content-Type', 'application/json'); + $newResponse = $response->withHeader('Content-Type', 'application/json'); Most often you'll be setting headers and response bodies on requests:: @@ -182,12 +184,12 @@ Creating Middleware Middleware can either be implemented as anonymous functions (Closures), or as invokable classes. While Closures are suitable for smaller tasks they make -testing harder, and can create a complicated ``Application`` class. Like most -parts of CakePHP, middleware classes have a few conventions: +testing harder, and can create a complicated ``Application`` class. Middleware +classes in CakePHP have a few conventions: * Middleware class files should be put in **src/Middleware**. For example: **src/Middleware/CorsMiddleware.php** -* Helper classes should be suffixed with ``Middleware``. For example: +* Middleware classes should be suffixed with ``Middleware``. For example: ``LinkMiddleware``. * Middleware are expected to implement the middleware protocol. @@ -197,8 +199,8 @@ Middleware Protocol While not a formal interface (yet), Middleware do have a soft-interface or protocol. The protocol is as follows: -#. Middleware must implement ``__invoke($request, $response, $next)``. -#. Middleware must return a response. +#. Middleware much implement ``__invoke($request, $response, $next)``. +#. Middleware must return an object implementing the PSR7 ``ResponseInterface``. Middleware can return a response either by calling ``$next`` or by creating their own response. We can see both options in our simple middleware:: @@ -213,8 +215,8 @@ their own response. We can see both options in our simple middleware:: // If we find /simple/ in the URL return a simple response. if (strpos($request->getUri()->getPath(), '/simple/') !== false) { $body = $response->getBody(); - $body->write('A simple response'); - return $response->withStatus(200) + $body->write('Thanks!'); + return $response->withStatus(202) ->withHeader('Content-Type', 'text/plain') ->withBody($body); } From 92e1e57400aca9393bf08504b2e4bf7a1bbfc181 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Wed, 1 Jun 2016 19:54:20 -0400 Subject: [PATCH 15/19] Fix stupid mistake. --- en/controllers/middleware.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 4d4c20120e..b08f33281b 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -199,7 +199,7 @@ Middleware Protocol While not a formal interface (yet), Middleware do have a soft-interface or protocol. The protocol is as follows: -#. Middleware much implement ``__invoke($request, $response, $next)``. +#. Middleware must implement ``__invoke($request, $response, $next)``. #. Middleware must return an object implementing the PSR7 ``ResponseInterface``. Middleware can return a response either by calling ``$next`` or by creating From cba626de81e3b0e18130d1d17661a7850396fed4 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 5 Jun 2016 22:15:28 -0400 Subject: [PATCH 16/19] Attempt to fix build issues. --- en/controllers/middleware.rst | 8 +++++++- es/controllers/middleware.rst | 4 ++-- fr/controllers/middleware.rst | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index b08f33281b..5009f37bf7 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -244,7 +244,7 @@ application:: { // Push your simple middleware onto the stack $middleware->push(new SimpleMiddleware()); - + // Push some more middleware onto the stack return $middleware; @@ -255,3 +255,9 @@ application:: Adding the new HTTP Stack to an Existing Application ==================================================== + +TODO + +.. meta:: + :title lang=en: Http Middleware + :keywords lang=en: http, middleware, psr7, request, response, wsgi, application, baseapplication diff --git a/es/controllers/middleware.rst b/es/controllers/middleware.rst index 4a5c32d003..9da613232f 100644 --- a/es/controllers/middleware.rst +++ b/es/controllers/middleware.rst @@ -11,5 +11,5 @@ Middleware para obtener información sobre el tema de esta página. .. meta:: - :title lang=es: Middleware - :keywords lang=es middleware + :title lang=es: Http Middleware + :keywords lang=es: http, middleware, psr7, request, response, wsgi, application, baseapplication diff --git a/fr/controllers/middleware.rst b/fr/controllers/middleware.rst index 498a834e61..ce037da545 100644 --- a/fr/controllers/middleware.rst +++ b/fr/controllers/middleware.rst @@ -13,5 +13,5 @@ Middleware information about this page's topic. .. meta:: - :title lang=fr Middleware - :keywords lang=fr middleware + :title lang=fr: Middleware + :keywords lang=fr: middleware From ca0989dcc9862507e14e98657f6dbc1e9f0e461a Mon Sep 17 00:00:00 2001 From: cake17 Date: Mon, 6 Jun 2016 10:53:00 +0200 Subject: [PATCH 17/19] [fr] add missing fr --- en/appendices/3-3-migration-guide.rst | 6 +- en/controllers/middleware.rst | 10 +- fr/appendices/3-3-migration-guide.rst | 85 +++++--- fr/controllers/middleware.rst | 266 +++++++++++++++++++++++++- fr/core-libraries/httpclient.rst | 3 +- 5 files changed, 322 insertions(+), 48 deletions(-) diff --git a/en/appendices/3-3-migration-guide.rst b/en/appendices/3-3-migration-guide.rst index 042b415c5a..31a015eb38 100644 --- a/en/appendices/3-3-migration-guide.rst +++ b/en/appendices/3-3-migration-guide.rst @@ -61,7 +61,8 @@ Http Client is now PSR7 Compatible ``Cake\Network\Http\Client`` has been moved to ``Cake\Http\Client``. Its request and response objects now implement the `PSR7 interfaces `__. Several methods on -``Cake\Http\Client\Response`` are now deprecated, see above for more information. +``Cake\Http\Client\Response`` are now deprecated, see above for more +information. ORM Improvements ================ @@ -102,7 +103,8 @@ Routing * ``Router::parse()``, ``RouteCollection::parse()`` and ``Route::parse()`` had a ``$method`` argument added. It defaults to 'GET'. This new parameter reduces - reliance on global state, and necessary for the PSR7 work integration to be done. + reliance on global state, and necessary for the PSR7 work integration to be + done. * When building resource routes, you can now define a prefix. This is useful when defining nested resources as you can create specialized controllers for nested resources. diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 5009f37bf7..4cd3496abe 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -12,9 +12,9 @@ CakePHP provides several middleware out of the box: * ``Cake\Error\Middleware\ErrorHandlerMiddleware`` traps exceptions from the wrapped middleware and renders an error page using the :doc:`/development/errors` Exception handler. -* ``Cake\Routing\AssetMiddleware`` checks whether the request is referring to a theme - or plugin asset file, such as a CSS, JavaScript or image file stored in either a - plugin's webroot folder or the corresponding one for a Theme. +* ``Cake\Routing\AssetMiddleware`` checks whether the request is referring to a + theme or plugin asset file, such as a CSS, JavaScript or image file stored in + either a plugin's webroot folder or the corresponding one for a Theme. * ``Cake\Routing\Middleware\RoutingMiddleware`` uses the ``Router`` to parse the incoming URL and assign routing parameters to the request. * ``Cake\I18n\Middleware\LocaleSelectorMiddleware`` enables automatic language @@ -196,8 +196,8 @@ classes in CakePHP have a few conventions: Middleware Protocol ------------------- -While not a formal interface (yet), Middleware do have a soft-interface or protocol. -The protocol is as follows: +While not a formal interface (yet), Middleware do have a soft-interface or +protocol. The protocol is as follows: #. Middleware must implement ``__invoke($request, $response, $next)``. #. Middleware must return an object implementing the PSR7 ``ResponseInterface``. diff --git a/fr/appendices/3-3-migration-guide.rst b/fr/appendices/3-3-migration-guide.rst index ea4c6f8612..2761a000fa 100644 --- a/fr/appendices/3-3-migration-guide.rst +++ b/fr/appendices/3-3-migration-guide.rst @@ -21,6 +21,8 @@ Deprecations * ``header()`` utilisez ``getHeaderLine()`` à la place. * ``cookie()`` utilisez ``getCookie()`` à la place. * ``version()`` utilisez ``getProtocolVersion()`` à la place. +* Les Filtres de Dispatcher sont maintenant dépréciés. Utilisez + :doc:`/controllers/middleware` à la place. Changements de Comportement =========================== @@ -36,6 +38,24 @@ variations mineures qui peuvent avoir des effets sur votre application: d'URLs étaient préfixées par le chemin de base alors que les tableaux d'URLs ne l'étaient pas. +PSR7 Middleware Support Added +============================= + +In tandem with the deprecation of Dispatcher Filters, support for PSR7 +middleware has been added. Middleware is part of the new HTTP stack that is an +opt-in component of CakePHP 3.3.0. By using the new HTTP stack, you can take +advantage of features like: + +* Using middleware from plugins, and libraries outside of CakePHP. +* Leverage the same response object methods in both the responses you get from + ``Http\Client`` and the responses your application generates. +* Be able to augment the response objects emitted by error handling and asset + delivery. + +See the :doc:`/controllers/middleware` chapter and :ref:`adding-http-stack` +sections for more information and how to add the new HTTP stack to an existing +application. + Http Client est maintenant compatible avec PSR7 =============================================== @@ -45,35 +65,8 @@ objet request et response implémentent maintenant les ``Cake\Http\Client\Response`` sont maintenant dépréciées, regardez plus haut pour plus d'informations. -Routing -======= - -* ``Router::parse()``, ``RouteCollection::parse()`` et ``Route::parse()`` ont - un nouvel argument ``$method``. Il est par défaut à 'GET'. Ce nouveau - paramètre réduit le recours à l'état global, et est nécessaire pour le travail - d'intégration de la norme PSR7. -* Quand vous construisez vos resource routes, vous pouvez maintenant définir un - préfixe. C'est utile quand vous définissez des ressources imbriquées car vous - pouvez créer des controllers spécialisés pour les ressources imbriquées. - -Console -======= - -* Les Shell tasks qui sont appelées directement à partir du CLI n'appellent plus - la méthode ``_welcome``. Ils vont maintenant aussi avoir le paramètre - ``requested`` défini. -* ``Shell::err()`` va maintenant appliquer le style 'error' au texte. Le style - par défaut est le texte rouge. - -Request -======= - -* ``Request::is()`` et ``Request::addDetector()`` supportent maintenant des - arguments supplémentaires dans les détecteurs. Cela permet aux détecteurs - callables d'opérer sur des paramètres supplémentaires. - -ORM -=== +Améliorations de l'ORM +====================== * Le support supplémentaire a été ajouté pour mapper des types de données complexes. Cela facilite le travail pour des types geo-spatiaux et les données @@ -106,8 +99,40 @@ Validation ``Validator::notEmpty()`` acceptent maintenant une liste de champs. Ceci vous permet de définir de façon plus concise les champs qui sont requis. +Autres Améliorations +==================== + +Routing +------- + +* ``Router::parse()``, ``RouteCollection::parse()`` et ``Route::parse()`` ont + un nouvel argument ``$method``. Il est par défaut à 'GET'. Ce nouveau + paramètre réduit le recours à l'état global, et est nécessaire pour le travail + d'intégration de la norme PSR7. +* Quand vous construisez vos resource routes, vous pouvez maintenant définir un + préfixe. C'est utile quand vous définissez des ressources imbriquées car vous + pouvez créer des controllers spécialisés pour les ressources imbriquées. +* Les Filtres de Dispatcher sont maintenant dépréciés. Utilisez + :doc:`/controllers/middleware` à la place. + +Console +------- + +* Les Shell tasks qui sont appelées directement à partir du CLI n'appellent plus + la méthode ``_welcome``. Ils vont maintenant aussi avoir le paramètre + ``requested`` défini. +* ``Shell::err()`` va maintenant appliquer le style 'error' au texte. Le style + par défaut est le texte rouge. + +Request +------- + +* ``Request::is()`` et ``Request::addDetector()`` supportent maintenant des + arguments supplémentaires dans les détecteurs. Cela permet aux détecteurs + callables d'opérer sur des paramètres supplémentaires. + Debugging Functions -=================== +------------------- * Les fonctions ``pr()``, ``debug()`` et ``pj()`` retournent maintenant la valeur résultante. Cela facilite leur utilisation quand des valeurs sont diff --git a/fr/controllers/middleware.rst b/fr/controllers/middleware.rst index ce037da545..ef841835ff 100644 --- a/fr/controllers/middleware.rst +++ b/fr/controllers/middleware.rst @@ -1,17 +1,263 @@ Middleware ########## -.. note:: - The documentation is not currently supported in French language for this - page. +Middleware objects give you the ability to 'wrap' your application in re-usable, +composable layers of Request handling, or response building logic. Middleware +are part of the new HTTP stack in CakePHP that leverages the PSR7 request and +response interfaces. By leveraging the PSR7 standard you can use any PSR7 +compatible middleware available on `The Packagist `__. - Please feel free to send us a pull request on - `Github `_ or use the **Improve This Doc** - button to directly propose your changes. +CakePHP provides several middleware out of the box: - You can referer to the english version in the select top menu to have - information about this page's topic. +* ``Cake\Error\Middleware\ErrorHandlerMiddleware`` traps exceptions from the + wrapped middleware and renders an error page using the + :doc:`/development/errors` Exception handler. +* ``Cake\Routing\AssetMiddleware`` checks whether the request is referring to a + theme or plugin asset file, such as a CSS, JavaScript or image file stored in + either a plugin's webroot folder or the corresponding one for a Theme. +* ``Cake\Routing\Middleware\RoutingMiddleware`` uses the ``Router`` to parse the + incoming URL and assign routing parameters to the request. +* ``Cake\I18n\Middleware\LocaleSelectorMiddleware`` enables automatic language + switching from the ``Accept-Language`` header sent by the browser. + +Utilisation du Middleware +========================= + +You attach middleware in your ``App\Application`` class' ``middleware`` method. +If you don't have an ``App\Application`` class, see the section on +:ref:`adding-http-stack` for more information. Your application's ``middleware`` +hook method will be called early in the request process, you can use the +``Middleware`` object to attach middleware:: + + namespace App; + + use Cake\Http\BaseApplication; + + class Application extends BaseApplication + { + public functin middleware($middleware) + { + $error = new \Cake\Error\Middleware\ErrorHandlerMiddleware(); + $middleware->push($error); + return $middleware; + } + } + +In addition to pushing onto the end of the ``MiddlewareStack`` you can do +a variety of operations:: + + $layer = new \App\Middleware\CustomMiddleware; + + // Pushed middleware will be last in line. + $middleware->push($layer); + + // Prepended middleware will be first in line. + $middleware->prepend($layer); + + // Insert in a specific slot. If the slot is out of + // bounds, it will be added to the end. + $middleware->insertAt(2, $layer); + + // Insert before another middleware. + // If the named class cannot be found, + // an exception will be raised. + $middleware->insertBefore( + 'Cake\Error\Middleware\ErrorHandlerMiddleware', + $layer + ); + + // Insert after another middleware. + // If the named class cannot be found, the + // middleware will added to the end. + $middleware->insertAfter( + 'Cake\Error\Middleware\ErrorHandlerMiddleware', + $layer + ); + +Ajouter un Middleware à partir des Plugins +------------------------------------------ + +After the middleware stack has been prepared by the application, the +``Server.buildMiddleware`` event is triggered. This event can be useful to add +middleware from plugins. Plugins can register listeners in their bootstrap +scripts, that add middleware:: + + // In ContactManager plugin bootstrap.php + use Cake\Event\EventManager; + + EventManager::instance()->on( + 'Server.buildMiddleware', + function ($event, $middleware) { + $middleware->push(new ContactPluginMiddleware()); + }); + +Requêtes et Réponses PSR7 +========================= + +Middleware and the new HTTP stack are built on top of the `PSR7 Request +& Response Interfaces `__. While all +middleware will be exposed to these interfaces, your controllers, components, +and views will *not*. + +Interagir avec les Requêtes +--------------------------- + +The ``RequestInterface`` provides methods for interacting with the headers, +method, URI, and body of a request. To interact with the headers, you can:: + + // Read a header as text + $value = $request->getHeaderLine(‘Content-Type’); + + // Read header as an array + $value = $request->getHeader(‘Content-Type’); + + // Read all the headers as an associative array. + $headers = $request->getHeaders(); + +Requests also give access to the cookies and uploaded files they contain:: + + // Get an array of cookie values. + $cookies = $request->getCookieParams(); + + // Get a list of UploadedFile objects + $files = $request->getUploadedFiles(); + + // Read the file data. + $files[0]->getStream(); + $files[0]->getSize(); + $files[0]->getClientFileName(); + + // Move the file. + $files[0]->moveTo($targetPath); + +Requests contain a URI object, which contains methods for interacting with the +requested URI:: + + // Get the URI + $uri = $request->getUri(); + + // Read data out of the URI. + $path = $uri->getPath(); + $query = $uri->getQuery(); + $host = $uri->getHost(); + +Lastly, you can interact with a request's 'attributes'. CakePHP uses these +attributes to carry framework specific request parameters. There are 3 important +attributes in any request handled by CakePHP: + +* ``base`` contains the base directory for your application if there is one. +* ``webroot`` contains the webroot directory for your application. +* ``params`` contains the results of route matching once routing rules have been + processed. + +Interagir avec les Réponses +--------------------------- + +The methods available to create a server response are the same as those +available when interacting with :ref:`httpclient-response-objects`. While the +interface is the same the usage scenarios are different. + +When modifying the response, it is important to remember that responses are +**immutable**. You must always remember to store the results of any setter +method. For example:: + + // This does *not* modify $response. The new object was not + // assigned to a variable. + $response->withHeader('Content-Type', 'application/json'); + + // This works! + $newResponse = $response->withHeader('Content-Type', 'application/json'); + +Most often you'll be setting headers and response bodies on requests:: + + // Assign headers and a status code + $response = $response->withHeader('Content-Type', 'application/json') + ->withHeader('Pragma', 'no-cache') + ->withStatus(422); + + // Write to the body + $body = $response->getBody(); + $body->write(json_encode(['errno' => $errorCode])); + +Créer un Middleware +=================== + +Middleware can either be implemented as anonymous functions (Closures), or as +invokable classes. While Closures are suitable for smaller tasks they make +testing harder, and can create a complicated ``Application`` class. Middleware +classes in CakePHP have a few conventions: + +* Middleware class files should be put in **src/Middleware**. For example: + **src/Middleware/CorsMiddleware.php** +* Middleware classes should be suffixed with ``Middleware``. For example: + ``LinkMiddleware``. +* Middleware are expected to implement the middleware protocol. + +Protocole du Middleware +----------------------- + +While not a formal interface (yet), Middleware do have a soft-interface or +protocol. The protocol is as follows: + +#. Middleware must implement ``__invoke($request, $response, $next)``. +#. Middleware must return an object implementing the PSR7 ``ResponseInterface``. + +Middleware can return a response either by calling ``$next`` or by creating +their own response. We can see both options in our simple middleware:: + + // In src/Middleware/SimpleMiddleware.php + namespace App\Middleware; + + class SimpleMiddleware + { + function __invoke($request, $response, $next) + { + // If we find /simple/ in the URL return a simple response. + if (strpos($request->getUri()->getPath(), '/simple/') !== false) { + $body = $response->getBody(); + $body->write('Thanks!'); + return $response->withStatus(202) + ->withHeader('Content-Type', 'text/plain') + ->withBody($body); + } + + // Calling $next() delegates control to then *next* middleware + // In your application's stack. + $response = $next($request, $response); + + // We could further modify the response before returning it. + return $response; + } + } + +Now that we've made a very simple middleware, let's attach it to our +application:: + + // In src/Application.php + namespace App; + + use App\Middleware\SimpleMiddleware; + + class Application + { + public function middleware($middleware) + { + // Push your simple middleware onto the stack + $middleware->push(new SimpleMiddleware()); + + // Push some more middleware onto the stack + + return $middleware; + } + } + +.. _adding-http-stack: + +Adding the new HTTP Stack to an Existing Application +==================================================== + +TODO .. meta:: - :title lang=fr: Middleware - :keywords lang=fr: middleware + :title lang=fr: Http Middleware + :keywords lang=fr: http, middleware, psr7, request, response, wsgi, application, baseapplication diff --git a/fr/core-libraries/httpclient.rst b/fr/core-libraries/httpclient.rst index 98c141ef3e..ffe2302b85 100644 --- a/fr/core-libraries/httpclient.rst +++ b/fr/core-libraries/httpclient.rst @@ -350,11 +350,12 @@ les paramètres ``$options`` de la requête:: 'cookies' => ['sessionid' => '123abc'] ]); +.. _httpclient-response-objects: Objets Response =============== -.. php:namepspace:: Cake\Http\Client +.. php:namespace:: Cake\Http\Client .. php:class:: Response From d38a48d1ec6c75cb99241d156dd31a908c5b601d Mon Sep 17 00:00:00 2001 From: cake17 Date: Mon, 6 Jun 2016 11:08:40 +0200 Subject: [PATCH 18/19] [fr] small changes to check sphinx warnings --- fr/controllers/middleware.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/fr/controllers/middleware.rst b/fr/controllers/middleware.rst index ef841835ff..81a0656b64 100644 --- a/fr/controllers/middleware.rst +++ b/fr/controllers/middleware.rst @@ -1,11 +1,12 @@ Middleware ########## -Middleware objects give you the ability to 'wrap' your application in re-usable, -composable layers of Request handling, or response building logic. Middleware -are part of the new HTTP stack in CakePHP that leverages the PSR7 request and -response interfaces. By leveraging the PSR7 standard you can use any PSR7 -compatible middleware available on `The Packagist `__. +Les objets Middleware vous donnent la possibilité de 'wrapper' votre application +en des couches compatibles et réutilisables de gestion de Requête, ou de la +logique de construction de réponse. Middleware are part of the new HTTP stack in +CakePHP that leverages the PSR7 request and response interfaces. By leveraging +the PSR7 standard you can use any PSR7 compatible middleware available on `The +Packagist `__. CakePHP provides several middleware out of the box: From 0d72c6fda59d07a56c9867fddd89f1b6e835da81 Mon Sep 17 00:00:00 2001 From: cake17 Date: Mon, 6 Jun 2016 11:19:31 +0200 Subject: [PATCH 19/19] [fr] small changes to check sphinx warnings --- fr/controllers/middleware.rst | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr/controllers/middleware.rst b/fr/controllers/middleware.rst index 81a0656b64..32addbf48f 100644 --- a/fr/controllers/middleware.rst +++ b/fr/controllers/middleware.rst @@ -3,12 +3,12 @@ Middleware Les objets Middleware vous donnent la possibilité de 'wrapper' votre application en des couches compatibles et réutilisables de gestion de Requête, ou de la -logique de construction de réponse. Middleware are part of the new HTTP stack in -CakePHP that leverages the PSR7 request and response interfaces. By leveraging -the PSR7 standard you can use any PSR7 compatible middleware available on `The -Packagist `__. +logique de construction de réponse. Middleware sont une partie du nouveau HTTP +stack dans qui tire parti des interfaces PSR7 request et response. En tirant +parti du standard PSR7, vous pouvez utilisez tout middleware compatible avec +PSR7 qui se trouve sur `Packagist `__. -CakePHP provides several middleware out of the box: +CakePHP fournit plusieurs middlewares: * ``Cake\Error\Middleware\ErrorHandlerMiddleware`` traps exceptions from the wrapped middleware and renders an error page using the