mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-02-24 09:42:24 +01:00
46 lines
1.0 KiB
PHP
46 lines
1.0 KiB
PHP
<?php
|
|
|
|
namespace DesignPatterns\Structural\DataMapper;
|
|
|
|
class UserMapper
|
|
{
|
|
/**
|
|
* @var StorageAdapter
|
|
*/
|
|
private $adapter;
|
|
|
|
/**
|
|
* @param StorageAdapter $storage
|
|
*/
|
|
public function __construct(StorageAdapter $storage)
|
|
{
|
|
$this->adapter = $storage;
|
|
}
|
|
|
|
/**
|
|
* 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.
|
|
* However the important part is in mapRowToUser() below, that will create a business object from the
|
|
* data fetched from storage
|
|
*
|
|
* @param int $id
|
|
*
|
|
* @return User
|
|
*/
|
|
public function findById(int $id): User
|
|
{
|
|
$result = $this->adapter->find($id);
|
|
|
|
if ($result === null) {
|
|
throw new \InvalidArgumentException("User #$id not found");
|
|
}
|
|
|
|
return $this->mapRowToUser($result);
|
|
}
|
|
|
|
private function mapRowToUser(array $row): User
|
|
{
|
|
return User::fromState($row);
|
|
}
|
|
}
|