2011-09-26 79 views
1

我有一個對象,表示用戶在我的網站上的帳戶,以及一個獨立的對象,充當主帳戶對象的附件,並擴展了用戶在網站上運行一些主要功能的能力 - 一個功能齊全的店面。根據加載順序允許對象存儲在對方中可以嗎?

我一直代表的關係像這樣:

Class Account { 
    $id 
    $store // this is the store object 
    $email 
    $password 
    $status 

    get_store() // loads the store 
} 

Class Store { 
    $id // unique store id 
    $store_name 
    $store_info 

    post_item() 
} 

到目前爲止,這一直很好,但是當我搜索或集合店這種方式,它需要我去通過賬戶對象來獲取到商店。

我想通過商店能夠訪問賬戶對象,將流程減半。

它是否也創建了一個問題,也允許一個$ account對象存儲在$ store對象中,以防萬一我想以另一種方式加載它?

允許這種雙向負荷將如下的例子:

Class Account { 
    $id 
    $store // this is the store object 
    $email 
    $password 
    $status 

    get_store() // loads the store 
} 

Class Store { 
    $id 
    $account // this is the account object 
    $store_name 
    $store_info 

    get_account() // loads the account 
    post_item() 
} 

回答

2

這是一個常見的重構。唯一需要注意的是,當您將一個對象與另一個對象關聯時,您將需要管理「返回指針」,例如,當爲一個賬戶提取商店時,你必須確保商店也會得到該賬戶的反向指針,反之亦然。

延伸閱讀:

+0

它是用PHP,你需要管理的返回指針的情況下?或者這是一種不同的語言?謝謝閱讀! – johnnietheblack

+1

@johnnie雙向意味着A有一個B有一個A,所以它不依賴於語言。 – Gordon

相關問題