1 | 场景:保存订单的时候,用事件监听这个动作,一旦保存订单成功,就执行相应的其他操作生成日志 |
2 |
|
3 | 1、编写事件和监听的关系,代码如下 |
4 |
|
5 | <?php |
6 |
|
7 | namespace App\Providers; |
8 |
|
9 | use Illuminate\Support\Facades\Event; |
10 |
|
11 | use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; |
12 |
|
13 |
|
14 | class EventServiceProvider extends ServiceProvider |
15 |
|
16 | { |
17 |
|
18 | /** |
19 |
|
20 | * The event listener mappings for the application. |
21 |
|
22 | * |
23 |
|
24 | * @var array |
25 |
|
26 | */ |
27 |
|
28 | protected $listen = [ |
29 |
|
30 | 'App\Events\Event' => [ |
31 |
|
32 | 'App\Listeners\EventListener', |
33 |
|
34 | ], |
35 |
|
36 | 'App\Events\PostSaved'=>[ |
37 |
|
38 | 'App\Listeners\SaveDataToCache' |
39 |
|
40 | ] |
41 |
|
42 | ]; |
43 |
|
44 |
|
45 | /** |
46 |
|
47 | * Register any events for your application. |
48 |
|
49 | * |
50 |
|
51 | * @return void |
52 |
|
53 | */ |
54 |
|
55 | public function boot() |
56 |
|
57 | { |
58 |
|
59 | parent::boot(); |
60 |
|
61 |
|
62 | // |
63 |
|
64 | } |
65 |
|
66 | } |
67 |
|
68 | 2、运行命令生成刚刚注册的事件和监听者的文件 |
69 |
|
70 | [root@iZm5eg0edzgzzaypwu5yjyZ blog]# /usr/local/php/bin/php artisan event:generate |
71 |
|
72 | Events and listeners generated successfully! |
73 |
|
74 | [root@iZm5eg0edzgzzaypwu5yjyZ blog]# |
75 |
|
76 | ps:该命令会在app/Events目录下生成PostSaved.php,在app/Listeners目录下生成SaveDataToCache.php |
77 |
|
78 | 3、编写事件内容 |
79 |
|
80 |
|
81 | <?php |
82 |
|
83 |
|
84 | namespace App\Events; |
85 |
|
86 |
|
87 | use Illuminate\Broadcasting\Channel; |
88 |
|
89 | use Illuminate\Queue\SerializesModels; |
90 |
|
91 | use Illuminate\Broadcasting\PrivateChannel; |
92 |
|
93 | use Illuminate\Broadcasting\PresenceChannel; |
94 |
|
95 | use Illuminate\Foundation\Events\Dispatchable; |
96 |
|
97 | use Illuminate\Broadcasting\InteractsWithSockets; |
98 |
|
99 | use Illuminate\Contracts\Broadcasting\ShouldBroadcast; |
100 |
|
101 | use App\Models\Order; |
102 |
|
103 | class PostSaved |
104 |
|
105 | { |
106 |
|
107 | use Dispatchable, InteractsWithSockets, SerializesModels; |
108 |
|
109 | //public $order; |
110 |
|
111 | /** |
112 |
|
113 | * Create a new event instance. |
114 |
|
115 | * |
116 |
|
117 | * @return void |
118 |
|
119 | */ |
120 |
|
121 | public function __construct(Order $order) |
122 |
|
123 | { |
124 |
|
125 | // |
126 |
|
127 | $this->order = $order; |
128 |
|
129 | } |
130 |
|
131 |
|
132 | /** |
133 |
|
134 | * Get the channels the event should broadcast on. |
135 |
|
136 | * |
137 |
|
138 | * @return \Illuminate\Broadcasting\Channel|array |
139 |
|
140 | */ |
141 |
|
142 | public function broadcastOn() |
143 |
|
144 | { |
145 |
|
146 | return new PrivateChannel('channel-name'); |
147 |
|
148 | } |
149 |
|
150 | } |
151 |
|
152 |
|
153 | 3、编写监听的内容 |
154 |
|
155 | <?php |
156 |
|
157 |
|
158 | namespace App\Listeners; |
159 |
|
160 |
|
161 | use App\Events\PostSaved; |