[php]标记投射和工作单元
[php]标记映射和工作单元
标记映射
系统中可能存在两个值相同,但又不是同一个引用的对象,这样的重复对象可能是从数据库中读出来的,这样就造成了不必要的查询。
标记映射是一个类ObjectWatcher,它负责管理进程中的领域对象,以保证进程中不出现重复对象。
标记映射可以防止重新读取数据库查询数据,只有当ObjectWatcher类中不存在标记映射对应的对象时才去查询数据库。这样就保证了在一个进程中,一条数据只对应一个对象。
代码很容易懂,都是一些存取数组值的操作。
ObjectWatcher代码:
namespace demo\domain; use \demo\domain\DomainObject; /** * 标记映射 */ class ObjectWatcher { private static $instance; // 标记映射 private $all = array(); private function __construct() { } public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * 获得对象对应的键值 * @param DomainObject $obj */ public function getGobalKey(DomainObject $obj) { $key = get_class($obj) . '_' . $obj->getId(); return $key; } /** * 添加到all * @param DomainObject $obj */ public static function add(DomainObject $obj) { $instance = self::getInstance(); $key = $instance->getGobalKey($obj); $instance->all[$key] = $obj; } /** * 从all中删除 * @param DomainObject $obj */ public static function delete(DomainObject $obj) { $instance = self::getInstance(); $key = $instance->getGobalKey($obj); unset($instance->all[$key]); } /** * 判断标记是否存在 * @param string $className * @param int $id */ public static function exists($className, $id) { $instance = self::getInstance(); $key = "{$className}_{$id}"; if (isset($instance->all[$key])) { return $instance->all[$key]; } return null; } }
Mapper代码:
namespace demo\mapper; use \demo\base\AppException; use \demo\base\ApplicationRegistry; use \demo\domain\DomainObject; use \demo\domain\ObjectWatcher; /** * Mapper */ abstract class Mapper { // PDO protected static $PDO; // config protected static $dsn, $dbUserName, $dbPassword; // PDO选项 protected static $options = array( \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', \PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION, ); public function __construct() { if (!isset(self::$PDO)) { // ApplicationRegistry获取数据库连接信息 $appRegistry = ApplicationRegistry::getInstance(); self::$dsn = $appRegistry->getDsn(); self::$dbUserName = $appRegistry->getDbUserName(); self::$dbPassword = $appRegistry->getDbPassword(); if (!self::$dsn || !self::$dbUserName || !self::$dbPassword) { throw new AppException('Mapper init failed!'); } self::$PDO = new \PDO(self::$dsn, self::$dbUserName, self::$dbPassword, self::$options); } } /** * 查找指定ID * @param int $id */ public function findById($id) { // 从ObjectWatcher中获取 $obj = $this->getFromMap($id); if (!is_null($obj)) { return $obj; } $pStmt = $this->getSelectStmt(); $pStmt->execute(array($id)); $data = $pStmt->fetch(); $pStmt->closeCursor(); if (!is_array($data) || !isset($data['id'])) { return $obj; } $obj = $this->createObject($data); return $obj; } /** * 返回Collection */ public function findAll() { $pStmt = $this->getSelectAllStmt(); $pStmt->execute(array()); $raws = $pStmt->fetchAll(\PDO::FETCH_ASSOC); $collection = $this->getCollection($raws); return $collection; } /** * 插入数据 * @param \demo\domain\DomainObject $obj */ public function insert(DomainObject $obj) { $flag = $this->doInsert($obj); // 保存或者更新ObjectWatcher的$all[$key]的对象 $this->addToMap($obj); return $flag; } /** * 更新对象 * @param \demo\domain\DomainObject $obj */ public function update(\demo\domain\DomainObject $obj) { $flag = $this->doUpdate($obj); return $flag; } /** * 删除指定ID * @param int $id */ public function deleteById($id) { $pStmt = $this->getDeleteStmt(); $flag = $pStmt->execute(array($id)); return $flag; } /** * 生成一个$data中值属性的对象 * @param array $data */ public function createObject(array $data) { // 从ObjectWatcher中获取 $obj = $this->getFromMap($data['id']); if (!is_null($obj)) { return $obj; } // 创建对象 $obj = $this->doCreateObject($data); // 添加到ObjectWatcher $this->addToMap($obj); return $obj; } /** * 返回对应key标记的对象 * @param int $id */ private function getFromMap($id) { return ObjectWatcher::exists($this->getTargetClass(), $id); } /** * 添加对象到标记映射ObjectWatcher类 * @param DomainObject $obj */ private function addToMap(DomainObject $obj) { return ObjectWatcher::add($obj); } /** * 返回子类Collection * @param array $raw */ public function getCollection(array $raws) { return $this->getFactory()->getCollection($raws); } /** * 返回子类持久化工厂对象 */ public function getFactory() { return PersistanceFactory::getFactory($this->getTargetClass()); } protected abstract function doInsert(\demo\domain\DomainObject $obj); protected abstract function doCreateObject(array $data); protected abstract function getSelectStmt(); protected abstract function getSelectAllStmt(); protected abstract function doUpdate(\demo\domain\DomainObject $obj); protected abstract function getDeleteStmt(); protected abstract function getTargetClass(); }
现在,当Mapper从数据库中取出的数据映射成的对象都被标记到ObjectWatcher了,而且不需要对对象手动操作标记到ObjectWatcher,Mapper就已经帮你完成了。这样带来的好处是可以减少对数据库的操作和新对象的创建,比如find、createObject。但这也许可能带来问题,如果你的程序需要并发处理数据,那么被标记的对象数据就可能不一致了,你在这个时候可能需要对数据加锁。
工作单元
有些时候,我们可能没有改变数据的任何值却向数据库多次保存该数据,这当然是不必要的吧。工作单元可以使你只保存那些需要的对象。工作单元可以在一次请求即将结束时,把在这次请求中发生变化的对象保存到数据库中。一次请求的最后是在控制器(Controller)调用完Command和View之后,那么我们就可以在这里让工作单元执行任务。
标记映射的作用是在处理过程开始时向数据库加载不必要的对象,而工作单元则是在处理过程之后防止不必要的对象保存到数据库中。这两个工作方式就像是互补的。
为了判断哪些数据库的操作是必要的,那就需要跟踪与对象相关的各种事件(比如:setter()重新设置了对象的属性值)。跟踪工作当然最好放在被跟踪的对象中。
修改过的ObjectWatcher类:
namespace demo\domain; use \demo\domain\DomainObject; /** * 标记映射 */ class ObjectWatcher { private static $instance; // 标记映射 private $all = array(); // 保存新建对象 private $new = array(); // 保存被修改过的对象(“脏对象”) private $dirty = array(); // 保存删除对象 private $delete = array(); private function __construct() { } public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } /** * 获得对象对应的键值 * @param DomainObject $obj */ public function getGobalKey(DomainObject $obj) { $key = get_class($obj) . '_' . $obj->getId(); return $key; } /** * 添加到all * @param DomainObject $obj */ public static function add(DomainObject $obj) { $instance = self::getInstance(); $key = $instance->getGobalKey($obj); $instance->all[$key] = $obj; } /** * 从all中删除 * @param DomainObject $obj */ public static function delete(DomainObject $obj) { $instance = self::getInstance(); $key = $instance->getGobalKey($obj); unset($instance->all[$key]); } /** * 添加到new * @param DomianObject $obj */ public static function addNew(DomainObject $obj) { $instance = self::getInstance(); $instance->new[] = $obj; } /** * 添加到dirty * @param DomianObject $obj */ public static function addDirty(DomainObject $obj) { $instance = self::getInstance(); if (!in_array($obj, $instance->dirty, true)) { $instance->dirty[$instance->getGobalKey($obj)] = $obj; } } /** * 添加到delete * @param DomainObject $obj */ public static function addDelete(DomainObject $obj) { $instance = self::getInstance(); $instance->delete[$instance->getGobalKey($obj)] = $obj; } /** * 清除标记dirty new delete * @param DomainObject $obj */ public static function addClean(DomainObject $obj) { $instance = self::getInstance(); // unset删除保存的对象 unset($instance->dirty[$instance->getGobalKey($obj)]); unset($instance->delete[$instance->getGobalKey($obj)]); // 删除new中的对象 $instance->new = array_filter($instance->new, function($a) use ($obj) { return !($a === $obj); }); } /** * 判断标记是否存在 * @param string $className * @param int $id */ public static function exists($className, $id) { $instance = self::getInstance(); $key = "{$className}_{$id}"; if (isset($instance->all[$key])) { return $instance->all[$key]; } return null; } /** * 对new dirty delete 中的标记对象执行操作 */ public function performOperations() { $instance = self::getInstance(); // new foreach ($instance->new as $obj) { $obj->finder()->insert($obj); } // dirty foreach ($instance->dirty as $obj) { $obj->finder()->update($obj); } // delete foreach ($instance->delete as $obj) { $obj->finder()->delete($obj); } $this->new = array(); $this->dirty = array(); $this->delete = array(); } }
由于ObjectWatcher的操作上对对象的操作,所以由这些对象自己来来执行ObjectWatcher是很适合的。
修改过的DomainObject类(markNew()、markDirty()、markDelete()、markClean()):
namespace demo\domain; use \demo\domain\HelperFactory; use \demo\domain\ObjectWatcher; /** * 领域模型抽象基类 */ abstract class DomainObject { protected $id = -1; public function __construct($id = null) { if (is_null($id)) { // 标记为new 新建 $this->markNew(); } else { $this->id = $id; } } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; $this->markDirty(); } public function markNew() { ObjectWatcher::addNew($this); } public function markDirty() { ObjectWatcher::addDirty($this); } public function markDeleted() { ObjectWatcher::addDelete($this); } public function markClean() { ObjectWatcher::addClean($this); } public static function getCollection($type) { return HelperFactory::getCollection($type); } public function collection() { return self::getCollection(get_class($this)); } public static function getFinder($type) { return HelperFactory::getFinder($type); } public function finder() { return self::getFinder(get_class($this)); } }

修改过的Mapper(和上面相同部分略去了,太占位子了):
/** * Mapper */ abstract class Mapper { //... /** * 查找指定ID * @param int $id */ public function findById($id) { // 从ObjectWatcher中获取 $obj = $this->getFromMap($id); if (!is_null($obj)) { return $obj; } $pStmt = $this->getSelectStmt(); $pStmt->execute(array($id)); $data = $pStmt->fetch(); $pStmt->closeCursor(); if (!is_array($data) || !isset($data['id'])) { return $obj; } $obj = $this->createObject($data); return $obj; } /** * 插入数据 * @param \demo\domain\DomainObject $obj */ public function insert(DomainObject $obj) { $flag = $this->doInsert($obj); // 保存或者更新ObjectWatcher的$all[$key]的对象 $this->addToMap($obj); $obj->markClean(); // 调试用的 echo 'insert :' . get_class($obj) . '_' . $obj->getName() . '_' . $obj->getId() .'<br>'; return $flag; } /** * 更新对象 * @param \demo\domain\DomainObject $obj */ public function update(\demo\domain\DomainObject $obj) { $flag = $this->doUpdate($obj); $obj->markClean(); // 调试用的 echo 'update :' . get_class($obj) . '_' . $obj->getName() . '_' . $obj->getId() .'<br>'; return $flag; } /** * 生成一个$data中值属性的对象 * @param array $data */ public function createObject(array $data) { // 从ObjectWatcher中获取 $obj = $this->getFromMap($data['id']); if (!is_null($obj)) { return $obj; } // 创建对象 $obj = $this->doCreateObject($data); // 添加到ObjectWatcher $this->addToMap($obj); // 清除new标记 ObjectWatcher::addClean($obj); return $obj; } //... }
对象的变化都能被跟踪到了,那么应该在哪里处理这些变化过的对象(“脏数据”)呢?上面说到了,应该在一次请求即将完成的时候。
一次请求即将结束时,Controller中调用工作单元(同样省略了没改变的代码):
namespace demo\controller; /** * Controller */ class Controller { // ... private function handleReuqest() { $request = new \demo\controller\Request(); $appController = \demo\base\ApplicationRegistry::getInstance()->getAppController(); // 执行完所有Command,有可能存在forward while ($cmd = $appController->getCommand($request)) { // var_dump($cmd); $cmd->execute($request); // 把当前Command设为已执行过 $request->setLastCommand($cmd); } // 工作单元执行任务 ObjectWatcher::getInstance()->performOperations(); // 获取视图 $view = $appController->getView($request); // 显示视图 $this->invokeView($view); } // ... }
好的,现在来个使用例子吧:
namespace demo\command; use demo\domain\Classroom; use demo\base\ApplicationRegistry; use demo\domain\ObjectWatcher; use demo\domain\HelperFactory; class Test extends Command { protected function doExecute(\demo\controller\Request $request) { $crMapper = HelperFactory::getFinder('demo\domain\Classroom'); // 新创建的对象 markNew() $crA = new Classroom(); $crA->setName('四年(3)班'); // 修改后的“脏”数据 $crB = $crMapper->findById(1); $crB->setName("五年(2)班"); } }
localhost/demo/runner.php?cmd=Test
insert :demo\domain\Classroom_四年(3)班_58 update :demo\domain\Classroom_五年(2)班_1
现在对领域对象的管理有了较大的改进了。还有,我们使用模式的目的是提高效率,而不是降低效率。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using
