views:

94

answers:

1

Hi there,

I currently work on a small application with models, mappers and controllers. My question is, (because I did not found any matching answer), how does the mapper interact with the model (& the controller), when we have the following situation.

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

This will work as fine as possible, the model has an id with which the mapper can retrieve the needed user (and map it back into an user object).

My problem is, how can I wrap this code, I mean, this code is very raw and it is definitly not very recommended to be used in a controller. I want to shorten it, but I do not exactly know how:

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);
}

It should look more like:

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);
}

But this is much more code. Should I include the getMapper procedure within the parent controller class, so I can easily access $this->_mapper without explicitly calling it?

The problem is, I do not want to break the mapper pattern, so the the Model should not access any SQL/Mapper method directly by $model->find(), but I do not want to have a lot of code just for first creating a mapper and do this and this etc.

I hope you'll understand me a little bit, myself is already confused enough, because I am new to many patterns and mapping/modelling techniques.

best regards,

+1  A: 

You could add a Service Layer, e.g.

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();
    }
}

Your controller won't access the UserModel and the UserMapper directly, but through the Service.

Gordon
Thanks ;) but I still have to call the Service class(es) within my controller.
daemonfire300
I'm not sure I understand what your question is then? Are you looking for Dependency Injection, e.g. http://components.symfony-project.org/dependency-injection/
Gordon
Yep this helped me too, thank you very much ;)
daemonfire300