浅谈对laravel5.6事件的理解

  • 内容
  • 评论
  • 相关

一楼喂猫。

最近公司用到laravel做项目,所以在这里简单说一下laravel中的事件的用法及楼主的理解,当做个笔记。

前提条件:你已经有一个有效的路由,并且指向了控制器,最重要是能跑。

事件是什么东西?按照官方文档的例子,我觉得可以做这样一个比喻。假如将你一天的行为定义为一个业务逻辑,那么过程中某些关键的动作都可以定义为一个事件,比如下班回家开门和关门的两个动作,就可以看成是两个事件。

监听器又是什么东西?按照官方文档的举例,应该就是实现事件的逻辑,也就是如何去完成自己定义的事件。

下面例子:

一、

如官方所说,通过laravel自带的EventServiceProvider注册事件及其监听器。

在app/Providers/EventServiceProvider中的$listen添加事件类名及监听器类名如:

protected $listen = [
  // test event
  'App\EventService\Events\TestEvent' = [
    'App\EventService\Listeners\TestListener'
  ]
];

之后执行php artisan event:generate,App\EventService\Events目录下会分别生成事件(TestEvent.php)和对应的监听器(TestListener.php)。

自动生成的TestEvent:

namespace App\EventService\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class TestEvent
{
  use Dispatchable, InteractsWithSockets, SerializesModels;

  public function __construct()
  {

  }

  public function broadcastOn()
  {
    return new PrivateChannel('channel-name');
  }
}

自动生成的TestListener:

namespace App\EventService\Listeners;

use App\EventService\Events\TestEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class TestListener
{
  public function __construct()
  {
    //
  }

  /**
  * Handle the event.
  *
  * @param TestEvent $event
  * @return void
  */
  public function handle(TestEvent $event)
  {
    //此处写逻辑
  }
}

分发事件(应用事件):

在你需要应用事件的地方,使用laravel提供的辅助函数event().官方举例是写在Controller中,具体应用在什么地方这个看自己的项目规范,楼主一般写在逻辑层。

namespace App\Http\Controllers;

use App\EventService\Events\TestEvent;
use App\Http\Controllers\Controller;
class OrderController extends Controller {
  public function index() {
    // 事件应用
    event(new TestEvent());
  }
}

若是需要使用队列的话,可以在监听器里面设置:

class TestListener implements ShouldQueue

二、

事件订阅者:

我没能理解官方的解释是啥意思,但是看例子后,应该就是在这个subscribe的监听器中,将多个事件的监听器绑写在一起。

在监听器中新建一个TestSubscriber.php

namespace App\EventService\Listeners;
class TestSubscriber {

// 监听逻辑1
public function onTestFirst($event) {}

// 监听逻辑2
public function onTestSecond($event) {}

/**
* 为订阅者注册监听器.
* @param Illuminate\Events\Dispatcher $events
*/
public function subscribe($events) {
$events->listen(
'App\EventService\Events\TestEventFirst',
'App\EventService\Listeners\UserEventSubscriber@onTestFirst'
);
$events->listen(
'App\EventService\Events\TestEventSecond',
'App\EventService\Listeners\UserEventSubscriber@onTestSecond'
);
}
}

namespace App\EventService\Listeners;
class TestSubscriber {

  // 监听逻辑1
  public function onTestFirst($event) {}

  // 监听逻辑2
  public function onTestSecond($event) {}

  /**
  * 为订阅者注册监听器.
  * @param Illuminate\Events\Dispatcher $events
  */
  public function subscribe($events) {
    $events->listen(
      'App\EventService\Events\TestEventFirst',
      'App\EventService\Listeners\UserEventSubscriber@onTestFirst'
    );
    $events->listen(
      'App\EventService\Events\TestEventSecond',
      'App\EventService\Listeners\UserEventSubscriber@onTestSecond'
    );
  }
}

注册事件订阅者

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvide extends ServiceProvider
{
  protected $listen = [
    //
  ];

  //注册订阅者
  protected $subscribe = [
    'App\EventService\Listeners\TestSubscriber',
  ];
}

评论

14条评论
  1. Gravatar 头像

    BURGERdype 回复

    used car dealerships

    Loan approval * Video
    Loan approval Loan approval Online Personal Loan Approval in 1 Hour Occasionally you won’t be able to wait till pa day on the 25 th of 30 th day of the month. Possibly you have a lot of bills that really need to be paid such as a car payment. perhaps you have a trip planned to go to the coast or just require a bit of cash to take your spouse for a special date and your pay day is just too far. Cash loans from Loan lenders make it possible for you to get money in your bank ...
    The post Loan approval * Video appeared first on Bedroom .

    Alaska Finance
    BONUS FREE DOFOLLOW Links SITE

    http://500781ed42596.bwebs.com/
    http://masterbeer.com.ua/blog/malye-pivovarni-chehii/#comment_51103/
    http://www.raiderfans.net/forum/member.php?353152-IZRAELdern
    http://handleyourbiz.blogspot.com/feeds/posts/default/
    http://myftp.vip/index.php?url=archives/3-5G.html&serendipity=true

    http://www.meerkatmetals.com/2017/02/05/hello-world/?unapproved=200&moderation-hash=5d7faa300afcc23aa2f80b50b33f23ff#comment-200
    http://alandsblandning.com/2014/10/10/entry-8/?unapproved=23294&moderation-hash=5eb30151d7fbdbe47f621d818858d6e3#comment-23294
    http://candidati.unica.it/mariadelzompo/profilo/curriculum-vitae/?unapproved=9624&moderation-hash=84630f0b0602f25f03eabaed7c4a884d#comment-9624
    http://alvitech.co.in/gsm-remote-controller-alarm-system-alv-gsm-d-x/?unapproved=41981&moderation-hash=48c9574eeec3e1950c9b019e2a1378be#comment-41981
    http://tontonhausu.cocolog-nifty.com/tonton/2006/07/post_8b67.html

    评论正在审核中...
  2. Gravatar 头像

    download minecraft 回复

    Thanks for some other wonderful article. Where else may just
    anybody get that type of information in such a perfect
    way of writing? I've a presentation next week, and I'm on the
    look for such information.

  3. Gravatar 头像

    minecraft free download 回复

    I every time used to study piece of writing in news papers but now as I am a user of net
    so from now I am using net for content, thanks to web.

  4. Gravatar 头像

    download minecraft free 回复

    Hi, constantly i used to check blog posts here in the early hours in the morning,
    because i love to gain knowledge of more and more.

  5. Gravatar 头像

    gamefly 回复

    Fascinating blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple tweeks would really make my
    blog stand out. Please let me know where you got your design. Thanks

发表评论

电子邮件地址不会被公开。 必填项已用*标注