PHP7 DataMapper

This commit is contained in:
Dominik Liebler
2016-09-22 21:04:16 +02:00
parent 320dc3c6bf
commit 243456b2da
8 changed files with 777 additions and 645 deletions

View File

@@ -47,6 +47,12 @@ UserMapper.php
:language: php :language: php
:linenos: :linenos:
StorageAdapter.php
.. literalinclude:: StorageAdapter.php
:language: php
:linenos:
Test Test
---- ----

View File

@@ -0,0 +1,30 @@
<?php
namespace DesignPatterns\Structural\DataMapper;
class StorageAdapter
{
/**
* @var array
*/
private $data = [];
public function __construct(array $data)
{
$this->data = $data;
}
/**
* @param int $id
*
* @return array|null
*/
public function find(int $id)
{
if (isset($this->data[$id])) {
return $this->data[$id];
}
return null;
}
}

View File

@@ -2,109 +2,29 @@
namespace DesignPatterns\Structural\DataMapper\Tests; namespace DesignPatterns\Structural\DataMapper\Tests;
use DesignPatterns\Structural\DataMapper\User; use DesignPatterns\Structural\DataMapper\StorageAdapter;
use DesignPatterns\Structural\DataMapper\UserMapper; use DesignPatterns\Structural\DataMapper\UserMapper;
/**
* UserMapperTest tests the datamapper pattern.
*/
class DataMapperTest extends \PHPUnit_Framework_TestCase class DataMapperTest extends \PHPUnit_Framework_TestCase
{ {
/** public function testCanMapUserFromStorage()
* @var UserMapper
*/
protected $mapper;
/**
* @var DBAL
*/
protected $dbal;
protected function setUp()
{ {
$this->dbal = $this->getMockBuilder('DesignPatterns\Structural\DataMapper\DBAL') $storage = new StorageAdapter([1 => ['username' => 'domnikl', 'email' => 'liebler.dominik@gmail.com']]);
->disableAutoload() $mapper = new UserMapper($storage);
->setMethods(array('insert', 'update', 'find', 'findAll'))
->getMock();
$this->mapper = new UserMapper($this->dbal); $user = $mapper->findById(1);
}
public function getNewUser() $this->assertInstanceOf('DesignPatterns\Structural\DataMapper\User', $user);
{
return array(array(new User(null, 'Odysseus', 'Odysseus@ithaca.gr')));
}
public function getExistingUser()
{
return array(array(new User(1, 'Odysseus', 'Odysseus@ithaca.gr')));
}
/**
* @dataProvider getNewUser
*/
public function testPersistNew(User $user)
{
$this->dbal->expects($this->once())
->method('insert');
$this->mapper->save($user);
}
/**
* @dataProvider getExistingUser
*/
public function testPersistExisting(User $user)
{
$this->dbal->expects($this->once())
->method('update');
$this->mapper->save($user);
}
/**
* @dataProvider getExistingUser
*/
public function testRestoreOne(User $existing)
{
$row = array(
'userid' => 1,
'username' => 'Odysseus',
'email' => 'Odysseus@ithaca.gr',
);
$rows = new \ArrayIterator(array($row));
$this->dbal->expects($this->once())
->method('find')
->with(1)
->will($this->returnValue($rows));
$user = $this->mapper->findById(1);
$this->assertEquals($existing, $user);
}
/**
* @dataProvider getExistingUser
*/
public function testRestoreMulti(User $existing)
{
$rows = array(array('userid' => 1, 'username' => 'Odysseus', 'email' => 'Odysseus@ithaca.gr'));
$this->dbal->expects($this->once())
->method('findAll')
->will($this->returnValue($rows));
$user = $this->mapper->findAll();
$this->assertEquals(array($existing), $user);
} }
/** /**
* @expectedException \InvalidArgumentException * @expectedException \InvalidArgumentException
* @expectedExceptionMessage User #404 not found
*/ */
public function testNotFound() public function testWillNotMapInvalidData()
{ {
$this->dbal->expects($this->once()) $storage = new StorageAdapter([]);
->method('find') $mapper = new UserMapper($storage);
->with(404)
->will($this->returnValue(array()));
$user = $this->mapper->findById(404); $mapper->findById(1);
} }
} }

View File

