型号&映射器关系

时间:2009-12-30 12:41:08

标签: php model-view-controller model datamapper

我目前正在使用模型,映射器和控制器的小应用程序。 我的问题是,(因为我没有找到任何匹配的答案),当我们遇到以下情况时,映射器如何与模型(和控制器)进行交互。

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

这将尽可能好,模型有一个id,映射器可以使用该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 / Mapper方法,但我不希望有很多代码只是为了首先创建一个映射器并执行此操作等。

我希望你能理解我一点,我自己已经足够困惑了,因为我是很多模式和绘图/建模技术的新手。

1 个答案:

答案 0 :(得分: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,而是通过服务。

相关问题