Home >PHP Framework >Laravel >What design patterns does laravel use?
Design patterns used by laravel: factory mode, singleton mode, registration tree mode, adapter mode, strategy mode, data object mapping mode, observer mode, prototype mode, decorator mode, iterator mode, Agent mode, etc.
The operating environment of this tutorial: Windows 7 system, Laravel 6 version, Dell G3 computer.
This article introduces you to some commonly used design patterns in Laravel. You have been using them, but you may not know them. . .
1: Factory mode
For example: Auth::user()
here Auth
This class is the method in the factory, Auth
is the alias in the registration tree.
Benefits:
Similar to function encapsulation, it allows objects to have a unified generation (instantiation) entry. When the class name of the class corresponding to our object changes, we only need to change the instantiation method in the factory class.
2: Singleton pattern
Benefits:
Objects cannot be instantiated externally and can only Can be instantiated once to save resources.
Implementation method:
private static $ins = null; //设置私有的属性 private function __construct() {} //使外部无法new这个类 public static function getIns() { //暴露给外部的调用方法 if(self::$ins instanceof self) { return self::$ins; } else { self::$ins = new self(); return self::$ins; } }
Declare a private or protected static variable of a class, declare the constructor as private (external new operations are not allowed), instantiate it if it does not exist, and then Return, if it exists, return directly.
3: Registration tree mode
Use:
config/app
#aliasesThe array in ## is a registration tree
Benefits:
The registration tree mode uses an array structure to access objects and factories. The method only needs to be called once (it can be placed in a place such as system environment initialization). When you need to call the object in the future, you can directly take it out from the registration tree. There is no need to call the factory method or singleton mode.Implementation method:
class Register { protected static $objects function set($alias,$object) { //将对象映射到全局树上 self::$objects[$alias]=$object; } static function get($name) { //获取对象 return self::$objects[$name]; } function _unset($alias) { //从全局树移除对象 unset(self::$onjects[$alias]); } }
$alias represents the alias, set it yourself
in the factory mode
Register::set('db1',$db);
Register::$objects['db1'];
4: Adapter mode
encapsulates different function interfaces of different tools into a unified API for easy calling. Such as:mysql,
mysqli,
PDO.
interface Database { function connect($host,$user,$password,$dbname); function query($sql); function close(); }Then use different tool functions to implement the same interface.
5: Strategy pattern
Benefits:Encapsulates a specific set of behaviors and algorithms into classes to adapt Certain specific contexts separate logical judgment from specific implementation, achieve hard coding to decoupling, and enable IOC, dependency inversion, and inversion control. Implementation:1. Define a strategy interface file (UserStrategy.php), define the strategy interface, and declare the strategy
FemaleUserStrategy.php,
MaleUserStrategy.php), implement the strategy interface, and override the strategy method
class Page { protected $strategy; function index() { if($request->get('female')) { $strategy=new FemaleUserStrategy(); } else { $strategy=new MaleUserStrategy(); } $this->strategy->method(); } public function __construct(UserStrategy $strategy) { $this->strategy=$strategy; } }
6: Data object mapping mode
Benefits: Mapping objects and data storage, operations on an object will be mapped to operations on data storage, which is also the implementation mechanism of ORM.class Model { public $id; public $name; public $email; …… function __construct($id) { //构造函数,调用class时自动执行,用来初始化。 //查询逻辑 } function __destruct() { //析构函数,当class调用完成后自动执行,用它来销毁实例,释放资源。 //增删改逻辑 } }
7: Observer pattern
Use: Trigger classEvent
<?php namespace App\Events; abstract class Event { //逻辑代码 }Listening class
EventListener
<?php namespace App\Listeners; use App\Events\SomeEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class EventListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SomeEvent $event) { // } }Benefits:When the status of an object changes, all objects that rely on it will receive notifications and automatically update, implementing Low coupling, non-intrusive notification and update mechanism.
8: Prototype pattern
# is similar to the factory pattern and is used to create objects. The difference is that the prototype pattern first creates a prototype object. , and then create new objects by cloning the prototype object. The prototype mode is suitable for the creation of large objects and only requires memory copying.$Object = new Object(); $object_1 = clone $Object; $object_2 = clone $Object;
9: Decorator pattern
To modify or add the functionality of a class, the traditional way is to write a subclass to inherit it , and reimplement the class method. The decorator pattern only needs to add a decorator object at runtime to dynamically add or modify the functionality of a class. Traditional method:class Method2 extends Method { function doSomething() { echo "<div style='color:red'>" parent::doSomething(); echo "</div>"; } } interfa Decorator { //定义装饰器接口 function beforeAction(); function afterAction(); //more decoratorMethod…… } class SomeClass { protected $decorators = []; function addDecorator(Decorator $decorator) { $this->decorators[] = $decorator; } function beforeMethod() { foreach ($this->decorators as $row) { $row->beforeAction(); } } function afterMethod() { $decorators = array_reverse($this->decorators); //做一个反转 foreach ($this->decorators as $row) { $row->afterAction(); } } function action() { $this->beforeMethod(); //method; $this->afterMethod(); } } class OneDecorator implements Decorator { protected $datas; function __construct($datas = 'request') { $this->datas = $datas; } function beforeAction() { echo "<div style='color:{$this->datas};'>"; } function afterAction() { echo "</div>"; } } $Object = new \SomeClass(); $Object->addDecorator(new \OneDecorator('blue')); //Add other decorator... $Object->action();
10:迭代器模式
在不需要了解内部实现的前提下,遍历一个聚合对象的内部元素,相对于传统编程方式它可以遍历元素所需的操作。
例如:
Object::all() Iterator extends Traversable { //PHP内置迭代器接口 /* 方法 */ abstract public mixed current (void) abstract public scalar key (void) abstract public void next (void) abstract public void rewind (void) abstract public boolean valid (void) } class ObjectAll implements \Iterator { protected $ids; //所有对象的id protected $index; //迭代器的当前位置 protected $data = array(); //保存从数据库取到的所有对象 function __construct() { //取出所有的id,$ids } function current() { //获取当前的元素的数据,第三个调用 $id = $this->ids[$this->index]['id']; return Object::find($id); } function next() { //获取下一个元素,第四个调用 $this->index ++; } function valid() { //验证当前元素是否还有下一个元素(查询当前是否有数据),第二个调用 return $this->index < count($this->$ids); } function rewind() { //当迭代器执行到末尾时,重置迭代器到整个集合的开头,最先调用 $this->index = 0; } function key() { //获取当前的索引,最后调用 return $this->index; } } $objects = new \ObjectAll(); foreach ($objects as $row) { dump($row->field); //增删改查操作 }
11:代理模式
在客户端与实体之间建立一个代理对象,客户端对实体进行操作全部委派给代理对象,隐藏实体的具体实现细节(slave
读库与master
写库分离)。代理对象还可以与业务代码分离,部署到另外的服务器,业务代码中通过PRC
来委派任务。
interface DBproxy { function getInfo($id); function setInfo($id, $value); } class Proxy implements DBproxy { function get() { //DB::('slave'); query } function set() { //DB::('master'); query } } $proxy = new Proxy(); $proxy->get($id); $proxy->set($id, $value);
相关推荐:最新的五个Laravel视频教程
The above is the detailed content of What design patterns does laravel use?. For more information, please follow other related articles on the PHP Chinese website!