1. Singleton mode
Singleton mode, as the name suggests, means that there is only one instance. As an object creation mode, the singleton mode ensures that a class has only one instance, instantiates itself and provides this instance to the entire system.
There are three main points of the singleton pattern:
First, a class can only have one instance;
Second, it must create this instance by itself;
Third, it must provide this instance to the entire system by itself.
Why use PHP singleton mode
1. PHP is mainly used in database applications. There will be a large number of database operations in an application. When developing in an object-oriented way, if you use the singleton mode, you can avoid a large number of operations. The new operation consumes resources and can also reduce database connections so that too many connections are less likely to occur.
2. If a class is needed to globally control certain configuration information in the system, it can be easily implemented using the singleton mode. This can be found in the FrontController part of zend Framework.
3. In a page request, it is easy to debug because all the code (such as database operation class db) is concentrated in one class. We can set hooks in the class and output logs to avoid var_dump and echo everywhere.
Example:
/** * 设计模式之单例模式 * $_instance必须声明为静态的私有变量 * 构造函数必须声明为私有,防止外部程序new类从而失去单例模式的意义 * getInstance()方法必须设置为公有的,必须调用此方法以返回实例的一个引用 * ::操作符只能访问静态变量和静态函数 * new对象都会消耗内存 * 使用场景:最常用的地方是数据库连接。 * 使用单例模式生成一个对象后,该对象可以被其它众多对象所使用。 */ class man { //保存例实例在此属性中 private static $_instance; //构造函数声明为private,防止直接创建对象 private function __construct() { echo '我被实例化了!'; } //单例方法 public static function get_instance() { var_dump(isset(self::$_instance)); if(!isset(self::$_instance)) { self::$_instance=new self(); } return self::$_instance; } //阻止用户复制对象实例 private function __clone() { trigger_error('Clone is not allow' ,E_USER_ERROR); } function test() { echo("test"); } } // 这个写法会出错,因为构造方法被声明为private //$test = new man; // 下面将得到Example类的单例对象 $test = man::get_instance(); $test = man::get_instance(); $test->test(); // 复制对象将导致一个E_USER_ERROR. //$test_clone = clone $test;
2. Simple factory pattern
①Abstract base class: Define some abstract methods in the class to implement them in subclasses
②Subclasses that inherit from abstract base classes: Implement abstract methods in the base class
③Factory class: used to instantiate all corresponding subclasses
/** * * 定义个抽象的类,让子类去继承实现它 * */ abstract class Operation{ //抽象方法不能包含函数体 abstract public function getValue($num1,$num2);//强烈要求子类必须实现该功能函数 } /** * 加法类 */ class OperationAdd extends Operation { public function getValue($num1,$num2){ return $num1+$num2; } } /** * 减法类 */ class OperationSub extends Operation { public function getValue($num1,$num2){ return $num1-$num2; } } /** * 乘法类 */ class OperationMul extends Operation { public function getValue($num1,$num2){ return $num1*$num2; } } /** * 除法类 */ class OperationDiv extends Operation { public function getValue($num1,$num2){ try { if ($num2==0){ throw new Exception("除数不能为0"); }else { return $num1/$num2; } }catch (Exception $e){ echo "错误信息:".$e->getMessage(); } } }
By using object-oriented inheritance features, we can easily extend the original program, For example: 'power', 'square root', 'logarithm', 'trigonometric function', 'statistics', etc., to avoid loading unnecessary code.
If we need to add a remainder class now, it will be very simple
We only need to write another class (this class inherits the virtual base class) and complete the corresponding functions in the class (for example: multiplication square operation), and greatly reduces the coupling degree, which facilitates future maintenance and expansion
/** * 求余类(remainder) * */ class OperationRem extends Operation { public function getValue($num1,$num2){ return $num1%$num12; } }
There is still an unresolved problem, which is how to let the program instantiate the corresponding object according to the operator input by the user?
Solution: Use a separate class to implement the instantiation process. This class is the factory
/** * 工程类,主要用来创建对象 * 功能:根据输入的运算符号,工厂就能实例化出合适的对象 * */ class Factory{ public static function createObj($operate){ switch ($operate){ case '+': return new OperationAdd(); break; case '-': return new OperationSub(); break; case '*': return new OperationSub(); break; case '/': return new OperationDiv(); break; } } } $test=Factory::createObj('/'); $result=$test->getValue(23,0); echo $result;
Other notes about this pattern:
Factory pattern:
Take transportation as an example: please request it can be customized Transportation, and you can customize the production process of transportation
1> Customize transportation
1. Define an interface, which contains the method of delivering the tool (start, run, stop)
2. Let airplanes, cars, etc. implement them
2> ; Customized factory (similar to above)
1. Define an interface, which contains the manufacturing method of hand tools (start, run, stop)
2. Write factory classes for manufacturing aircraft and cars respectively to inherit and implement this interface
3. Observe Observer Pattern
The Observer Pattern is a behavioral pattern that defines a one-to-many dependency relationship between objects, so that when the state of an object changes, all objects that depend on it are notified and automatically refreshed. . It perfectly separates the observer object and the observed object. A list of dependencies (observers) that are interested in the principal can be maintained in a separate object (the principal). Have all observers individually implement a common Observer interface to eliminate the direct dependency between the principal and dependent objects. (I can’t understand it anyway)
Used spl (standard php library)
class MyObserver1 implements SplObserver { public function update(SplSubject $subject) { echo __CLASS__ . ' - ' . $subject->getName(); } } class MyObserver2 implements SplObserver { public function update(SplSubject $subject) { echo __CLASS__ . ' - ' . $subject->getName(); } } class MySubject implements SplSubject { private $_observers; private $_name; public function __construct($name) { $this->_observers = new SplObjectStorage(); $this->_name = $name; } public function attach(SplObserver $observer) { $this->_observers->attach($observer); } public function detach(SplObserver $observer) { $this->_observers->detach($observer); } public function notify() { foreach ($this->_observers as $observer) { $observer->update($this); } } public function getName() { return $this->_name; } } $observer1 = new MyObserver1(); $observer2 = new MyObserver2(); $subject = new MySubject("test"); $subject->attach($observer1); $subject->attach($observer2);
$subject->notify();
4. Strategy mode
In this mode, the algorithm is derived from complex classes extracted and thus can be easily replaced. For example, if you want to change the way pages are ranked in search engines, Strategy mode is a good choice. Think about the parts of a search engine—one that traverses pages, one that ranks each page, and another that sorts the results based on the ranking. In complex examples, these parts are all in the same class. By using the Strategy pattern, you can put the arrangement part into another class to change the way the page is arranged without affecting the rest of the search engine's code.
As a simpler example, the following shows a user list class that provides a method to find a set of users based on a set of plug-and-play policies
//定义接口 interface IStrategy { function filter($record); } //实现接口方式1 class FindAfterStrategy implements IStrategy { private $_name; public function __construct($name) { $this->_name = $name; } public function filter($record) { return strcmp ( $this->_name, $record ) <= 0; } } //实现接口方式1 class RandomStrategy implements IStrategy { public function filter($record) { return rand ( 0, 1 ) >= 0.5; } } //主类 class UserList { private $_list = array (); public function __construct($names) { if ($names != null) { foreach ( $names as $name ) { $this->_list [] = $name; } } } public function add($name) { $this->_list [] = $name; } public function find($filter) { $recs = array (); foreach ( $this->_list as $user ) { if ($filter->filter ( $user )) $recs [] = $user; } return $recs; } } $ul = new UserList ( array ( "Andy", "Jack", "Lori", "Megan" ) ); $f1 = $ul->find ( new FindAfterStrategy ( "J" ) ); print_r ( $f1 ); $f2 = $ul->find ( new RandomStrategy () );
print_r ( $f2 );
Strategy pattern is very suitable for complex data management systems or data processing systems, both of which require high flexibility in the way of data filtering, searching or processing

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.


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

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),

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

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