dflydev / dflydev-fig-cookies

Cookies for PSR-7 HTTP Message Interface.
MIT License
224 stars 29 forks source link

Implement easy immutable object creation #48

Closed dafriend closed 2 years ago

dafriend commented 3 years ago

Since the point of immutable objects is to create them in a state that cannot be modified. Shouldn't it be possible to achieve the desired end-state without leaving a long trail of immutable objects in our wake?

This PR adds two methods to allow efficient immutable object creation by using configuration arrays. In essence, we get to the full state we need without chaining a lot of ->withSomeSetting($value) calls.

The method withConfig(array $config) allows a bulk mutation of an existing SetCookie, e.g.

$setCookie = SetCookie::create('lu')->withConfig($config);

The second addition is the method fromConfig(array $config) allows creating a new SetCookie with a minimal amount of cloning.

$setCookie = SetCookie::fromConfig($config);  // truthfully, this is essentially a decoration of the first example

The following $config could be used for both examples.

$config = [ 'name' => 'lu', 'value' => 'Rg3vHJZnehYLjVg7qi3bZjzg', 'expires' => 'Tue, 15-Jan-2013 21:47:38 GMT', 'maxAge' => 500, 'path' => '/', 'domain' => '.example.com', 'secure' => true, 'httpOnly' => true, 'samesite' => 'lax' ];

I may not understand all I know about immutable objects. I look forward to any feedback offered.

dafriend commented 2 years ago

Closed for lack of interest.