Skip to content
This repository has been archived by the owner on Dec 31, 2022. It is now read-only.

Return $this directly without using clone class instance #7

Open
peter279k opened this issue Feb 11, 2019 · 2 comments
Open

Return $this directly without using clone class instance #7

peter279k opened this issue Feb 11, 2019 · 2 comments

Comments

@peter279k
Copy link
Member

As title, please consider the following sample code firstly:

public function withCookieParams(array $cookieParams) : ServerRequestInterface
{
     $clone = clone $this;
     $clone->cookieParams = $cookieParams;
     return $clone;
}

How about using the following code?

public function withCookieParams(array $cookieParams) : ServerRequestInterface
{
     $this->cookieParams = $cookieParams;
     return $this;
}

I think using the clone to clone $this instance is not necessary because it should override the methods/attributes on $this class instance.

@fenric
Copy link
Member

fenric commented Feb 11, 2019

Hello @peter279k :)

This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
updated cookie values.

Source: https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface

/**
 * Return an instance with the specified cookies.
 *
 * The data IS NOT REQUIRED to come from the $_COOKIE superglobal, but MUST
 * be compatible with the structure of $_COOKIE. Typically, this data will
 * be injected at instantiation.
 *
 * This method MUST NOT update the related Cookie header of the request
 * instance, nor related values in the server params.
 *
 * This method MUST be implemented in such a way as to retain the
 * immutability of the message, and MUST return an instance that has the
 * updated cookie values.
 *
 * @param array $cookies Array of key/value pairs representing cookies.
 * @return static
 */

@peter279k
Copy link
Member Author

peter279k commented Feb 12, 2019

Hi @fenric, thank you for your reply.

You explain that makes sense.

How about using the following code:

...
	public function withServerParams(array $serverParams) : ServerRequestInterface
	{
                if ($this->serverParams === $serverParams) {
                    return $this;
                }

		$clone = clone $this;
		$clone->serverParams = $serverParams;
		return $clone;
	}
...

We can check whether the params are different before setting new params.

And it can prevent the unnecessary setting params and cloning instance work.

It has the same issues for other methods on this package.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants