模型与数据库映射
While there’s still a huge number of cases where Domain Models are considered an overkill “enterprisey” solution that doesn’t jive with the natural pragmatism that proliferates throughout the world of PHP, they’re 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.
尽管在很多情况下, 域模型被认为是一种过分的“企业”解决方案,但并没有与整个PHP世界中普遍存在的自然实用主义混为一谈,但它们却不断地违反了许多开发人员的想法,即使是那些他们像沉船的最后救生衣一样紧贴数据库模型范式。
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’ll 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 at some point, a fact that highlights why Domain Models are often surrounded by a cloud of bullying.
有一些原因在很大程度上证明了这种React的合理性。 毕竟,即使构建最简单的域模型,也需要定义其构建对象之间的约束,规则和关系,它们在给定上下文中的行为方式以及它们在生命周期中将携带的数据类型。 另外,在模型数据与存储之间进行传输的过程可能需要在某个时候删除一组数据映射器 ,这一事实凸显了为何域模型经常被欺凌云所包围。
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’s possible to scale them down and get the most from them in smaller environments too. To demonstrate this, in my previous article 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’ll be developing a basic mapping module which will allow you to move data easily between the blog’s model and a MySQL database, all while keeping them neatly isolated from one other.
上一篇文章没有一个真正的幸福结局。 它仅显示了模型的机制,而不是如何使其与“真实”持久层同步工作。 因此,在您以这种不礼貌的态度将我扔给狮子之前,在此后续文章中,我们将开发一个基本的映射模块,该模块将允许您轻松地在博客模型和MySQL数据库之间移动数据,同时保持数据整洁彼此隔离。
The phrase may sound like an cheap cliché, I know, but I’m 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’ll be trying to connect a batch of mapping classes to a blog’s 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.
我知道这句话听起来像是个陈词滥调,但是我每次解决软件问题时对重新发明轮子都不特别感兴趣(当然,除非我需要更好,更快的轮子)。 在这种情况下,考虑到我们将尝试将一批映射类连接到博客的域模型的情况,确实需要付出额外的努力。 考虑到这种努力的规模,其想法是从头开始建立一个基本的数据访问层(DAL),以便可以轻松地将域对象保存在MySQL数据库中,然后通过一些通用查找器按需进行检索。
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:
有问题的DAL将仅由几个组件组成:第一个组件将是一个简单的数据库适配器接口,其合同如下所示:
<?php namespace LibraryDatabase; interface DatabaseAdapterInterface { public function connect(); public function disconnect(); public function prepare($sql, array $options = array()); public function execute(array $parameters = array()); 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.
不可否认,上述DatabaseAdapterInterface是可驯服的生物。 它的合同允许我们在运行时创建不同的数据库适配器,并执行一些常见的任务,例如连接数据库和运行CRUD操作,而不必大惊小怪。
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:
现在,我们需要至少一个接口的实现者来完成所有这些很酷的事情。 承担此责任的骄傲骑士将是非规范的PDO适配器,其外观如下:
<?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(); } }Feel free to curse me for throwing such a fat code snippet at you, but it was a necessary evil. What’s more, even while the PdoAdapter class looks somewhat tangled, it’s 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.
随意诅咒我向您抛出如此繁琐的代码片段,但这是必然的恶行。 而且,即使PdoAdapter类看起来有些纠结,它实际上是一个简单的包装程序,它利用了PDO即时提供的许多功能,而没有将客户端代码暴露给冗长的API。
Now that PdoAdapter is doing the dirty database work for us, let’s create a few MySQL tables which will store the data corresponding to blog posts, comments, and users:
现在, PdoAdapter为我们完成了肮脏的数据库工作,让我们创建一些MySQL表,该表将存储与博客文章,评论和用户相对应的数据:
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.
上面的数据库模式定义了帖子和评论之间的一对多关系,以及评论和用户(博客的评论者)之间的一对一关系。 如果您喜欢冒险,可以随意调整架构以适合您的特定需求。 为了简洁起见,我将其保持如此简单。
At this point we’ve implemented a simple DAL which we can use for persisting the blog’s 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.
至此,我们已经实现了一个简单的DAL,可将其用于在MySQL中持久保存博客的域模型,而在此过程中不会花费太多精力。 现在,我们需要在图像中添加中间人,即上述的数据映射器,以便可以在后台悄悄地处理任何阻抗不匹配的情况。
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’t boil down to just say… hey, I’ll get these relational mappers up and running during a coffee break. That’s why ORM libraries like Doctrine 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 blog’s domain objects without facing the learning curve of a third-party package.
当然,这取决于上下文,但是在大多数情况下,构建映射层(尤其是双向关系层)要远离琐碎的事情。 这个过程并不能简单地说明……嘿,我将在喝咖啡休息的时候启动并运行这些关系映射器。 这就是为什么像Doctrine这样的ORM库毕竟可以生存和呼吸的原因。 但是,在这种情况下,我们希望利用生活在我们内部的粗体编码器,并创建自己的映射器集,以在不面对第三方软件包学习曲线的情况下对博客的域对象进行按摩。
Let’s begin with encapsulating as much mapping logic as possible within an abstract class, like the below one:
让我们从在一个抽象类中尽可能多地封装映射逻辑开始,如下所示:
<?php namespace ModelMapper; use LibraryDatabaseDatabaseAdapterInterface; 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.
该类从几个通用查找器的后面抽象出从指定表中提取数据所需的所有逻辑,然后将这些逻辑用于以有效状态重构域对象。 由于重构应该在层次结构中委派给精炼的实现,因此createEntity()方法已声明为抽象。
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:
现在让我们定义一组具体的映射器,这些映射器将处理博客文章,评论和用户。 这是第一个,以及它实现的接口:
<?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); } <?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:
注意, PostMapper的实现遵循合理的路径。 简而言之,它不仅扩展了其抽象父级,而且还在构造函数中注入了一个注释映射器(仍未定义),以便同步处理帖子和注释,而不会向外界揭示创建整个对象图的复杂性。 当然,我们不应该因为看到仍然蒙着面纱的注释映射器外观而高兴自己,因此这里是其源代码,并与相应的接口耦合:
<?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); } <?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); } }The 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’s make a final effort and define another which will handle users:
CommentMapper类的行为与其同级PostMapper十分相似。 简而言之,它在构造函数中要求用户映射器,以便可以将特定注释绑定到相应的注释器。 考虑到CommentMapper随和的性质,让我们做最后的努力,并定义另一个可以处理用户的内容:
<?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); } <?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’ve 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’s 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.
现在已经设置了UserMapper类,我们终于从一开始就实现了我们承诺的目标:从头开始构建易于按摩的映射层,能够在简单的博客域模型之间来回移动数据和MySQL。 但是,让我们不要在后面轻拍一下,因为查看映射器是否像初次看到腮红一样功能最佳的方法是作为示例。
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 layer’s perspective. Let’s wire up all the mapper graphs together:
如您所料,以高效的方式使用Blog域模型非常简单,因为映射器的API会进行实际的工作,并从模型本身隐藏底层数据库。 但是,从应用程序层的角度来看,最好理解此功能。 让我们将所有映射器图连接在一起:
<?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’re ready to get some real action, now let’s 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’s fix that add a few comments:
如果所有工作都按预期进行,则应该使用先前的条目很好地填充posts表。 但是,是我还是他们看起来有点寂寞? 让我们修复一下,添加一些注释:
<?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 Joe’s 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.
由于Joe出色的口才,第一篇博客文章现在应该有两条评论,第二篇博客文章应该有一条评论。 注意,用于维持注释和用户之间界限的外键是在运行时拾取的。 但是,在生产中,它们很可能应该收集在用户界面中。
Now that the blog’s database has been finally hydrated with a couple of posts, comments, and a chatty user’s info, the last thing we should do is pull in all the data and dump it on screen. Here we go:
现在,博客的数据库终于被两篇文章,评论和一些健谈的用户信息所淹没,我们最后要做的就是提取所有数据并将其转储到屏幕上。 开始了:
<?php $posts = $postMapper->findAll();Even when this one-liner is… well just a one-liner, it’s 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:
即使是单行代码,也仅仅是单行代码,它实际上是根据数据库的请求创建博客域对象图并将其放入内存中以进行进一步处理的主力军。 另一方面,可以通过骨骼视图轻松地将所讨论的图形分解回去,如下所示:
<!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>Indeed, looping through a few posts, comments, and users is a boring task that doesn’t deserve any further explanation. Of course if you’re an insightful, hawk-eye observer, you might have noticed that this seemingly harmless view is in fact a hog eater which blatantly pulls in the entire database and throws it into the user interface’s heart. Let’s no rush to judgments since there are a few common tricks that can be used for tackling this issue, including caching (in any of its multiple forms), lazy-loading, and so forth.
确实,浏览一些帖子,评论和用户是一项无聊的任务,不需要任何进一步的解释。 当然,如果您是一位有洞察力的鹰眼观察者,您可能已经注意到,这种看似无害的观点实际上是一个吞噬者,它公然拉入整个数据库并将其扔到用户界面的心脏。 别急着进行判断,因为有一些常见的技巧可用于解决此问题,包括缓存(以多种形式出现), 延迟加载等。
Spicing up the data mappers with some of these goodies will be left as homework for you, something that surely will keep you entertained for quite a long time.
使用其中的一些东西来增强数据映射器将留给您作为家庭作业,这肯定会使您长时间保持娱乐。
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’s 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.
很少有人会认为,即使使用像PHP这样随和的语言,丰富的域模型的实现也并非是一夜之间的高中式任务。 可以肯定地说,在很多情况下,可以将往返DAL的模型数据委托给交钥匙映射库或框架(假设存在这样的事情),定义域对象之间的关系以及它们自己的规则,数据和行为取决于开发人员。
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, 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.
尽管如此,额外的努力通常会产生有益的波动效果,因为它有助于积极推动多层设计的使用以及良好的OOP做法,在这些做法中,所涉及的对象仅具有一些明确定义的职责 ,并且该模型不会受到数据库逻辑污染的原始生态系统。 除此之外,可以以一种相当轻松的方式将模型从一种基础架构转换为另一种基础架构,您将了解为什么在开发必须良好扩展的应用程序时这种方法非常有吸引力。
Image via kentoh/ Shutterstock
图片来自kentoh / Shutterstock
翻译自: https://www.sitepoint.com/integrating-the-data-mappers/
模型与数据库映射