2017-09-20 68 views
2

我最近不得不使用Slim\Http\MessageSlim\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()); 

我看到這裏發生了什麼。但我不明白爲什麼一個類會像這樣實現。

有什麼好處?爲什麼要以這種方式限制開發人員?

+4

您可能需要研究「[不可改變的對象(https://blog.joefallon.net/2015/08/immutable-objects -in-PHP /)」。 – Fildor

+0

和函數式編程 –

+0

投票結束爲基於意見。嘗試https://softwareengineering.stackexchange.com我無法投票遷移它 –

回答

3

苗條使用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/