1
\$\begingroup\$

In my controller I had the idea to do something like the following:

// retrieve fields from form
$firstname = $form->getInput('firstname');
$lastname = $form->getInput('lastname');
[...]
// create Member object
$member = new Member($firstname, $lastname, [...]);
// save Member in DB
$this->_daoFactory->get('Member')->save($member);

In this example, the DAO factory would create an instance of the MemberDAO class, which (I guess) acts like a data mapper? And allows me to save the Member object in DB, to update a Member, get a Member from id, and other db requests probably.

What do you think about this code?

Thank you for your review!

\$\endgroup\$
1
\$\begingroup\$

A lot of MVC frameworks do the datamapping in the same class (usually with static methods). I would also avoid creating hard links between controllers and models (like having each model property as a parameter in the class constructor). Something like this is a little more elegant, IMO:

<?php

// Model
class Member
{
    public static function forge(array $data = array())
    {
        return new static($data);
    }

    public function __construct(array $data = array())
    {
        foreach ($data as $k => $v)
        {
            // consider checking here for expected properties,
            // sanitizing input, etc.
            $this->$k = $v;
        }
    }

    public function save()
    {
        // If primary key exists, run DB update query
        // Otherwise, run insert query

        // Return success/failure information (and/or throw exceptions)
    }
}

// Controller action
$member = Member::forge($form->get_sanitized_postdata());
$member->save();
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Why didn't you instantiate with "new" operator instead? $member = new Member($form->get_sanitized_postdata()); \$\endgroup\$ – Matthew Jun 21 '13 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.