Skip to content
Mark Story edited this page Mar 5, 2017 · 1 revision

CakePHP 3.5.0 will feature a new set of cookie objects that provide an OO interface to building and using HTTP cookies. In addition to the Cookie object, we have a few different Cookie 'collections'. I'd like to unify those collections with the goal of only having 1 single cookie collection.

Use Cases for a CookieCollection

CookieCollections are used in a few different places in CakePHP:

  1. In an Http\Client as a cookie jar where state is retained between client requests.
  2. Adding cookies to a Controller Response.
  3. Reading cookie data from a ServerRequest.

Each use case requires some common methods and some use-case specific methods.

Generic Methods

  • Iteration (IteratorAggregate)
  • has($key) - Check if a cookie exists
  • get($key) - Get a cookie
  • remove($key) - Remove a cookie
  • add($cookie) - Add a cookie
  • all() - Get all the cookies.

Methods specific to Http\Client usage

  • addFromResponse($response, $request) - Add cookies from a response. A request is needed to infer the path and domain of cookies that have not included it.
  • addToRequest($request) - Apply all the cookies matching this request.

These two methods allow a CookieCollection to function as a 'cookie jar' for the client.

Methods specific to adding cookies to a Controller Response

  • addToResponse($response) - Add cookies in the collection to a response.

Methods specific to Reading cookie data from a ServerRequest

  • createFromRequest($request) - Build a new CookieCollection from a request object.

All of the above methods could be implemented in a single class allowing us to streamline how users have to interact with cookies in CakePHP even further.