One of the new components coming with CakePHP 1.2 is the cookie component. It is a rather simple component, so it is very easy to use this component. Let us do an example.

As always when using a component we have to add the cookie component to the $components array of our controller:

var $components = array('Cookie');

If we now call our controller in the browser we will see the following notices (if we are in the debug modus):

Notice: For added security you should add the var cookieName to your Controller or AppController in
/home/dho/projects/cake_1.2.x.x/cake/libs/controller/components/cookie.php on line 153

Notice: For added security you should add the var cookieKey to your Controller or AppController in
/home/dho/projects/cake_1.2.x.x/cake/libs/controller/components/cookie.php on line 161

Notice: Add var cookieDomain = .yourdomain.com; to your Controller or AppController to allow access on all subdomains in
/home/dho/projects/cake_1.2.x.x/cake/libs/controller/components/cookie.php on line 169

To remove these notices we do what is recommended in the notices and add the expected variables to our controller:

var $cookieName = 'myCookie';
var $cookieKey = 'has82js737hak2';
var $cookieDomain = '.myproject.localhost';

As it is not very cool to add a development domain to the code, we will refactor a bit and set the domain dynamically in the constructor:

var $cookieDomain;

function __construct() {
    parent::__construct();
    $this->cookieDomain = '.'.$_SERVER['SERVER_NAME'];
}

Writing to the cookie and reading from it is as you would expect:

$this->Cookie->write('User.id', 1);

respectively

$this->Cookie->read('User.id');

For more details see the API (thanks to Christian Winther aka Jippi for providing these API docs).

P.S.: For those of you who are using my unofficial test suite there is a new version available which supports the cookie component. You can use it in your tests as shown in the following test function which tests that a user with a cookie is automatically logged in when requesting /users/login:

function testLoginWithCookie() {
    $this->get('/users/login', null, array('User.id' => $this->dho['id']));
    $this->assertRedirectedTo(’/projects’);
}

You can also check if the correct value has been written to the cookie with something like:

$this->assertEqual($this->dho['id'], $this->cookie['User.id']);