Home  >  Article  >  Backend Development  >  Detailed explanation of the use of facade pattern in PHP

Detailed explanation of the use of facade pattern in PHP

php中世界最好的语言
php中世界最好的语言Original
2018-05-19 10:35:081172browse

This time I will bring you a detailed explanation of the facade pattern in PHP. Facade pattern usage in PHP. What are the notes when using the facade pattern in PHP? The following is a practical case. Let’s take a look. take a look.

About the translation of the word facade

The word facade originally refers to the surface and appearance of a building. In architecture, it is translated as the term "facade". The 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 it is in the real world or the programming world, the purpose of facade (appearance) It is to "put on" a beautiful and attractive appearance, or mask, for something that may have been ugly and messy. 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 a unified entry interface for one or more subsystems ( 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 such 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) {
  ...
 }
}

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

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

Then our customers, It can be easily called like this:

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

Example 2: A bad third-party mail class

Suppose you have to use the following one that looks terrible Third-party email classes, especially each method name in it, you have to stay for a few seconds to understand:

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());
 }
}

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();
 }
}

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();

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();

Example 3: Complete one The complex process of commodity trading

Suppose that a commodity trading link 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();
}

可以看到,一个流程呢包含了很多步骤,涉及到了很多Object,一旦类似环节要用在多个地方,可能就会导致问题,所以可以先创建一个外观类:

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();
 }
}

这样呢,我们的终端调用就可以两行解决:

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

示例四:往多个社交媒体同步消息的流程

// 发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);
 }
}

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

这样终端调用就可以:

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

facade pattern的优劣势

优势

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

劣势

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

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

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

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

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

php与js打开本地exe应用程序传递参数步骤详解

如何实现php删除固定路径下文件夹与文件

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

Statement:
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