Laravel 的 Events 及 Observers(四)

WBOY
Release: 2016-06-20 12:30:26
Original
879 people have browsed it

我同意,模型事件非常酷,然而,有时候,你需要一些更高级的东西。

当你使用 Laravel 的时候,你基本上就是在使用面向对象编程,你可能需要做一些与模型事件相同的事,那就是模型观察者 — 一个模型事件的高级版本。

要使用它,你需要做的就是像下面这样声明一个新的类(可以放在一个叫做 observers的专用文件夹中):

class BookObserver {    public function creating($book)    {      // I want to create the $book book, but first...    }      public function saving($book)      {          // I want to save the $book book, but first...      }      public function saved($book)      {          // I just saved the $book book, so....      }  }
Copy after login

然后在 EventServiceProvider类的 boot()方法中这样注册它:

Book::observe(new BookObserver);
Copy after login

这个理的概念和前面都是相同的,没什么新的东西。通过观察者,你也可以使用前面模型事件中学到的每一个单独的概念。你可以声明任何你想要的方法,然后只需要使用事件标示符绑定一个特定的事件。因此, creating事件是与 creating()方法相关的,以此类推。

很明显,你可以在前置方法中终止该操作,比如说 createing()和 updating():

class BookObserver {    public function creating($book)    {      $somethingGoesWrong = true;      if($somethingGoesWrong)      {        return false;      }    }  }
Copy after login

好了,下面我们来看一些模型观察者的例子。

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!