@@ -2,56 +2,34 @@
namespace DesignPatterns\Structural\DataMapper; namespace DesignPatterns\Structural\DataMapper;
/**
* DataMapper pattern.
*
* This is our representation of a DataBase record in the memory (Entity)
*
* Validation would also go in this object
*/
class User class User
{ {
/** /**
* @var int * @var string
*/ */
protected $userId; private $username;
/** /**
* @var string * @var string
*/ */
protected $username; private $email;
/** public static function fromState(array $state): User
* @var string
*/
protected $email;
/**
* @param null $id
* @param null $username
* @param null $email
*/
public function __construct($id = null, $username = null, $email = null)
{ {
$this->setUserID($id); // validate state before accessing keys!
$this->setUsername($username);
$this->setEmail($email); return new self(
$state['username'],
$state['email']
);
} }
/** public function __construct(string $username, string $email)
* @return int
*/
public function getUserId()
{ {
return $this->userId; // validate parameters before setting them!
}
/** $this->username = $username;
* @param int $userId $this->email = $email;
*/
public function setUserID($userId)
{
$this->userId = $userId;
} }
/** /**
@@ -62,14 +40,6 @@ class User
return $this->username; return $this->username;
} }
/**
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/** /**
* @return string * @return string
*/ */
@@ -77,12 +47,4 @@ class User
{ {
return $this->email; return $this->email;
} }
/**
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
} }

View File

@@ -2,107 +2,44 @@
namespace DesignPatterns\Structural\DataMapper; namespace DesignPatterns\Structural\DataMapper;
/**
* class UserMapper.
*/
class UserMapper class UserMapper
{ {
/** /**
* @var DBAL * @var StorageAdapter
*/ */
protected $adapter; private $adapter;
/** /**
* @param DBAL $dbLayer * @param StorageAdapter $storage
*/ */
public function __construct(DBAL $dbLayer) public function __construct(StorageAdapter $storage)
{ {
$this->adapter = $dbLayer; $this->adapter = $storage;
} }
/** /**
* saves a user object from memory to Database. * finds a user from storage based on ID and returns a User object located
* * in memory. Normally this kind of logic will be implemented using the Repository pattern.
* @param User $user * However the important part is in mapRowToUser() below, that will create a business object from the
* * data fetched from storage
* @return bool
*/
public function save(User $user)
{
/* $data keys should correspond to valid Table columns on the Database */
$data = array(
'userid' => $user->getUserId(),
'username' => $user->getUsername(),
'email' => $user->getEmail(),
);
/* if no ID specified create new user else update the one in the Database */
if (null === ($id = $user->getUserId())) {
unset($data['userid']);
$this->adapter->insert($data);
return true;
} else {
$this->adapter->update($data, array('userid = ?' => $id));
return true;
}
}
/**
* finds a user from Database based on ID and returns a User object located
* in memory.
* *
* @param int $id * @param int $id
* *
* @throws \InvalidArgumentException
*
* @return User * @return User
*/ */
public function findById($id) public function findById(int $id): User
{ {
$result = $this->adapter->find($id); $result = $this->adapter->find($id);
if (0 == count($result)) { if ($result === null) {
throw new \InvalidArgumentException("User #$id not found"); throw new \InvalidArgumentException("User #$id not found");
} }
$row = $result->current();
return $this->mapObject($row); return $this->mapRowToUser($result);
} }
/** private function mapRowToUser(array $row): User
* fetches an array from Database and returns an array of User objects
* located in memory.
*
* @return array
*/
public function findAll()
{ {
$resultSet = $this->adapter->findAll(); return User::fromState($row);
$entries = array();
foreach ($resultSet as $row) {
$entries[] = $this->mapObject($row);
}
return $entries;
}
/**
* Maps a table row to an object.
*
* @param array $row
*
* @return User
*/
protected function mapObject(array $row)
{
$entry = new User();
$entry->setUserID($row['userid']);
$entry->setUsername($row['username']);
$entry->setEmail($row['email']);
return $entry;
} }
} }

View File

@@ -1,22 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Diagram> <Diagram>
<ID>PHP</ID> <ID>PHP</ID>
<OriginalElement>\DesignPatterns\Structural\DataMapper\User</OriginalElement> <OriginalElement>\DesignPatterns\Structural\DataMapper\StorageAdapter</OriginalElement>
<nodes> <nodes>
<node x="0.0" y="185.0">\DesignPatterns\Structural\DataMapper\UserMapper</node>
<node x="204.0" y="185.0">\DesignPatterns\Structural\DataMapper\StorageAdapter</node>
<node x="0.0" y="0.0">\DesignPatterns\Structural\DataMapper\User</node> <node x="0.0" y="0.0">\DesignPatterns\Structural\DataMapper\User</node>
<node x="0.0" y="274.0">\DesignPatterns\Structural\DataMapper\UserMapper</node>
</nodes> </nodes>
<notes /> <notes />
<edges /> <edges />
<settings layout="Hierarchic Group" zoom="0.871331828442438" x="141.5" y="211.5" /> <settings layout="Hierarchic Group" zoom="1.0" x="64.0" y="88.5" />
<SelectedNodes> <SelectedNodes>
<node>\DesignPatterns\Structural\DataMapper\User</node> <node>\DesignPatterns\Structural\DataMapper\StorageAdapter</node>
</SelectedNodes> </SelectedNodes>
<Categories> <Categories>
<Category>Methods</Category>
<Category>Fields</Category> <Category>Fields</Category>
<Category>Constants</Category> <Category>Constants</Category>
<Category>Constructors</Category>
<Category>Methods</Category>
</Categories> </Categories>
<VISIBILITY>private</VISIBILITY> <VISIBILITY>private</VISIBILITY>
</Diagram> </Diagram>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 39 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 112 KiB