search
HomeBackend DevelopmentPHP TutorialTransaction 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 Transaction script and domain model of business logic layer

  1. //Create a base class here for data processing, assuming that pdo is used
  2. abstract class Base
  3. function
  4. __construct { $dsn = woobaseApplicationRegistry::getDSN( );
  5.                                                                                                                                                                                           "No DSN" );
  6. }
  7. $dsn ); self::$DB
  8. ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_
  9. Exception); functiondoStatement() { Execute sql
  10. }
  11. }
  12. static $add_blog = "INSERT INTO blog (name) values(?)"
  13. ;
  14. static$del_blog
  15. =
  16. "DELETE FROM blog WHERE (?)";
  17. //Add blogtransaction script
  18. function addBlog(...) {
  19. //Process parameters, spell sql in add_blog format, call the parent class doStatement to execute, notify friends, and a series of subroutines. . .
  20. }
  21. delBlog(...) {
  22.           // Processing parameters, spelling del_blog Format sql, call the parent class doStatement to execute. }
  23. } ?> 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
  24. 2.1 Concept
  25. 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
  26. 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
  27. 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.
  28. 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 Transaction script and domain model of business logic layer

    1. //Create a base class here for data processing, assuming that pdo is used
    2. abstract class Base
    3. function
    4. __construct { );
    5. if
    6. (is_null($dsn)) {
    7.                                                                                                      :$DB =
    8. new
    9. PDO($dsn); self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_
    10. Exception
    11. ); }
    12. protected
    13. function
    14. doStatement() {
    15. } }
    16. class D Blogmodel
    17. Extends Base {
    18. Function addblog (...) {}}}
    19. abstract
    20. class DomainObject {
    21. private
    22. $id;
    23. function __construct($id
    24. = null ) {
    25.                                                                                                                functiongetId() {
    26. return$ this
    27. ->id;
    28. }
    29. static function
    30. getCollection(
    31. $type) {
    32.               //Get the
    33. object to be operated on 
    34.                                  DomainObject {
    35. private $name;
    36. private $feed
    37. ;
    38. function__construct($id
    39. =null,
    40. $name=null) { $this->name = $name
    41. ;
    42. $id ) ;
    43. }
    44. function addBlog(...){
    45. //Call the feed to send notifications to friends
    46. }
    47. function setFeed(FeedCollection $Feed
    48. ) {
    49. $Feed;
    50. } }
    51. ?>
    52. 2.4 Summary
    53. 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.
    The above introduces the transaction script and domain model of the business logic layer, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

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

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

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

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

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

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

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.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

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

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

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.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

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.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

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

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft