Laravel 的 Events 及 Observers(四)

來源:互聯網
上載者:User
我同意,模型事件非常酷,然而,有時候,你需要一些更進階的東西。

當你使用 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....      }  }

然後在 EventServiceProvider類的 boot()方法中這樣註冊它:

Book::observe(new BookObserver);

這個理的概念和前面都是相同的,沒什麼新的東西。通過觀察者,你也可以使用前面模型事件中學到的每一個單獨的概念。你可以聲明任何你想要的方法,然後只需要使用事件標示符綁定一個特定的事件。因此, creating事件是與 creating()方法相關的,以此類推。

很明顯,你可以在前置方法中終止該操作,比如說 createing()和 updating():

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

好了,下面我們來看一些模型觀察者的例子。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.