Home Backend Development PHP Tutorial Laravel 的 Events 及 Observers(五)

Laravel 的 Events 及 Observers(五)

Jun 20, 2016 pm 12:30 PM

首先,我们为你展示如何通过模型观察者实现前面模式事件中的第一个例子。

在 app/Observers文件夹中创建  WelcomeUserObserver.php文件,并加入下面的代码:

<?php  namespace App\Observers;  class WelcomeUserObserver {    public function created($user){      Mail::send('emails.welcome', ['user' => $user], function($message) use ($user)      {          $message->to($user->email, $user->first_name . ' ' . $user->last_name)->subject('Welcome to My Awesome App, '.$user->first_name.'!');      });    }  }
Copy after login

然后在 EventServiceProvider的 boot()方法中注册该观察者:

/**   * Register any other events for your application.   *   * @param  \Illuminate\Contracts\Events\Dispatcher  $events   * @return void   */  public function boot(DispatcherContract $events)  {      parent::boot($events);      User::observe(new WelcomeUserObserver);  }
Copy after login

这样就 OK 了!现在你的观察者已经与模型关联起来了。

下面我们假设另一种情况。图书管理员对代码提出了一些新的需求:

  • 当添加一个新的作者的时候,每一个用户都收到一条通知
  • 每次添加/删除作者的时候,都发送一封邮件
  • 最后,每次删除一本书的时候,图书管理员都要知道数据库中有多少作者是没有与相关的图书的

好了,下面我们就开始吧。我们需要三个单独的类(请记住我们的 单一职责原则): CustomerNewAuthorObserver、 LibrarianAuthorObserver、 AuthorsWithoutBooksObservers。

注意:你可以按自己喜欢的方式命名这些类,我们这里只是选择比较容易与所选行为关联起来的名称。

下面我们分别来创建三个类:

<?php  // file: app/Observers/CustomerNewAuthorObserver  namespace App\Observers;  class CustomerNewAuthorObserver {    public function created($author)    {    }  }<?php  // file: app/Observers/LibrarianAuthorObserver  namespace App\Observers;  class LibrarianAuthorObserver {    public function created($author)    {    }    public function deleted($author)    {    }  }<?php  // file: app/Observers/AuthorsWithoutBooksObservers  namespace App\Observers;  class AuthorsWithoutBooksObservers {    public function deleted($author)    {    }  }
Copy after login

好了,现在应该添加一些逻辑了,首先为 CustomerNewAuthorObserver添加:

<?php  // file: app/Observers/CustomerNewAuthorObserver  namespace App\Observers;  class CustomerNewAuthorObserver {    public function created($author)    {      // getting all users...      $users = \App\User::all();      foreach($users as $user)      {        Mail::send('emails.created_author_customer', ['author' => $author], function($message) use ($user)        {            $message->to($user->email, $user->first_name . ' ' . $user->last_name)->subject('New Author Added!');        });      }    }  }
Copy after login

注意:我知道这是一种非常简单粗暴的方法,这里只是为了实现上面的目的。实际情况中可以使用 邮件队列。

<?php  // file: app/Observers/LibrarianAuthorObserver  namespace App\Observers;  class LibrarianAuthorObserver {    public function created($author) {      Mail::send('emails.created_author_librarian', ['author' => $author], function($message) use ($author)      {          $message->to('librarian@awesomelibrary.com', 'The Librarian')->subject('New Author: ' . $author->first_name . ' ' . $author->last_name);      });    }    public function deleted($author) {      Mail::send('emails.deleted_author_librarian', ['author' => $author], function($message) use ($author)      {          $message->to('librarian@awesomelibrary.com', 'The Librarian')->subject('New Author: ' . $author->first_name . ' ' . $author->last_name);      });    }  }
Copy after login

最后:

<?php  // file: app/Observers/AuthorsWithoutBooksObservers  namespace App\Observers;  class AuthorsWithoutBooksObservers {    public function deleted($author) {      $authorsWithoutBooks = \App\Author::has('books', '=', 0)->get();      if(count($authorsWithoutBooks) > 0){        Mail::send('emails.author_without_books_librarian', ['authorsWithoutBooks' => $authorsWithoutBooks], function($message)        {            $message->to('librarian@awesomelibrary.com', 'The Librarian')->subject('Authors without Books! A check is required!');        });      }    }  }
Copy after login

注意:就像前面提过的,我们假定你已经了解了 Laravel 发送邮件的基本知识,没有的话可以到官网学习下相关知识。

到这里并没有结束。你可以在大量的案例和场景中使用 Laravel 的模型事件和模型观察者。举个例子,假设你写博客,你希望每次发布一篇新文章或者更新一篇原有文章的时候,都更新一些站点地图,这时就可以用到观察者。再比如,当添加新书的时候,记录一些东西,也可以用到观察者。

该篇属于专题:《 Laravel 的 Events(事件) 及 Observers(观察者)》

  • 下一篇:《 Laravel 的 Events 及 Observers(六) — 总结》
  • 上一篇:《 Laravel 的 Events 及 Observers(四) — 模型观察者》
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

See all articles