4 Methods to Create Cookie Object in Symfony 7

4 Methods to Create Cookie Object in Symfony 7

In Symfony application, the Cookie class is used to represent HTTP cookie. There are various ways to create an object of that class.

This tutorial provides 4 methods how to create Cookie object in Symfony 7 application.

Method 1 - 'new' keyword

We can use the new keyword to create an object of the Cookie class. Pass cookie name, value, and other arguments to constructor.

<?php

use Symfony\Component\HttpFoundation\Cookie;

$cookie = new Cookie('name', 'John');

Method 2 - 'create' static method

An object of the Cookie class can be created using create static method.

<?php

use Symfony\Component\HttpFoundation\Cookie;

$cookie = Cookie::create('name', 'John');

Method 3 - 'create' and 'withXXX' methods

The create static method of the Cookie class accepts many optional arguments. Only one argument is required, which is the cookie name. Instead of providing arguments to the create method, we can use withXXX methods (e.g. withValue, withExpires) for constructing the Cookie object. Each withXXX method returns a new Cookie object.

<?php

use Symfony\Component\HttpFoundation\Cookie;

$cookie = Cookie::create('name')
    ->withValue('John');

Method 4 - 'fromString' static method

We can create an object of the Cookie class from a raw header value using fromString static method.

<?php

use Symfony\Component\HttpFoundation\Cookie;

$cookie = Cookie::fromString('name=John');

Leave a Comment

Cancel reply

Your email address will not be published.