Transaction script and domain model of business logic layer
In the previous blog, we have learned about the three presentation layer modes of front-end controller, page controller, and application controller. If they carefully arrange the communication between the external world and the inside of the system, then the work of the business logic layer It is the business part that handles the application. The business logic layer should be kept away from external "noise". Business logic is the fundamental purpose of the entire application, and other parts of the system serve this part.
Here are two commonly used domain logic patterns: transaction script pattern and domain model pattern.
1. Transaction Script
1.1 Concept
Transaction Script: Use processes to organize business logic, and each process handles a single request from the presentation layer. It seems a bit too abstract. Most business applications can be viewed as a series of transactions. Sometimes, a transaction may simply display database information, and sometimes it may involve many checksum calculation steps. Transaction scripts organize all this logic into a single process, and each transaction has its own transaction script, which means it has its own execution process. However, note that common subtasks between transactions can be decomposed into multiple subroutines.
1.2 Why use transaction scripts
The advantage of transaction script mode is that you can get the results you want quickly. Each script handles the input data well and manipulates the database to ensure the desired results. Therefore, it is a fast and effective mechanism that does not require investing a lot of time and energy in complex design. It is perfect for small projects with tight deadlines.
1.3 Implementing transaction scripts
Based on my work experience, many programmers are using this pattern without knowing it, including myself before.
Now suppose that there is a business of publishing blog and deleting blog, then treat these two businesses as two transaction scripts respectively.
Php code
- //Create a base class here for data processing, assuming that pdo is used
- abstract class Base function
- __construct { $dsn = woobaseApplicationRegistry::getDSN( );
- "No DSN" );
- }
- $dsn ); self::$DB ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_
- Exception); functiondoStatement() { Execute sql
- }
- }
- static $add_blog = "INSERT INTO blog (name) values(?)" ;
- static$del_blog =
- "DELETE FROM blog WHERE (?)";
- //Add blogtransaction script
- function addBlog(...) {
- //Process parameters, spell sql in add_blog format, call the parent class doStatement to execute, notify friends, and a series of subroutines. . .
- }
- delBlog(...) {
- // Processing parameters, spelling del_blog Format sql, call the parent class doStatement to execute. }
- } ?> If you are writing a more complex application, this approach makes the project less scalable because transaction scripts inevitably bleed into each other, resulting in code duplication. 2. Domain Model
- 2.1 Concept Domain Model: It is difficult to explain clearly in words. Simply put, the domain model symbolizes the various participants in the project in the real world. The principle of "everything is an
- object" is most vividly reflected here. Elsewhere objects always carry various specific responsibilities, but in domain patterns, they are often described as a set of properties and attached agents. They are certain things that do certain things. 2.2 Why use domain model In real code, there will be many transaction script patterns, and you will find that duplicate code is a common problem. When different transactions want to perform the same task, duplication seems to be the fastest solution, but this greatly increases the cost of code maintenance. Sometimes it can be solved by refactoring, but slowly copy-pasting may become an unavoidable part of development.
-
2.3 Implementing the domain model
To achieve comparison, quote the example of the transaction model, and map the domain model class directly to the table of the relational database (doing this will make development simpler)
Php code
- //Create a base class here for data processing, assuming that pdo is used
- abstract class Base function
- __construct { ); if
- (is_null($dsn)) {
- :$DB = new
- PDO($dsn); self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_ Exception
- ); }
- protected function
- doStatement() {
- } }
- class D Blogmodel
- Extends Base {
- Function addblog (...) {}}}
- abstract
- class DomainObject {
- private
- $id;
- function __construct($id = null ) {
- functiongetId() {
- return$ this ->id;
- }
- static function getCollection(
- $type) {
- //Get the object to be operated on
- DomainObject {
- private $name;
- private $feed ;
- function__construct($id =null,
- $name=null) { $this->name = $name ;
- $id ) ;
- }
- function addBlog(...){
- //Call the feed to send notifications to friends
- }
- function setFeed(FeedCollection $Feed ) {
- $Feed;
- } }
- ?>
- 2.4 Summary
- Whether the domain model is designed to be simple or complex depends on the complexity of the business logic. The advantage of using a domain model is that when you design the model, you can focus on the problems that the system wants to solve, while other problems (such as persistence and performance, etc.) can be solved by other layers. In implementation projects, most programmers still focus half of their attention on the database when designing the domain model. Separating the domain model from the data layer comes at a cost, and you might as well put the database code directly into the model (although you might use a data entry to handle the actual SQL). For relatively simple models, especially when classes correspond to data tables one-to-one, this method is completely feasible and can reduce the time consumption caused by creating external systems for coordinating objects and databases.

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
