Object-relational behavior pattern lazy loading
1. Concept
Lazy Load: An object, although it does not contain all the data required, but it knows how to obtain the data.
Lazy loading seems to be very simple. It is to obtain the data from the database when it is needed to reduce the consumption of the database. But there are still a lot of tricks involved.
2. Implement lazy loading
There are four main methods to implement Lazy Load: delayed initialization, virtual proxy, value holder and ghosting.
(1) Lazy initialization
1.1 Concept
This is the simplest method. This means that every time you access an attribute field, you must first check whether the field is empty. If it is empty, then obtain the value of this field. This must ensure that all access to this field, even from within the class, must be achieved through the acquisition method.
class Supplier{
private $products;
public function getProducts(){
if($products == null)
$products = $Product->findForSupplier();
return $products;
}
}1.3 When to use
Consider using lazy loading only when the domain requires additional database access.
Requires additional calls, and when the data called when using the main object is not used.
Most suitable for activity records, table data entries and row data entries.
(2) Virtual proxy
2.1 Concept
is essentially an object and does not contain anything. Only when one of its methods is called, it loads the appropriate object from the database.
To put it simply, it is a proxy object of an object. The object is not loaded during initialization. It is only loaded when the proxy object is called.
/**
* 虚代理,只有在被访问成员时才调用闭包函数生成目标对象。
*/
class VirtualProxy
{
private $holder = null;
private $loader = null;
/**
* @param Closure $loader 生成被代理对象的闭包函数
*/
public function __construct(Closure $loader)
{
$this->loader = $loader;
}
/**
* 代理成员方法的调用
*
* @param string $method
* @param array $arguments
* @throws BadMethodCallException
* @return mixed
*/
public function __call($method, array $arguments = null)
{
$this->check();
if (!method_exists($this->holder, $method)) {
throw new BadMethodCallException();
}
return call_user_func_array(
array(&$this->holder, $method),
$arguments);
}
/**
* 代理成员属性的读取
*
* @param string $property
* @throws ErrorException
* @return mixed
*/
public function __get($property)
{
$this->check();
if (!isset($this->holder->$property)) {
throw new ErrorException();
}
return $this->holder->$property;
}
/**
* 代理成员属性的赋值
*
* @param string $property
* @param mixed $value
*/
public function __set($property, $value)
{
$this->check();
$this->holder->$property = $value;
}
/**
* 检查是否已经存在被代理对象,不存在则生成。
*/
private function check()
{
if (null == $this->holder) {
$loader = $this->loader;
$this->holder = $loader();
}
}
}
// 测试
$v = new VirtualProxy(function(){
echo 'Now, Loading', "\n";
$a = new ArrayObject(range(1,100));
$a->abc = 'a';
// 实际使用中,这里调用的是 DataMapper 的 findXXX 方法
// 返回的是领域对象集合
return $a;
});
// 代理对象直接当作原对象访问
// 而此时构造方法传入的 callback 函数才被调用
// 从而实现加载对象操作的延迟
echo $v->abc . $v->offsetGet(50);(3) Value holder (value holder)
3.1 Concept
An object used to wrap some other object. To get the base object, you can access the value holder to get its value, but only the first The first time the value holder is accessed it actually reads the data from the database.
(4) Ghost
4.1 Concept
A real object in partial state. When the object is loaded from the database, it only contains its ID. Every time a domain is accessed, it loads its full state. Think of a ghost as an object, with each of its fields lazily initialized all at once, or as a virtual proxy, with the object itself being its virtual proxy.
//继承要加载的对象
class DeferredEventCollection extends EventCollection {
private $stmt;
private $valueArray;
private $run=false;//标识当前加载状态
//构造方法,不真正获取数据,只包含其$valueArray(ID)
function __construct( Mapper $mapper, \PDOStatement $stmt_handle,array $valueArray ) {
parent::__construct( null, $mapper );
$this->stmt = $stmt_handle;
$this->valueArray = $valueArray;
}
//加载完全状态
function notifyAccess() {
if ( ! $this->run ) {
$this->stmt->execute( $this->valueArray );
$this->raw = $this->stmt->fetchAll();
$this->total = count( $this->raw );
}
$this->run=true;
}
}3. Risks of delayed loading
1. Inheritance often causes problems with delayed loading. If you want to use ghosting, you need to know what type of ghost you want to create, which is often difficult to tell if the data is not loaded correctly. Virtual proxies suffer from the same problem in statically typed languages.
2. Lazy loading can easily lead to more database access than required. Alias in the book "fluctuation loading". For example, use lazy loading to populate a collection, and then only access one element at a time. In this way, the database will be accessed every time an object is accessed, instead of reading out all the required objects at once. This loading method will seriously affect the performance of the system. Of course, instead of using lazy-loaded collections, you can make the class collection itself lazy-loaded, loading the entire content at once when loading the class collection.
4. Summary
Lazy loading is very suitable for aspect-oriented (AOP) programming. The lazy loading operation can be placed in a separate aspect, so that the lazy loading strategy can be changed independently, and domain developers do not have to deal with lazy loading issues.
Regardless of whether you add lazy loading code explicitly in domain classes, lazy loading is a good practice. In addition to type safety, the benefit of using a collection object instead of an array is that you can use lazy loading.
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
1384
52
What is the architecture and working principle of Spring Data JPA?
Apr 17, 2024 pm 02:48 PM
SpringDataJPA is based on the JPA architecture and interacts with the database through mapping, ORM and transaction management. Its repository provides CRUD operations, and derived queries simplify database access. Additionally, it uses lazy loading to only retrieve data when necessary, thus improving performance.
What is the original meaning of dynamic linking and static linking in Linux?
Feb 05, 2024 pm 05:45 PM
As usual, let’s ask a few questions: Why dynamic linking? How to do dynamic linking? What is address-independent code technology? What is delayed binding technology? How to do explicit linking while the program is running? Why dynamic linking? The emergence of dynamic linking is to solve some shortcomings of static linking: saving memory and disk space: As shown in the figure below, Program1 and Program2 contain two modules, Program1.o and Program2.o respectively, and they both require the Lib.o module. In the case of static linking, both target files use the Lib.o module, so they have copies in the executable files Program1 and program2 output by the link and run at the same time.
What to do if the html image is too large
Apr 05, 2024 pm 12:24 PM
Here are some ways to optimize HTML images that are too large: Optimize image file size: Use a compression tool or image editing software. Use media queries: Dynamically resize images based on device. Implement lazy loading: only load the image when it enters the visible area. Use a CDN: Distribute images to multiple servers. Use image placeholder: Display a placeholder image while the image is loading. Use thumbnails: Displays a smaller version of the image and loads the full-size image on click.
Java JPA performance optimization tips: make your application fly
Feb 19, 2024 pm 09:03 PM
Article keywords: JavaJPA performance optimization ORM entity management JavaJPA (JavaPersistance API) is an object-relational mapping (ORM) framework that allows you to use Java objects to operate data in the database. JPA provides a unified API for interacting with databases, allowing you to use the same code to access different databases. In addition, JPA also supports features such as lazy loading, caching, and dirty data detection, which can improve application performance. However, if used incorrectly, JPA performance can become a bottleneck for your application. The following are some common performance problems: N+1 query problem: When you use JPQL queries in your application, you may encounter N+1 query problems. In this kind of
Decoding Laravel performance bottlenecks: Optimization techniques fully revealed!
Mar 06, 2024 pm 02:33 PM
Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid
How does Hibernate optimize database query performance?
Apr 17, 2024 pm 03:00 PM
Tips for optimizing Hibernate query performance include: using lazy loading to defer loading of collections and associated objects; using batch processing to combine update, delete, or insert operations; using second-level cache to store frequently queried objects in memory; using HQL outer connections , retrieve entities and their related entities; optimize query parameters to avoid SELECTN+1 query mode; use cursors to retrieve massive data in blocks; use indexes to improve the performance of specific queries.
How to prevent iframe loading event
Feb 19, 2024 am 08:02 AM
How to prevent iframe loading events In web development, we often use iframe tags to embed other web pages or content. By default, when the browser loads an iframe, the loading event is triggered. However, in some cases we may want to delay the loading of an iframe, or prevent the loading event entirely. In this article, we'll explore how to achieve this through code examples. 1. Delay loading of iframe If you want to delay loading of iframe, we can use
What are the disadvantages of Hibernate ORM framework?
Apr 18, 2024 am 08:30 AM
The HibernateORM framework has the following shortcomings: 1. Large memory consumption because it caches query results and entity objects; 2. High complexity, requiring in-depth understanding of the architecture and configuration; 3. Delayed loading delays, leading to unexpected delays; 4. Performance bottlenecks, in May occur when a large number of entities are loaded or updated at the same time; 5. Vendor-specific implementation, resulting in differences between databases.


