Data Mapper Code Examples of PHP Design Patterns (13)

aims

The data mapper is a data access layer used to transfer data in both directions between a persistent data store (usually a relational database) and the data representation in memory (domain layer). The goal of this mode is to separate the memory representation, persistent storage, and data access of data. This layer is composed of one or more mappers (or data access objects) and performs data conversion. The scope of the mapper implementation is different. The general mapper will handle many different domain entity types, and the dedicated mapper will handle one or several.

example

Database Object Relational Mapper (ORM): The DAO used by Doctrine2, named "EntityRepository".

UML graphics

★Official PHP advanced learning exchange community "click" management to organize some materials, BAT and other first-line companies have advanced knowledge systems (relevant learning materials and written interview questions) and are not limited to: distributed architecture, high scalability, high Performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, microservices, Nginx and other knowledge points, advanced advanced dry goods

Code

  • User.php

<?php

namespace DesignPatterns\Structural\DataMapper;

class User
{
    /**
     * @var string
     */
    private $username;

    /**
     * @var string
     */
    private $email;

    public static function fromState(array $state): User
    {
        // 在你访问的时候验证状态

        return new self(
            $state['username'],
            $state['email']
        );
    }

    public function __construct(string $username, string $email)
    {
        // 先验证参数再设置他们

        $this->username = $username;
        $this->email = $email;
    }

    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }
}
  • UserMapper.php

<?php

namespace DesignPatterns\Structural\DataMapper;

class UserMapper
{
    /**
     * @var StorageAdapter
     */
    private $adapter;

    /**
     * @param StorageAdapter $storage
     */
    public function __construct(StorageAdapter $storage)
    {
        $this->adapter = $storage;
    }

    /**
     * 根据 id 从存储器中找到用户,并返回一个用户对象
     * 在内存中,通常这种逻辑将使用 Repository 模式来实现
     * 然而,重要的部分是在下面的 mapRowToUser() 中,它将从中创建一个业务对象
     * 从存储中获取的数据
     *
     * @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);
    }
}
  • StorageAdapter.php

<?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;
    }
}

test

  • Tests / DataMapperTest.php

<?php

namespace DesignPatterns\Structural\DataMapper\Tests;

use DesignPatterns\Structural\DataMapper\StorageAdapter;
use DesignPatterns\Structural\DataMapper\User;
use DesignPatterns\Structural\DataMapper\UserMapper;
use PHPUnit\Framework\TestCase;

class DataMapperTest extends TestCase
{
    public function testCanMapUserFromStorage()
    {
        $storage = new StorageAdapter([1 => ['username' => 'domnikl', 'email' => '[email protected]']]);
        $mapper = new UserMapper($storage);

        $user = $mapper->findById(1);

        $this->assertInstanceOf(User::class, $user);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testWillNotMapInvalidData()
    {
        $storage = new StorageAdapter([]);
        $mapper = new UserMapper($storage);

        $mapper->findById(1);
    }
}

The Growth Path of PHP Internet Architect * The Ultimate Guide to "Design Patterns"

PHP Internet Architect 50K Growth Guide + Industry Problem Solving Guide (Continuous Update)

Interview with 10 companies, get 9 offers, PHP interview questions in 2020

★If you like my article and want to communicate and learn with more senior developers, get more technical consultation and guidance related to interviews with major companies, welcome to join our group, password: phpzh (group ID: 856460874).

The latest PHP advanced tutorial in 2020, full series!

If the content is good, I hope everyone will support and encourage you to give a like/like, and welcome to communicate together; in addition, if you have any questions, you can suggest what you want to see in the comments.

Guess you like

Origin blog.csdn.net/weixin_43814458/article/details/108609186