I've just added this method to my class:
/**
* @param string|StreamableInterface $body
* @return Message
*/
public function setBody($body) {
$this->body = $body instanceof StreamableInterface ? $body : new StringStream($body, true);
return $this;
}
And now it occurs to me that the semantics are a little bit different depending on if you pass the method a string or an object.
If you give it a string, it will construct a new object, otherwise it will just create a reference to the object you provide, which means that you can further modify that object from outside this class in one case, but not the other.
Is this bad practice? Should I create a full clone of the object if you pass one in? I'm not sure what the expected behaviour is.
In my opinion, the stream shouldn't be cloned and you should keep your code the way it is. I would even consider what you have done best practice. If someone wants the object to have its own isolated stream, then they should give the object its own stream—I would leave that decision up to the caller.
Your method is what is commonly done in almost every similar scenario I have seen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With