Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use PHP advanced features

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use the advanced features of PHP". In daily operation, I believe many people have doubts about how to use the advanced features of PHP. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about how to use the advanced features of PHP. Next, please follow the editor to study!

PHP advanced features-a combination of reflective Reflection and Factory factory design patterns [code example]

PHP advanced features-a combination of reflection and factory design patterns [explained with Laravel-Admin code examples]

Use reflection to achieve factory mode production without creating specific factory classes

Reflection [Relfection]

What is Reflection?

Reflection, or reflection. Reflection provides the ability for object-oriented programming to reflect on itself.

This understanding is a bit too conceptual, which, in popular terms, means that the cause can be found out according to the results of the event. In programming, you can find out which class the object belongs to and that the class has all the properties and methods based on an instantiated object, and you can even read document comments. This process of counter-checking is called reflection.

PHP provides complete reflection API, providing the ability to introspect classes, interfaces, functions, methods, and extensions. In addition, reflection API provides methods to fetch documentation comments from functions, classes, and methods. For more information, please see the introduction to PHP reflection on PHP's official website.

What can Reflection do?

As mentioned above, you can use reflection to get all the properties and methods of a class, as well as annotation documents, and even access to class properties and methods [protected/private]. These features greatly improve the flexibility of using PHP. For example:

-the so-called elegance of the Laravel framework, that is, containers, dependency injection, and IOC control inversion, depends on these features.

-the annotation routing of the Hyperf framework is also implemented according to the annotations obtained by reflection

-generate documents because reflection can gain access to class properties and methods, you can scan all files throughout the project and use reflection to generate documents

-Test-driven development uses reflection to obtain the characteristics of all methods of this class for test-driven development

-Development plug-ins use reflection to capture the internal structure of classes to implement Hook functions, such as framework plug-ins

Advantages and disadvantages of Reflection

Merit reflection provides anti-parsing of classes, resulting in a high degree of flexibility compared to the original object-oriented programming, and reasonable use can make the code look more elegant and concise. Originally, in object-oriented programming, using an instance of a class requires new an object before using a method, but using the reflection mechanism, you only need to provide a method of this class and then use the reflection mechanism to use the object or method. The Laravel framework uses a lot of reflection to gain a reputation for elegance, and the annotation routing implementation of Swoole's Hyperf framework also uses reflection.

At the same time, because reflection is an inverse process of class instantiation, it destroys the object-oriented encapsulation and directly exposes the entire internal structure of the class, which leads to the misuse of reflection, the code will be difficult to manage, and the whole project will be very confusing. Even lead to business execution confusion. Especially in the team of dozens of people in large projects, imagine that the original object-oriented, only tell what can be used, what can not be used, CTO wrote the underlying code, others inherit and then use it, other people do not know the internal structure. Once reflection is used, if a programmer accidentally sets a property or method that was originally protected or private to be accessible, and other programmers unknowingly call data or methods that should have been hidden, it will lead to an unpredictable disaster [see sample code below]

Second, because of the high flexibility of reflection, it is impossible to trace the source directly by clicking on the code in IDE, which is really painful for beginners, both Laravel and Hyperf

In the following code, the reflection mechanism directly sets the private method to be externally accessible

# Example:

Factory design pattern

Three factory design patterns [simple factory pattern] [factory pattern] [abstract factory pattern]

The simple factory pattern is also called the static factory method pattern. To put it simply, the way to create an object is achieved through a static method. In the simple factory pattern, instances of different classes are returned based on the parameters passed

In PHP, in the simple factory pattern, there is an abstract product class [that is, abstract class Calculate], which can be an interface / abstract class / normal class. This abstract product class can derive multiple concrete product classes [i.e. class CalculateAdd and class CalculateSub]. Finally, a specific factory class [that is, class CalculateFactory] is used to obtain the instance of the desired product class.

Code implementation

1) Abstract product production class: operation abstract class

/ / produce abstract class abstract class Calculate {/ / Digital A protected $number_a = null; / / Digital B protected $number_b = null; / / set digital A public function setNumberA ($number) {$this- > number_a = $number;} / / set digital B public function setNumberB ($number) {$this- > number_b = $number;} / / get digital A public function getNumberA () {return $this- > number_a } / / get the digital B public function getNumberB () {return $this- > number_b;} / / get the calculation result [get the product produced] public function getResult () {return null;}}

2) specific product production categories: addition / subtraction, etc.

/ / addition operation class CalculateAdd extends Calculate {/ / obtain operation result [obtain specific product] public function getResult () {return $this- > number_a + $this- > number_b;}} / / subtraction operation class CalculateSub extends Calculate {/ / obtain operation result [obtain specific product] public function getResult () {return $this- > number_a-$this- > number_b }} / / multiplication / division and other operations [other products]

3) Factory: factory class. That is, a separate class is used to create the instantiation process, which is the factory. That is, the simple factory model

In php, the way to implement is actually a switch function or a new match function from php8 to instantiate the required product production class

/ / instantiate different objects according to different operations / / [that is, according to the desired product Instantiate the corresponding product class for production] / / the corresponding implementation is actually a new match function of switch or php8 function / / the following demonstrates class CalculateFactory {public static function setCalculate ($type = null) {return match ($type) {'add' = > (function () {return new CalculateAdd ()) with the latest match function. }) (), 'sub' = > (function () {return new CalculateSub ();}) (), default = > null;};} / / specific use of $calculate = CalculateFactory::setCalculate (' add'); $calculate- > setNumberA = 1There is calculated-> setNumberB = 2bang / calculate echo $calculate- > getResult;//echo 3

