1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
|
<?php ---- for code coloring
1. [PHP](https://www.sitepoint.com/php/)
2. March 16, 2012
3. https://www.sitepoint.com/integrating-the-data-mappers/
By [Alejandro Gervasio](https://www.sitepoint.com/author/agervasio/)
## Building a Domain Model - Integrating Data Mappers
**See DDL at end this article**.
While there iss still a huge number of cases where [Domain Models](http://martinfowler.com/eaaCatalog/domainModel.html) are considered an overkill "enterprisey" solution that does not jive with the natural pragmatism that proliferates throughout the world of PHP, they are steadily breaching the minds of many developers, even of those who cling to the Database Model paradigm like the last life jacket of a sinking ship.
There are some reasons that largely justify such a reaction. After all, building even the simplest Domain Model demands definition of the constraints, rules, and relationships among its building objects, how they will behave in a given context, and what type of data they will carry during their life cycle. Plus, the process of transferring model data to and from the storage will likely require to drop a set of [Data Mappers](http://martinfowler.com/eaaCatalog/dataMapper.html) at some point, a fact that highlights why Domain Models are often surrounded by a cloud of bullying.
Eager prejudgements tend to be misleading, though. The bones of a rich Domain Model will certainly be accommodated more comfortably inside the boundaries of a large application, but it is possible to scale them down and get the most from them in smaller environments too. To demonstrate this, in [my previous article](http://www.sitepoint.com/building-a-domain-model/) I showed you how to implement a simple blog domain model composed of a few posts, comments, and user objects.
The previous article lacked a true happy ending; it merely showed the mechanics of the model, not how to put it to work in synchrony with a "real" persistence layer. So before you throw me to the lions for such an impolite attitude, in this follow-up we will be developing a basic mapping module which will allow you to move data easily between the blogs model and a MySQL database, all while keeping them neatly isolated from one other.
## Building a Naive DAL (or why my PDO adapter is better than yours)
The phrase may sound like an cheap cliche, I know, but I am not particularly interested in reinventing the wheel each time I tackle a software problem (unless I need a nicer and faster wheel, of course). In this case, the situation does warrant some additional effort considering we will be trying to connect a batch of mapping classes to a blogs domain model. Given the magnitude of the endeavor, the idea is to set up from scratch a basic Data Access Layer (DAL) so that domain objects can easily be persisted in a MySQL database, and in turn, retrieved on request through some generic finders.
The DAL in question will be made up of just a couple of components: the first one will be a simple database adapter interface, whose contract looks like this:
### 1. DatabaseAdapterInterface.php
```php
<?php
namespace LibraryDatabase;
interface DatabaseAdapterInterface
{
public function connect();
public function disconnect();
public function prepare($sql, array $options = array());
public function execute(array $parameters = array());
// C R U D :
public function fetch($fetchStyle = null,
$cursorOrientation = null, $cursorOffset = null);
public function fetchAll($fetchStyle = null, $column = 0);
public function select($table, array $bind, $boolOperator = "AND");
public function insert($table, array $bind);
public function update($table, array $bind, $where = "");
public function delete($table, $where = "");
}
```
Undeniably, the above `DatabaseAdapterInterface` is a tameable creature. Its contract allows us to create different database adapters at runtime and perform a few common tasks, such as connecting to the database and running CRUD operations without much fuss.
Now we need at least one implementer of the interface that does all these cool things. The proud cavalier that will assume this responsibility will be a non-canonical PDO adapter, which looks as follows:
### 2. PdoAdapter.php - Admin_crud.php
```php
<?php
namespace LibraryDatabase;
class PdoAdapter implements DatabaseAdapterInterface
{
protected $config = array();
protected $connection;
protected $statement;
protected $fetchMode = PDO::FETCH_ASSOC;
public function __construct($dsn, $username = null,
$password = null, array $driverOptions = array()) {
$this->config = compact("dsn", "username", "password",
"driverOptions");
}
public function getStatement() {
if ($this->statement === null) {
throw new PDOException(
"There is no PDOStatement object for use.");
}
return $this->statement;
}
public function connect() {
// if there is a PDO object already, return early
if ($this->connection) {
return;
}
try {
$this->connection = new PDO(
$this->config["dsn"],
$this->config["username"],
$this->config["password"],
$this->config["driverOptions"]);
$this->connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(
PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
throw new RunTimeException($e->getMessage());
}
}
public function disconnect() {
$this->connection = null;
}
public function prepare($sql, array $options = array() {
$this->connect();
try {
$this->statement = $this->connection->prepare($sql,
$options);
return $this;
}
catch (PDOException $e) {
throw new RunTimeException($e->getMessage());
}
}
public function execute(array $parameters = array()) {
try {
$this->getStatement()->execute($parameters);
return $this;
}
catch (PDOException $e) {
throw new RunTimeException($e->getMessage());
}
}
public function countAffectedRows() {
try {
return $this->getStatement()->rowCount();
}
catch (PDOException $e) {
throw new RunTimeException($e->getMessage());
}
}
public function getLastInsertId($name = null) {
$this->connect();
return $this->connection->lastInsertId($name);
}
public function fetch($fetchStyle = null,
$cursorOrientation = null, $cursorOffset = null) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $this->getStatement()->fetch($fetchStyle,
$cursorOrientation, $cursorOffset);
}
catch (PDOException $e) {
throw new RunTimeException($e->getMessage());
}
}
public function fetchAll($fetchStyle = null, $column = 0) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $fetchStyle === PDO::FETCH_COLUMN
? $this->getStatement()->fetchAll($fetchStyle, $column)
: $this->getStatement()->fetchAll($fetchStyle);
}
catch (PDOException $e) {
throw new RunTimeException($e->getMessage());
}
}
public function select($table, array $bind = array(),
$boolOperator = "AND") {
if ($bind) {
$where = array();
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
$where[] = $col . " = :" . $col;
}
}
$sql = "SELECT * FROM " . $table
. (($bind) ? " WHERE "
. implode(" " . $boolOperator . " ", $where) : " ");
$this->prepare($sql)
->execute($bind);
return $this;
}
public function insert($table, array $bind) {
$cols = implode(", ", array_keys($bind));
$values = implode(", :", array_keys($bind));
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
$sql = "INSERT INTO " . $table
. " (" . $cols . ") VALUES (:" . $values . ")";
return (int) $this->prepare($sql)
->execute($bind)
->getLastInsertId();
}
public function update($table, array $bind, $where = "") {
$set = array();
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
$set[] = $col . " = :" . $col;
}
$sql = "UPDATE " . $table . " SET " . implode(", ", $set)
. (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute($bind)
->countAffectedRows();
}
public function delete($table, $where = "") {
$sql = "DELETE FROM " . $table . (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute()
->countAffectedRows();
}
}
```
Fat code snippet, but it is necessary evil. What is more, even while PdoAdapter class looks somewhat tangled (knotty, confused mass, Highly complex), it is actually a simple wrapper which exploits much of the functionality that PDO offers right out the box without exposing client code to a verbose API.
At this point we have implemented a simple DAL which we can use for persisting the blogs domain model in MySQL without sweating too much during the process. Now we need to add the middle men to the picture, that is the aforementioned data mappers, so any impedance mismatches can be handled quietly behind the scenes.
## Implementing a Bi-directional Mapping Layer
It depends on the context of course, but most of the time building a mapping layer (and specifically a bi-directional relational one) is quite a ways away from being trivial. The process doesn not boil down to just say... hey, I will get these relational mappers up and running during a coffee break. That is why ORM libraries like [Doctrine](http://www.doctrine-project.org/) live and breathe after all. In this case, however, we want to leverage the bold coder living inside of us and create our own set of mappers to l massage the blogs domain objects without facing the learning curve of a third-party package.
Let us begin with encapsulating as much mapping logic as possible [within an abstract class](http://martinfowler.com/refactoring/catalog/extractSuperclass.html), like the below one:
window.propertag.cmd.push(function() { proper\_display('sitepoint\_content\_1'); });
### 3. AbstractDataMapper.php
```php
<?php
namespace ModelMapper;
use LibraryDatabase DatabaseAdapterInterface;
abstract class AbstractDataMapper
{
protected $adapter;
protected $entityTable;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function getAdapter() {
return $this->adapter;
}
public function findById($id)
{
$this->adapter->select($this->entityTable,
array('id' => $id));
if (!$row = $this->adapter->fetch()) {
return null;
}
return $this->createEntity($row);
}
public function findAll(array $conditions = array())
{
$entities = array();
$this->adapter->select($this->entityTable, $conditions);
$rows = $this->adapter->fetchAll();
if ($rows) {
foreach ($rows as $row) {
$entities[] = $this->createEntity($row);
}
}
return $entities;
}
// Create an entity (IMPLEMENTATION DELEGATED TO CONCRETE MAPPERS)
abstract protected function createEntity(array $row);
}
```
The class abstracts away behind a couple of generic finders all of the logic required for pulling in data from a specified table, which is then used for reconstituting domain objects in a valid state. Because reconstitutions should be delegated down the hierarchy to refined implementations, the `createEntity()` method has been declared abstract.
Let's now define the set of concrete mappers that will deal with blog posts, comments, and users. Here's the first one, along with the interface it implements:
### 4. PostMapperInterface.php
```php
<?php
namespace ModelMapper;
use ModelPostInterface;
interface PostMapperInterface
{
public function findById($id);
public function findAll(array $conditions = array());
public function insert(PostInterface $post);
public function delete($id);
}
```
### 5. PostMapper.php
```php
<?php
namespace ModelMapper;
use LibraryDatabaseDatabaseAdapterInterface,
ModelPostInterface,
ModelPost;
class PostMapper extends AbstractDataMapper implements PostMapperInterface
{
protected $commentMapper;
protected $entityTable = "posts";
public function __construct(DatabaseAdapterInterface $adapter,
CommentMapperInterface $commenMapper) {
$this->commentMapper = $commenMapper;
parent::__construct($adapter);
}
public function insert(PostInterface $post) {
$post->id = $this->adapter->insert($this->entityTable,
array("title" => $post->title,
"content" => $post->content));
return $post->id;
}
public function delete($id) {
if ($id instanceof PostInterface) {
$id = $id->id;
}
$this->adapter->delete($this->entityTable, "id = $id");
return $this->commentMapper->delete("post_id = $id");
}
protected function createEntity(array $row) {
$comments = $this->commentMapper->findAll(
array("post_id" => $row["id"]));
return new Post($row["title"], $row["content"], $comments);
}
}
```
Notice that the implementation of `PostMapper` follows a fairly logical path. Simply put, not only does it extend its abstract parent, but it injects in the constructor a comment mapper (still undefined), in order to handle in sync both posts and comments without revealing to the outside world the complexities of creating the whole object graph. Of course, we shouldn't deny ourselves the joy of seeing how the still veiled comment mapper looks, hence here's its source code, coupled to the corresponding interface:
### 6. CommentMapperInterface.php
```php
<?php
namespace ModelMapper;
use ModelCommentInterface;
interface CommentMapperInterface
{
public function findById($id);
public function findAll(array $conditions = array());
public function insert(CommentInterface $comment, $postId,
$userId);
public function delete($id);
}
```
### 7. CommentMapperInterface.php
```php
<?php
namespace ModelMapper;
use LibraryDatabaseDatabaseAdapterInterface,
ModelCommentInterface,
ModelComment;
class CommentMapper extends AbstractDataMapper implements CommentMapperInterface
{
protected $userMapper;
protected $entityTable = "comments";
public function __construct(DatabaseAdapterInterface $adapter,
UserMapperInterface $userMapper) {
$this->userMapper = $userMapper;
parent::__construct($adapter);
}
public function insert(CommentInterface $comment, $postId,
$userId) {
$comment->id = $this->adapter->insert($this->entityTable,
array("content" => $comment->content,
"post_id" => $postId,
"user_id" => $userId));
return $comment->id;
}
public function delete($id) {
if ($id instanceof CommentInterface) {
$id = $id->id;
}
return $this->adapter->delete($this->entityTable,
"id = $id");
}
protected function createEntity(array $row) {
$user = $this->userMapper->findById($row["user_id"]);
return new Comment($row["content"], $user);
}
}
```
CommentMapper class behaves quite similar to its sibling `PostMapper`. In short, it asks for a user mapper in the constructor, so that a specific comment can be tied up to the corresponding commenter. Considering the easy-going nature of `CommentMapper`, let us make a final effort and define another which will handle users:
### 8. UserMapperInterface.php
```php
<?php
namespace ModelMapper;
use ModelUserInterface;
interface UserMapperInterface
{
public function findById($id);
public function findAll(array $conditions = array());
public function insert(UserInterface $user);
public function delete($id);
}
```
### 9. UserMapper.php
```php
<?php
namespace ModelMapper;
use ModelUserInterface,
ModelUser;
class UserMapper extends AbstractDataMapper implements UserMapperInterface
{
protected $entityTable = "users";
public function insert(UserInterface $user) {
$user->id = $this->adapter->insert($this->entityTable,
array("name" => $user->name,
"email" => $user->email));
return $user->id;
}
public function delete($id) {
if ($id instanceof UserInterface) {
$id = $id->id;
}
return $this->adapter->delete($this->entityTable,
array("id = $id"));
}
protected function createEntity(array $row) {
return new User($row["name"], $row["email"]);
}
}
```
Now that the UserMapper class is set, we have finally reached the goal we were committed to from the very start: build up from scratch an easy-to-massage mapping layer, capable of moving data back and forward between a simplistic blog domain model and MySQL. But let us not pat ourselves in the back yet, as the best way to see if the mappers are as functional as they look at first blush is by example.
## Mapping Blogs Domain Objects to and from the DAL
As you might expect, consuming the blog domain model in an efficient manner is pretty straightforward, as the mappers APIs do the actual hard work and hide the underlying database from the model itself. This ability, though, is best appreciated from the application layers perspective. Let us wire up all the mapper graphs together:
### 10. Cls_db_test.php
```php
<?php
use LibraryLoaderAutoloader;
require_once __DIR__ . "/Autoloader.php";
$autoloader = new Autoloader();
$autoloader->register();
// create a PDO adapter
$adapter = new PdoAdapter("mysql:dbname=blog", "myfancyusername",
"myhardtoguesspassword");
// create the mappers
$userMapper = new UserMapper($adapter);
$commentMapper = new CommentMapper($adapter, $userMapper);
$postMapper = new PostMapper($adapter, $commentMapper);
```
So far, so good. At this point, the mappers have been initialized by dropping their collaborators into the corresponding constructors. Considering that they are ready to get some real action, now let us use the post mapper and insert a few trivial posts into the database:
```php
$postMapper->insert(
new Post(
"Welcome to SitePoint",
"To become yourself a true PHP master, you must first master PHP."));
$postMapper->insert(
new Post(
"Welcome to SitePoint (Reprise)",
"To become yourself a PHP Master, you must first master... Wait! Did I post that already?"));
```
If all works as expected, the `posts` table should be nicely populated with the previous entries. But, is it just me or do they look a little lonely? Let us fix that add a few comments:
```php
$user = new User("Everchanging Joe", "joe@example.com");
$userMapper->insert($user);
// Joe's comments for the first post (post ID = 1, user ID = 1)
$commentMapper->insert(
new Comment(
"I just love this post! Looking forward to seeing more of this stuff.",
$user),
1, $user->id);
$commentMapper->insert(
new Comment(
"I just changed my mind and dislike this post! Hope not seeing more of this stuff.",
$user),
1, $user->id);
// Joe's comment for the second post (post ID = 2, user ID = 1)
$commentMapper->insert(
new Comment(
"Not quite sure if I like this post or not, so I cannot say anything for now.",
$user),
2, $user->id);
```
Thanks to Joes remarkable eloquence, the first blog post should have now two comments and second should have one. Notice that the foreign keys used to sustain the bound between comments and users have been just picked up at runtime. In production, however, they most likely should be gathered inside the user interface.
Now that the blogs database has been finally hydrated with a couple of posts, comments, and a chatty users info, the last thing we should do is pull in all the data and dump it on screen. Here we go:
### 11. tbl.php
```php
<?php
$posts = $postMapper->findAll();
```
Even when this one-liner is... well just a one-liner, it is actually the workhorse that creates blog domain object graphs on request from the database and put them in memory for further processing. On the other hand, the graphs in question can be easily decomposed back through a skeletal view, as follows:
```html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Building a Domain Model in PHP</title>
</head>
<body>
<header>
<h1>SitePoint.com</h1>
</header>
<section>
<ul>
<?php
foreach ($posts as $post) {
?>
<li>
<h2><?php echo $post->title;?></h2>
<p><?php echo $post->content;?></p>
<?php
if ($post->comments) {
?>
<ul>
<?php
foreach ($post->comments as $comment) {
?>
<li>
<h3><?php echo $comment->user->name;?> says:</h3>
<p><?php echo $comment->content;?></p>
</li>
<?php
}
?>
</ul>
<?php
}
?>
</li>
<?php
}
?>
</ul>
</section>
</body>
</html>
```
### Lazy loading eg Doctrine ORM Proxy, Laravel Eloquent
...\fwphp\glomodul\z_examples\02_mvc\domain_m_lazy_load\index.php
https://docs.php.earth/php/ref/oop/design-patterns/lazy-loading/
[lazy-loading]( http://martinfowler.com/eaaCatalog/lazyLoad.html )
An object that does not contain all of the data you need but knows how to get it.
Software design pattern where the initialization of an object occurs only when it is actually needed and not before to preserve simplicity of usage and improve performance.
The opposite of lazy loading is eager loading where data, resource, and object is created in the time of the initialization.
### Closing Remarks
Very few will disagree that the implementation of a rich Domain Model is far away from being an overnight, high school-like task, even when using an easy-going language like PHP. While it is safe to say that forwarding model data to and from the DAL can be delegated in many cases to a turnkey mapping library or framework (assuming there exists such a thing), defining the relationships between domain objects, as well as their own rules, data, and behavior is up to the developer.
Despite this, the extra effort in general causes a beneficial wave effect, as it helps out in pushing actively the use of a multi-tier design along with good OOP practices where the involved objects have just a few, [well-defined responsibilities](http://en.wikipedia.org/wiki/Single_responsibility_principle), and the model doesn't get its pristine ecosystem polluted with database logic. Add to this that shifting the model from one infrastructure to another can be done in a fairly painless fashion, and you'll get to see why this approach is very appealing when developing applications that must scale well.
```
CREATE TABLE posts (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(100) DEFAULT NULL,
content TEXT,
PRIMARY KEY (id)
);
CREATE TABLE users (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(45) DEFAULT NULL,
email VARCHAR(45) DEFAULT NULL,
PRIMARY KEY (id)
);
CREATE TABLE comments (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
content TEXT,
user_id INTEGER DEFAULT NULL,
post_id INTEGER DEFAULT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREGIN KEY (post_id) REFERENCES posts(id)
);
```
The above database schema defines a one-to-many relationship between posts and comments, and a one-to-one relationship between comments and users (the blog's commentators). If you're feeling adventurous, you're free to tweak the schema at will to suit your specific needs. For the sake of brevity, however, I've kept it that simple.
|