为什么要在oop中返回一个对象的克隆?
问题描述:
我最近不得不使用Slim\Http\Message
和Slim\Http\Request
来获取用户发布的数据。为什么要在oop中返回一个对象的克隆?
我注意到方法withBody()
中的一些东西,它返回对象的克隆而不是$this
。
这给我带来了一些麻烦,因为我无法让我的应用程序工作,直到我将$request->withBody(...)
分配给变量($request
),然后在脚本中使用该新变量继续使用。
我有一个模拟的例子来解释(见代码中的注释);
class Request {
protected $body;
public function addBody($body) {
$clone = clone $this;
$clone->body = $body;
return $clone;
}
public function getBody() {
return $this->body;
}
}
$request = new Request;
// this will return NULL
$request->addBody([
'name' => 'john',
'email' => '[email protected]',
]);
var_dump($request->getBody());
// -----------------------
// but this will return the "body" that was passed in above.
$request = $request->addBody([
'name' => 'john',
'email' => '[email protected]',
]);
var_dump($request->getBody());
我看到这里发生了什么。但我不明白为什么一个类会像这样实现。
有什么好处?为什么要以这种方式限制开发人员?
答
苗条使用PSR-7 HTTP消息接口标准,它描述本身如下:
<?php
namespace Psr\Http\Message;
/**
* HTTP messages consist of requests from a client to a server and responses
* from a server to a client. This interface defines the methods common to
* each.
*
* Messages are considered immutable; all methods that might change state MUST
* be implemented such that they retain the internal state of the current
* message and return an instance that contains the changed state.
*
* @see http://www.ietf.org/rfc/rfc7230.txt
* @see http://www.ietf.org/rfc/rfc7231.txt
*/
interface MessageInterface
{
//etc
}
“的消息被认为是不可变”。它们被认为是Value对象,它绝对不能改变状态,如果你想改变状态,就返回一个新的实例。
这里有一个链接解释值对象http://deviq.com/value-object/
并从页面有点提取物我联系:
值对象是不可变的类型,只有 其属性的状态是可区分的。也就是说,不同于具有 唯一标识符并且保持不同的实体,即使其属性为 ,否则其相同,具有完全相同属性 的两个值对象可以被认为是相等的。值对象是在Evans的领域驱动设计书中首次描述的 模式,并且在Smith 和Lerman的领域驱动设计基础课程中进一步解释。
希望这会帮助你理解为什么!
最后,必须在实际的PSR-7标准凌晨看看这里http://www.php-fig.org/psr/psr-7/
您可能需要研究“[不可改变的对象(https://blog.joefallon.net/2015/08/immutable-objects -in-PHP /)”。 – Fildor
和函数式编程 –
投票结束为基于意见。尝试https://softwareengineering.stackexchange.com我无法投票迁移它 –