Summary:

The simple factory pattern is actually to create a base class [abstract], which stores the common code of all the specific production classes, but does not execute the process, and then all the classes of the specific production products inherit the base class and then implement their respective production processes. Finally, create a factory class that is used to get the required production class based on the passed parameters

The factory method mode, also known as the factory mode, belongs to the creative mode. In factory mode, the parent class of the factory class is only responsible for defining the common interface and does not perform the actual production action. The actual production action is handed over to the subclass of the factory to complete. This delays the instantiation of the class to the subclass of the factory, which instantiates the specific product, that is, production.

In the factory pattern, unlike the simple factory pattern, there is an abstract factory class [i.e. interface CalculateFactory], which can be an interface / abstract class, and this abstract factory class can derive multiple concrete factory classes [i.e. FactoryAdd and FactorySub]

Code implementation [the following code needs to use the above production abstraction class]

The following code requires the production abstract class above: abstract class Calculate

And the specific production categories, namely: CalculateAdd and CalculateSub. Let's not repeat the implementation.

Interface CalculateFactory {public function CreateCalculate ();} class FactoryAdd implements CalculateFactory {public function CreateCalculate () {return new CalculateAdd ();}} class FactorySub implements CalculateFactory {public function CreateCalculate () {return new CalculateSub ();}} / / specific use / / create factory instance $calculateFactory = new FactoryAdd (); $add = $calculateFactory- > CreateCalculate (); $add- > setNumberA (1); $add- > setNumberB (2); / / calculate echo $add- > getResult (); / / echo 3

Summary:

The difference between the factory pattern and the simple factory model is that in the simple factory model, only one factory produces the corresponding production object [that is, CalculateFactory]. In the factory model, each production object is produced by its own factory, and these factories inherit from the same interface [that is, interface CalculateFactory]

Abstract factory pattern abstract factory pattern provides an interface for creating a series of related or interdependent objects without specifying their concrete classes. It's abstract to understand that. A more popular explanation is that, compared to the factory pattern above, the abstract factory pattern has another super factory on top of each different factory, which is an abstract interface [interface] that is used to produce concrete factories.

In the abstract factory pattern, there are multiple abstract product classes [i.e. abstract class Phone and abstract class Android], which can be interfaces / abstract classes / normal classes, and each abstract product class can derive multiple concrete product classes [i.e. class IPhone / class MiPhone and class IOS / class Android]. An abstract factory class [i.e. interface AbstractFactory] can derive multiple concrete factory classes [i.e. class iPhoneFactory and class MiFactory], and each concrete factory class can create multiple instances of product classes [that is, all have createPhone and createSystem]

Code implementation

/ / Abstract product class abstract class Phone {} abstract class System {} / / concrete product class class IPhone extends Phone {} class MiPhone extends Phone {} / specific product class class IOS extends System {} class Android extends System {} / / Super factory interface AbstractFactory {public function createPhone (); public function createSystem ();} / specific Apple factory class iPhoneFactory implements AbstractFactory {/ / production of iPhone public function createPhone () {return new IPhone () } / / production of Apple operating system public function createSystem () {return new IOS ();} / specific Xiaomi factory class MiFactory implements AbstractFactory {/ / production of Xiaomi phone public function createPhone () {return new MiPhone ();} / production of Android public function createSystem () {return new Android ();}}

Summary:

Compared with the factory pattern, the abstract factory pattern provides an interface to specify the products that need to be produced. Every factory that inherits from this interface can produce according to the specified pattern [AbstarctFactory in code]

The final purpose of the above three factory patterns is to extract the duplicate code, summarize, decouple and reuse according to the specific requirements scenarios, so that they can be used directly in the required scenarios.

The three models are summarized as follows:

Simple Factory:

An abstract product class (can be: interface, abstract class, ordinary class), which can derive multiple concrete product classes

A single concrete factory class

Each specific factory class can only create one instance of a specific product class.

Factory mode:

An abstract product class (can be: interface, abstract class, ordinary class), which can derive multiple concrete product classes

An abstract factory class (which can be: interface, abstract class) that can derive multiple concrete factory classes

Each specific factory class can only create one instance of a specific product class.

Abstract factory:

Multiple abstract product classes (can be: interfaces, abstract classes, normal classes), and each abstract product class can derive multiple concrete product classes

An abstract factory class (which can be: interface, abstract class) that can derive multiple concrete factory classes

Each specific factory class can create multiple instances of a specific product class.

The difference between the three modes:

The simple factory pattern has only one abstract product class and only one concrete factory class.

The factory method pattern has only one abstract product class, while the abstract factory pattern has multiple abstract product classes

The concrete factory class of the factory method pattern can only create one instance of the concrete product class, while the abstract factory pattern can create multiple instances of the concrete product class.

The combination of factory mode and reflection

The characteristics of reflection can be used to realize the production process of factory mode, and an example is given with Laravel-admin.

First, take a look at the following code, requirement background: different permission buttons need to be displayed according to different roles.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report