search
HomeBackend DevelopmentPHP TutorialStudy Notes---Dahua PHP Design Pattern_PHP Tutorial

Study notes---Dahua PHP design pattern

PHPStorm IDE
Selection of development fonts: Source Code Pro, Courier New, Concolas
php namespace: can resolve conflicts between methods with the same name in different classes
namespace test1;
function test(){
Auto loading:
function __autoload($class){
require __DIR__.'/'$class.'.php';
}
spl_autoload_register(); This function can allow multiple autoloads and must be in the first line
For example:
spl_autoload_register('autoload1');
spl_autoload_register('autoload2');
function autoload1($class){
require __DIR__.'/'$class.'.php';
}
function autoload2($class){
require __DIR__.'/'$class.'.php';
}
require later class name::method name call();
For example: Test1::test();Test2::test();
PSR-0 Specification
1 The namespace of php must be consistent with the absolute path
2 The first letter of the class name and the file name must be capitalized
3 Except for intersection files, other ".php" must have only one class and cannot have executable code. For example: echo();
__DIR__ Magic constant Get the path of the current file
__FUNCTION__ Magic constant Get the current method
__METHOD__ Magic constant to get the current class name and method
BASEDIR Website root directory
SPL standard introduction
SplStack(); first-in-last-out stationary data structure
$stack=new SplStack();
$stack->push("test1"); //First inbound
$stack->push("test2"); //Advanced
echo $stack->pop(); //Last exit outbound test2
echo $stack->pop(); //pop out test1
SplQueue(); first-in-first-out queue data structure
$SplQueue=new SplQueue();
$SplQueue->enqueue("test1"); //Advanced
$SplQueue->enqueue("test2"); //Advanced
echo $SplQueue->dequeue(); //First out test1
echo $SplQueue->dequeue(); //First out test2
SplMinheap(); Heap data structure
$SplMinheap=new SplMinheap();
$SplMinheap->insert('test1');
$SplMinheap->insert('test2');
echo $SplMinheap->extract(); test1
echo $SplMinheap->extract(); test2
$sqlFixedArray(); Fixed size array (fixed length)
$array= new $sqlFixedArray(10); (set the data length in brackets)
$array['0']=1;
$array['8']=8;
PHP chain test operation implementation The advantage is that you can use one line of code to implement many functions
$ob->where()->order()->limit()->select();
PHP advanced object-oriented features
Using PHP magic methods
1 __get/__set                                                                                                                                                                                      
2 __call/__callStatic //Used to control PHP method calls/control class static method calls
3 __toString //Convert a PHP object into a string
4 __invoke                                                                                                                                                                                  
The printed result will be printed regardless of whether the subscripts 1-7 have a value. If there is no value, a null value will be automatically given
PHPstorm configuration and installation
http://blog.csdn.net/ikscher/article/details/43672365
Three basic design patterns
Factory pattern: Use factory methods or classes to generate objects, instead of directly replacing new with new in the code
Benefits: In case of changes, you only need to change one factory pattern class
Singleton mode: allows objects of a certain class to be created only once
Benefits: No matter how many instance objects are needed, the database is actually only connected once
Registration mode: Global shared exchange object works better with factory mode
Benefit: globally shared exchange object
Trying the registration tree together with the factory mode can reduce the waste of memory resources. Because the same object is called. You can also add data pairs
Image mapping mode reduces direct operations on the database and operates the properties of the class library
Adapter Mode
Encapsulate different interfaces into a unified API
PHP classes are single inheritance, that is, multiple inheritance is not supported. When a class requires the functions of multiple classes, inheritance is powerless. For this reason, PHP cited
Incorporated class interface technology.
If all methods in an abstract class are abstract methods, no variables are declared, and all members in the interface are public
Permissions, then this special abstract class is called interface.
The interface is defined using the keyword interface, and the keyword implements is used to implement the methods in the interface, which must be fully implemented.
Strategy Pattern Encapsulates a specific set of behaviors and algorithms into classes to adapt to certain specific contexts. This pattern is the Strategy Pattern
For example, judging the gender of the user and giving different needs
Write the man’s needs first and then write the woman’s needs
Decide which requirement to call based on the transmitted value, instead of using cumbersome judgment to implement it. If you want to change it, just write another requirement
Data object mapping mode
1 Data object mapping mode is to map objects and data storage. Operations on an object will be mapped to operations on data storage
Observer Pattern When the state of an object changes, all objects that depend on it will be notified and automatically updated. Useful When an event occurs
When it is generated, everything related to it can be written in the observer class
Prototype mode is similar to factory mode, both are used to create objects
Different from the implementation of the factory pattern, the prototype pattern creates a prototype object in advance and then creates a new object by cloning the prototype object.
This eliminates the need for initialization when creating a class
Prototype pattern is suitable for the creation of large objects. Creating a large object requires a lot of overhead. If it is new every time, it will consume a lot of money. The prototype mode is only
Memory copy is required.
Use: For example, a class object created involves many loops and the like. After new is created, the object can be cloned directly the next time it is called
Instead of continuing with new
Decorator mode Decorator mode (Decorator) can dynamically add and modify the function of a class. A class provides a function. If you modify
And adds additional functionality to the traditional editing mode, you need to write a subclass to inherit it and reimplement the class method
Using the decorator pattern, you only need to add a decorator object at runtime to achieve maximum flexibility.
Iterator pattern traverses the internal elements of an aggregate object without knowing the internal implementation
Compared with traditional programming patterns, the iterator pattern can hide the operations required to traverse elements
namespace test;
class AllUser implements Iterator {//Call the iterator interface provided by PHP itself
protected $ids;
protected $data = array();
protected $num ;
function __construct(){
//Instantiate the model
//Read database
}
function valid(){//Verify whether there is another element currently
}
function next(){//Get the next element
}
function current(){ //Get the current element
}
function rewind(){//Reset the entire iterator
}
function key(){//Get the position in the iterator
}
Agent Mode
Establish a proxy object (proxy) between the client and the entity. The client delegates all operations on the entity to the proxy object, hiding the entity
Specific implementation details of
The proxy can also be separated from the business code and deployed to another server. The business code delegates tasks through RPC.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1060602.htmlTechArticleStudy notes---Dahua PHP design pattern PHPStorm IDE development font selection: Source Code Pro, Courier New, Concolas PHP namespace: can solve the conflict of methods with the same name in different classes...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

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.