About the analysis of facade pattern in PHP

不言
Release: 2023-03-31 22:50:01
Original
2403 people have browsed it

This article mainly introduces the detailed usage and code examples of the facade pattern in PHP. Friends who need this can refer to it.

About the translation of the word facade

The word facade originally refers to the surface and appearance of a building, and is translated as the term "facade" in architecture , the domestic focus on the word facade may be more dependent on the popularity of laravel. It seems that everyone unanimously translates the facade in laravel as "facade". To be honest, when I saw the mention of "facade" in the translation document for the first time, I think you had the same thought as me: "What the hell are you talking about? Are you talking about the store or the store's facade?" "Until now, if I have to say facade in Chinese, if I have to use the word "facade", my heart still will not consciously "click", and I know there is a problem here.

What is the best translation of facade? However, some people simply advocate not translating, and just use the English words when they encounter it. This is not a long-term solution. After all, it is to pave the way for newbies to understand. Later, I accidentally saw that Taiwanese scholars, or Taiwan's Wikipedia to be precise, translated facade pattern as "appearance pattern." Considering the actual role of this pattern, I felt instantly relieved. Even though the facade in laravel is not strictly a facade pattern, many people are still criticizing laravel for its misuse and misleading of the word facade. However, it is still borrowing or imitating the facade pattern, so the facade in laravel, this article also I think it would be better to translate it into "appearance". Of course, for better understanding, it can be "service appearance". Even so, from a personal perspective, I would rather call it "service locator", "service agent" or "service alias". In fact, many people abroad also suggest changing the name like this, but Taylor's attitude on this matter is Unusually tough, so there is no need to force it for now.

Through the following, after actually understanding what facade pattern is, I think you will better understand why it is more appropriate to translate it as "appearance pattern".

What is the facade pattern (definition of "appearance pattern")

Whether in the real world or the programming world, the purpose of the facade (appearance) is to give a Maybe something that was originally ugly and messy is "put on" a beautiful, attractive appearance, or mask. In Chinese proverb: What is appearance? "A man depends on his clothes and a horse depends on his saddle." Based on this, the facade pattern is to add (or convert) one or more messy, complex, and difficult-to-refactor classes to a beautiful and elegant interface (interface), so that you can be happier and more comfortable. It is convenient to operate it, thereby indirectly operating the actual logic behind it.

When to use facade pattern

facade pattern ("appearance pattern") is often used to provide unified functionality to one or more subsystems. Entrance interface (interface), or operation interface.
When you need to operate projects left by others, or third-party code. Especially in general, these codes are not easily refactored and no tests are provided. At this time, you can create a facade ("appearance") to "wrap" the original code to simplify or optimize its usage scenarios.

No matter how much I say, it is better to give a few examples to make it more intuitive:

Example 1: In Java, complex system information inside the computer is operated through the facade

Suppose we have some complex subsystem logic:

class CPU {
 public void freeze() { ... }
 public void jump(long position) { ... }
 public void execute() { ... }
}
class Memory {
 public void load(long position, byte[] data) {
  ...
 }
}
class HardDrive {
 public byte[] read(long lba, int size) {
  ...
 }
}
Copy after login

In order to operate them more conveniently, we can create a Appearance class (facade):

class Computer {
 public void startComputer() {
  cpu.freeze();
  memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
  cpu.jump(BOOT_ADDRESS);
  cpu.execute();
 }
}
Copy after login

Then our customers can easily call like this:

class You {
 public static void main(String[] args) {
  Computer facade = new Computer();
  facade.startComputer();
 }
}
Copy after login

Example 2: A bad third-party mail class

Suppose you have to use the following third-party mail class that looks terrible, In particular, you have to pause for a few seconds to understand each method name:

interface SendMailInterface
{
 public function setSendToEmailAddress($emailAddress);
 public function setSubjectName($subject);
 public function setTheEmailContents($body);
 public function setTheHeaders($headers);
 public function getTheHeaders();
 public function getTheHeadersText();
 public function sendTheEmailNow();
}
class SendMail implements SendMailInterface
{
 public $to, $subject, $body;
 public $headers = array();
 
 public function setSendToEmailAddress($emailAddress)
 {
  $this->to = $emailAddress;
 }
 public function setSubjectName($subject)
 {
  $this->subject = $subject;
 }
 public function setTheEmailContents($body)
 {
  $this->body = $body;
 }
 public function setTheHeaders($headers)
 {
  $this->headers = $headers;
 }
 public function getTheHeaders()
 {
  return $this->headers;
 }
 public function getTheHeadersText()
 {
  $headers = "";
  foreach ($this->getTheHeaders() as $header) {
   $headers .= $header . "\r\n";
  }
 }
 
 public function sendTheEmailNow()
 {
  mail($this->to, $this->subject, $this->body, $this->getTheHeadersText());
 }
}
Copy after login

At this time, you can’t directly change the source code. There is no other way. Let’s create a facade

class SendMailFacade
{
 private $sendMail;
 public function __construct(SendMailInterface $sendMail)
 {
  $this->sendMail = $sendMail;
 }
 public function setTo($to)
 {
  $this->sendMail->setSendToEmailAddress($to);
  return $this;
 }
 public function setSubject($subject)
 {
  $this->sendMail->setSubjectName($subject);
  return $this;
 }
 public function setBody($body)
 {
  $this->sendMail->setTheEmailContents($body);
  return $this;
 }
 public function setHeaders($headers)
 {
  $this->sendMail->setTheHeaders($headers);
  return $this;
 }
 public function send()
 {
  $this->sendMail->sendTheEmailNow();
 }
}
Copy after login

