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!
1 Answer 1
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();
-
\$\begingroup\$ Why didn't you instantiate with "new" operator instead? $member = new Member($form->get_sanitized_postdata()); \$\endgroup\$Matthew– Matthew2013年06月21日 00:09:19 +00:00Commented Jun 21, 2013 at 0:09