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

What are the php design patterns?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you what php design patterns are, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!

1. Singleton mode

The singleton pattern means that only one instance of this class exists in the application at any time. It is common that we use singleton mode to allow only one object to access the database, thus preventing multiple database connections from being opened. To implement a singleton class, you should include the following:

Unlike ordinary classes, singleton classes cannot be instantiated directly, but can only be instantiated by themselves. Therefore, to achieve such a restrictive effect, the constructor must be marked private.

For a singleton class to work without being directly instantiated, it must be provided with such an instance. Therefore, it is necessary for the singleton class to have a private static member variable that can hold the instance of the class and a corresponding public static method that can access the instance.

In PHP, to prevent the cloning of singleton objects from breaking the above implementation of singleton classes, an empty private _ clone () method is usually provided for the base.

Here is a basic singleton pattern:

The copy code is as follows:

Class SingetonBasic {

Private static $instance

/ / other vars..

Private function _ construct () {

/ / do construct..

}

Private function _ _ clone () {}

Public static function getInstance () {

If (! (self::$instance instanceof self)) {

Self::$instance = new self ()

}

Return self::$instance

}

/ / other functions..

}

$a = SingetonBasic::getInstance ()

B = SingetonBasic::getInstance ()

Var_dump ($a = = $b)

2. Factory mode

The factory pattern is that you can create a class that is specifically implemented and returns instances of other classes depending on the input parameters or application configuration. Here is one of the most basic factory models:

The copy code is as follows:

Class FactoryBasic {

Public static function create ($config) {

}

}

For example, here is a factory that describes shape objects that want to create different shapes depending on the number of parameters passed in.

The copy code is as follows:

/ / the common function of defining shapes: obtaining perimeter and area.

Interface IShape {

Function getCircum ()

Function getArea ()

}

/ / define rectangle class

Class Rectangle implements IShape {

Private $width, $height

Public function _ _ construct ($width, $height) {

$this- > width = $width

$this- > height = $height

}

Public function getCircum () {

Return 2 * ($this- > width + $this- > height)

}

Public function getArea () {

Return $this- > width * $this- > height

}

}

/ / define a circle class

Class Circle implements IShape {

Private $radii

Public function _ _ construct ($radii) {

$this- > radii = $radii

}

Public function getCircum () {

Return 2 * M_PI * $this- > radii

}

Public function getArea () {

Return M_PI * pow ($this- > radii, 2)

}

}

/ / create different shapes according to the number of parameters passed in.

Class FactoryShape {

Public static function create () {

Switch (func_num_args ()) {

Case 1:

Return new Circle (func_get_arg (0))

Break

Case 2:

Return new Rectangle (func_get_arg (0), func_get_arg (1))

Break

}

}

}

/ / rectangular object

C = FactoryShape::create (4,2)

Var_dump ($c-> getArea ())

/ / Circle object

$o = FactoryShape::create (2)

Var_dump ($o-> getArea ())

Using the factory pattern makes it easier to call a method because it has only one class and one method, and if you do not use the factory pattern, decide which class and which method should be called Using the factory pattern also makes it easier to make changes to the application in the future. For example, to add support for a shape, you only need to modify the create () method in the factory class, instead of using the factory pattern, you need to modify the code block that calls the shape.

3. Observer mode

The Observer pattern provides you with another way to avoid tight coupling between components. The pattern is simple: an object makes itself observable by adding a method that allows another object, that is, the observer to register itself. When the observable object changes, it sends a message to the registered observer. The actions performed by these observers using this information are independent of the observable object. The result is that objects can talk to each other without having to know why.

A simple example: when a listener listens to a radio station (that is, the station joins a new listener), it sends a prompt message that can be observed by the log watcher who sent the message.

The copy code is as follows:

/ / Observer interface

Interface IObserver {

Function onListen ($sender, $args)

Function getName ()

}

/ / observable interface

Interface IObservable {

Function addObserver ($observer)

Function removeObserver ($observer_name)

}

/ / Observer class

Abstract class Observer implements IObserver {

Protected $name

Public function getName () {

Return $this- > name

}

}

/ / observable class

Class Observable implements IObservable {

Protected $observers = array ()

Public function addObserver ($observer) {

If (! ($observer instanceof IObserver)) {

Return

}

$this- > observers [] = $observer

}

Public function removeObserver ($observer_name) {

Foreach ($this- > observers as $index = > $observer) {

If ($observer- > getName () = $observer_name) {

Array_splice ($this- > observers, $index, 1)

Return

}

}

}

}

/ / simulate a class that can be observed: RadioStation

Class RadioStation extends Observable {

Public function addListener ($listener) {

Foreach ($this- > observers as $observer) {

$observer- > onListen ($this, $listener)

}

}

}

/ / simulate an observer class

Class RadioStationLogger extends Observer {

Protected $name = 'logger'

Public function onListen ($sender, $args) {

Echo $args, 'join the radiostation.'

}

}

/ / simulate another observer class

Class OtherObserver extends Observer {

Protected $name = 'other'

Public function onListen ($sender, $args) {

Echo 'other observer..'

}

}

$rs = new RadioStation ()

/ / inject into the observer

$rs- > addObserver (new RadioStationLogger ())

$rs- > addObserver (new OtherObserver ())

/ / remove the observer

$rs- > removeObserver ('other')

/ / you can see the observed information

$rs- > addListener ('cctv')

These are all the contents of the article "what are php Design patterns?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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