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!

asked Jun 5, 2013 at 22:33
\$\endgroup\$

1 Answer 1

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();
answered Jun 11, 2013 at 23:51
\$\endgroup\$
1
  • \$\begingroup\$ Why didn't you instantiate with "new" operator instead? $member = new Member($form->get_sanitized_postdata()); \$\endgroup\$ Commented Jun 21, 2013 at 0:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.