I am following data mapper guide. But it has a model class in the mapper class. So I modified it by using dependency injection.
Model,
class User
{
/**
* @var int
*/
protected $userId;
/**
* @var string
*/
protected $username;
/**
* @var string
*/
protected $email;
/**
* @param null $id
* @param null $username
* @param null $email
*/
public function __construct($id = null, $username = null, $email = null)
{
$this->userId = $id;
$this->username = $username;
$this->email = $email;
}
/**
* @return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* @param int $userId
*/
public function setUserID($userId)
{
$this->userId = $userId;
}
/**
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
}
Mapper,
class UserMapper
{
public function __construct($model)
{
$this->model = $model;
}
public function findAll()
{
$resultSet = array(
array('userid' => 1, 'username' => 'Odysseus', 'email' => 'Odysseus@ithaca.gr'),
array('userid' => 2, 'username' => 'Penelope', 'email' => 'Penelope@ithaca.gr')
);
$entries = array();
foreach ($resultSet as $row) {
$entries[] = $this->mapObject($row);
}
return $entries;
}
protected function mapObject(array $row)
{
$this->model->setUserID($row['userid']);
$this->model->setUsername($row['username']);
$this->model->setEmail($row['email']);
return $this->model;
}
}
Usage,
$model = new User();
$mapper = new UserMapper($model);
$users = $mapper->findAll();
print_r($users);
Result (which is incorrect),
Array
(
[0] => User Object
(
[userId:protected] => 2
[username:protected] => Penelope
[email:protected] => Penelope@ithaca.gr
)
[1] => User Object
(
[userId:protected] => 2
[username:protected] => Penelope
[email:protected] => Penelope@ithaca.gr
)
)
But it returns the correct result without dependency injection,
protected function mapObject(array $row)
{
$entry = new User();
$entry->setUserID($row['userid']);
$entry->setUsername($row['username']);
$entry->setEmail($row['email']);
return $entry;
}
Result,
Array
(
[0] => User Object
(
[userId:protected] => 1
[username:protected] => Odysseus
[email:protected] => Odysseus@ithaca.gr
)
[1] => User Object
(
[userId:protected] => 2
[username:protected] => Penelope
[email:protected] => Penelope@ithaca.gr
)
)
So, how can I use dependency injection with data mapper to return the correct result? any ideas?
Aucun commentaire:
Enregistrer un commentaire