2009-12-30 248 views
1

我目前正在使用模型,映射器和控制器的小應用程序。 我的問題是,(因爲我沒有找到任何匹配的答案),當我們遇到以下情況時,映射器如何與模型(&控制器)進行交互。模型和映射關係

$user = new UserModel(); 
$user->setId('21'); 
$userMapper = new UserMapper($user); 
$userMapper->retrieve(); 

這將工作得很好,模型有一個id,映射器可以檢索所需用戶(並將其映射回用戶對象)。

我的問題是,如何包裝這段代碼,我的意思是,這段代碼非常原始,並且明確地不建議在控制器中使用。 我想縮短它,但我不知道究竟如何:

public function view($id) 
{ 
    $user->find($id); // this seems always to be tied with the user object/model (e.g. cakephp), but I think the ->find operation is done by the mapper and has absolutly nothing to do with the model 
    $view->assign('user',$user); 
} 

它看起來更像是:

public function view($id) 
{ 
    $mapper = $registry->getMapper('user'); 
    $user = $mapper->find($id); 
    // or a custom UserMapper method: 
    # $user = $mapper->findById($id); 
    $view->assign('user',$user); 
} 

但這是太多的代碼。 我應該在父級控制器類中包含getMapper過程,因此我可以在不明確調用它的情況下輕鬆訪問$this->_mapper

問題是,我不想破壞映射器模式,所以模型不應該直接通過$model->find()來訪問任何SQL /映射器方法,但我不想有很多代碼只是爲了首先創建一個映射器和做到這一點,這等

我希望你能夠理解我一點點,我自己已經夠糊塗,因爲我是新來的許多模式和繪圖/建模技術。

+1

馬上跟隨模式是沒有意義的;)只要做一些對你來說很方便的事情。模式應該爲你節省時間並幫助你找出解決問題的方法,但它們不是你必須遵循的宗教。 – openfrog 2010-01-04 18:19:54

回答

1

您可以添加一個Service Layer,例如,

class UserService 
{ 
    public function findUserById($id) 
    { 
     // copied and adjusted from question text 
     $user = new UserModel(); 
     $user->setId($id); 
     $userMapper = new UserMapper($mapper); 
     return $userMapper->retrieve(); 
    } 
} 

您的控制器將不能直接訪問的usermodel和UserMapper,而是通過服務。

+0

謝謝;)但我仍然需要在我的控制器中調用Service類。 – 2009-12-30 12:54:15

+1

我不確定我明白你的問題是什麼?您是否在尋找依賴注入,例如http://components.symfony-project.org/dependency-injection/ – Gordon 2009-12-30 12:59:59

+0

是啊幫我也非常感謝你;) – 2009-12-30 13:15:11