Then the original terminal call without optimization may be like this:

$sendMail = new SendMail();
$sendMail->setSendToEmailAddress($to);
$sendMail->setSubjectName($subject);
$sendMail->setTheEmailContents($body);
$sendMail->setTheHeaders($headers);
$sendMail->sendTheEmailNow();
Copy after login

Now that we have the appearance class, it can be like this:

$sendMail  = new SendMail();
$sendMailFacade = new sendMailFacade($sendMail);
$sendMailFacade->setTo($to)->setSubject($subject)->setBody($body)->setHeaders($headers)->send();
Copy after login

##Example 3: Complete the complex process of a commodity transaction

Assume that a commodity transaction requires the following steps:

$productID = $_GET['productId']; 
$qtyCheck = new productQty();

 // 检查库存
if($qtyCheck->checkQty($productID) > 0) {
  
 // 添加商品到购物车
 $addToCart = new addToCart($productID);
  
 // 计算运费
 $shipping = new shippingCharge();
 $shipping->updateCharge();
  
 // 计算打折
 $discount = new discount();
 $discount->applyDiscount();
  
 $order = new order();
 $order->generateOrder();
}
Copy after login

As you can see, a process includes It involves many steps and involves many Objects. Once similar links are used in multiple places, it may cause problems, so you can create an appearance class first:

class productOrderFacade {
 public $productID = '';  
 public function __construct($pID) {
  $this->productID = $pID;
 }
 public function generateOrder() {   
  if($this->qtyCheck()) {
   $this->addToCart();
   $this->calulateShipping();
   $this->applyDiscount();
   $this->placeOrder();
  }   
 }
 private function addToCart () {
  /* .. add product to cart .. */
 } 
 private function qtyCheck() {
  $qty = 'get product quantity from database';
  if($qty > 0) {
   return true;
  } else {
   return true;
  }
 }
  private function calulateShipping() {
  $shipping = new shippingCharge();
  $shipping->calculateCharge();
 }
 private function applyDiscount() {
  $discount = new discount();
  $discount->applyDiscount();
 }
 private function placeOrder() {
  $order = new order();
  $order->generateOrder();
 }
}
Copy after login

In this way, our terminal call can be solved in two lines:

$order = new productOrderFacade($productID);
$order->generateOrder();
Copy after login

##Example 4: Process of synchronizing messages to multiple social media

// 发Twitter消息
class CodeTwit {
 function tweet($status, $url)
 {
 var_dump('Tweeted:'.$status.' from:'.$url);
 }
}
// 分享到Google plus上
class Googlize {
 function share($url)
 {
 var_dump('Shared on Google plus:'.$url);
 }
}
//分享到Reddit上
class Reddiator {
 function reddit($url, $title)
 {
 var_dump('Reddit! url:'.$url.' title:'.$title);
 }
}
Copy after login

如果每次我们写了一篇文章,想着转发到其他平台,都得分别去调用相应方法,这工作量就太大了,后期平台数量往往只增不减呢。这个时候借助于facade class:

class shareFacade {
 
 protected $twitter; 
 protected $google; 
 protected $reddit; 
 function __construct($twitterObj,$gooleObj,$redditObj)
 {
 $this->twitter = $twitterObj;
 $this->google = $gooleObj;
 $this->reddit = $redditObj;
 } 
 function share($url,$title,$status)
 {
 $this->twitter->tweet($status, $url);
 $this->google->share($url);
 $this->reddit->reddit($url, $title);
 }
}
Copy after login

这样终端调用就可以:

$shareObj = new shareFacade($twitterObj,$gooleObj,$redditObj);
$shareObj->share('//myBlog.com/post-awsome','My greatest post','Read my greatest post ever.');
Copy after login

facade pattern的优劣势

优势

能够使你的终端调用与背后的子系统逻辑解耦,这往往发生在你的controller里,就意味着你的controller可以有更少的依赖,controller关注的更少了,从而责任和逻辑也更明确了,同时也意味着你子系统里的逻辑更改,并不会影响到你的controller里终端调用。

劣势

虽然特别有用,但是一个常见的陷阱就是,过度使用这个模式,明明可能那个时候你并不需要,这个往往注意即可。当然也有人争论说,明明我原来的代码都能用,干嘛费这个劲,那么同样是房子,你是喜欢住在精致的屋子里呢,还是说有四面墙就行了呢?

感觉facade pattern与其他的设计模式似曾相识?

认真学过我们《Laravel底层核心技术实战揭秘》这一课程的同学,可能到这里就会尤其觉得这个facade pattern好像在哪里见过?可能你会脱口而出:“这货跟之前咱们学的decorator pattern有啥区别呢?为啥不直接说成修饰者模式呢?”

确实,在“包装”逻辑方面,它们确实类似,但是:

修饰者模式(Decorator)——用来给一个Object添加、包裹上新的行为、逻辑,而不需要改动原来的代码

外观模式(facade pattern)——用来给一个或多个复杂的子系统、或者第三方库,提供统一的入口,或者说统一的终端调用方式

还是有一定差别的~

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

学习laravel的模型事件的几种用法

关于PHP的Laravel框架中使用消息队列queue及异步队列的方法分析

Laravel 5框架的模型和控制器以及视图基础流程的学习

The above is the detailed content of About the analysis of facade pattern in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!