


PHP Three-Layer Structure (Part 2) PHP Implementation of AOP Page 1/2_PHP Tutorial
Source code download address for this article: http://xiazai.jb51.net/201007/yuanma/TraceLWord.rar
The development environment is eclipse(pdt)
Let us focus on the intermediate service layer. The intermediate service layer code is relatively simple. It just calls the data access layer code to save the message to the database. As shown in code 1:
// Code 1
// Intermediate service layer
class LWordServiceCore implements ILWordService {
//Add a message
public function append($newLWord) {
//Call the data access layer
$dbTask = new LWordDBTask();
$ dbTask->append($newLWord);
}
};
After seeing the message board demonstration, the company’s product department and marketing department may propose various ideas and needs. For example, they want to determine the user's permissions before adding a message! Only registered users can leave messages! We need to modify the code, as shown in code 2:
// Code 2, add login Verification
// Intermediate service layer
class LWordServiceCore implements ILWordService {
// Add message
public function append($newLWord) {
if (!($userLogin)) {
// Prompt user to log in
}
// Call the data access layer
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
}
};
The marketing department also hopes to check the content of the message before adding it. If the message contains swear words, it will not be saved. We continue to modify the code, as shown in code 3:
// Code 3, add swear words Filter
// Intermediate service layer
class LWordServiceCore implements ILWordService {
// Add message
public function append($newLWord) {
if (!($userLogin)) {
// Prompt user to log in
}
if (stristr($newLWord, "SB")) {
// Contains swear words, prompt message sending failure
}
// Call the data access layer
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
}
};
The product department also put forward new requirements , they hope to add a points mechanism. Specifically, it gives the user +5 points every time they successfully leave a message. We continue to modify the code, as shown in code 4:
// Code 4, add a message Points mechanism
// Intermediate service layer
class LWordServiceCore implements ILWordService {
// Add message
public function append($newLWord) {
if (!($userLogin)) {
// Prompt user to log in
}
if (stristr($newLWord, "SB")) {
// Contains swear words, prompt message sending failure
}
// Call data access Layer
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
// Give users extra points
$score = getUserScore($userName);
$score = $score + 5;
saveUserScore($userName, $score);
}
};
Not long after, the product department refined the requirements , they hope that users will be upgraded every time they accumulate 1,000 points. We continue to modify the code, as shown in code 5:
// Code 5, add users Upgrade rules
//Intermediate service layer
class LWordServiceCore implements ILWordService {
//Add message
public function append($newLWord) {
if (!($userLogin)) {
// Prompt user to log in
}
if (stristr($newLWord, "fuck")) {
// Contains swear words, prompt message sending failed
}
// Call the data access layer
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
// Add points to the user
$score = getUserScore($userName);
$score = $score + 5;
saveUserScore($userName, $score);
// Upgrade the user
if (($score % 1000) == 0) {
$level = getUserLevel($userName);
$level = $level + 1;
saveUserLevel($userName, $level);
}
}
};
As demand increases, we need to constantly modify the intermediate service layer code. But it should not be difficult for you to find that the more requirements there are, the more and larger the intermediate service layer code will be! In the end, even if we use the three-layer structure development model, we still cannot effectively reduce the difficulty of the project! In addition, after modifying the intermediate service code in response to changes in demand, all codes need to be retested, instead of effectively testing new codes...
In fact, let us analyze this message board code carefully. I want to first propose A concept of primary business logic and secondary business logic. No matter what, storing the message content in the database is the backbone of the business logic! This is the main business logic! This section has not been modified as demand has increased. As for permission verification and content checking before storing in the database, and adding points to users after storing in the database, and then upgrading users, these are all pre-processing and finishing tasks, and they are all secondary business logic! The main business logic is almost unchanged, but the secondary business logic changes very frequently. In order to improve the readability and maintainability of the code, we can consider placing these secondary business logic elsewhere and try not to let them interfere with the main business logic. The main business logic should concentrate on what it should do. As for anything else, the main business logic will not care about it! Then our code can be written like this, as shown in code 6:
// Code 6. Separate the main business logic and secondary business logic
// Intermediate service layer
class LWordServiceCore implements ILWordService {
// Add message
public function append($newLWord) {
// Before adding a message
beforeAppend($newLWord);
// Call the data access layer
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
/ / After adding a message
behindAppend($newLWord);
}
};
We can put the permission judgment code and message content text filtering code into the beforeAppend function, The user points code is inserted into the behindAppend function, thus cleaning up the secondary business logic from the main business logic code. The main business logic knows that there is an "overture" function beforeAppend and an "epilogue" function behindAppend, but the main business logic does not know what is specifically done in the overture and epilogue functions, and does not need to know! Of course, the actual coding work is not that simple. We have to take into account more changes in needs of the product department and marketing department, so it is best to implement a plug-in method to deal with such changes, but relying only on the two functions beforeAppend and behindAppend is the best way to achieve this goal. This cannot be achieved~
If you want to implement the plug-in method, you can create an interface! The advantage of using interfaces is that they can isolate definition and implementation, and the other is to achieve polymorphism. We create a message extension interface ILWordExtension, which has two functions beforeAppend and behindAppend. Functions such as permission verification, content inspection, and bonus points can be regarded as three implementation classes that implement the ILWordExtension interface. The main business logic traverses these three implementation classes in order to complete the secondary business logic. As shown in Figure 1:
The CheckPowerExtension extension class is used for user permission verification, the CheckContentExtension extension class is used for message content checking, and the AddScoreExtension extension class is used for adding points and upgrades to users. The schematic code is shown in code 7:

(Figure 1), add the extended interface
// Code 7, add extension interface
// Extension interface
interface ILWordExtension {
// Before adding a message
public function beforeAppend($newLWord);
/ / After adding a message
public function behindAppend($newLWord);
};
// Check permissions
class CheckPowerExtension implements ILWordExtension {
// Before adding a message
public function beforeAppend($newLWord) {
// Determine user permissions here
}
// After adding a message
public function behindAppend($newLWord) {
}
};
// Check message text
class CheckContentExtension implements ILWordExtension {
// Before adding message
public function beforeAppend($newLWord) {
if (stristr($newLWord, "SB")) {
throw new Exception();
}
}
// After adding a message
public function behindAppend($newLWord) {
}
};
// User points
class AddScoreExtension implements ILWordExtension {
// Before adding a message
public function beforeAppend($newLWord) {
}
// After adding a message
public function behindAppend($newLWord) {
// Give users points here
}
};
// Intermediate service layer
class LWordServiceCore implements ILWordService {
//Add a message
public function append($newLWord) {
//Before adding a message
$this->beforeAppend($newLWord);
// Call the data access layer
$dbTask = new LWordDBTask();
$dbTask->append($newLWord);
// After adding a message
$this-> ;behindAppend($newLWord);
}
// Before adding a message
private function beforeAppend($newLWord) {
// Get the extended array
$extArray = $this- >getExtArray();
foreach ($extArray as $ext) {
// Traverse each extension and call its beforeAppend function
$ext->beforeAppend($newLWord);
}
}
// After adding a message
private function behindAppend($newLWord) {
// Get the extension array
$extArray = $this->getExtArray ();
foreach ($extArray as $ext) {
// Traverse each extension and call its behindAppend function
$ext->behindAppend($newLWord);
}
}
// Get the extension array,
// The return value of this function is actually the ILWordExtension interface array
private function getExtArray() {
return array(
// Check permissions
new CheckPowerExtension(),
// Check content
new CheckContentExtension(),
// Bonus points
new AddScoreExtension(),
);
}
};
If there are new requirements, we only need to add the ILWordExtension implementation class and register it in the getExtArray function. The program has since become organized and can be considered scalable.

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
