Maison > développement back-end > tutoriel php > Laravel 5.1 事件、事件监听的容易应用

Laravel 5.1 事件、事件监听的容易应用

WBOY
Libérer: 2016-06-13 12:27:44
original
859 Les gens l'ont consulté

Laravel 5.1 事件、事件监听的简单应用

?

有时候当我们单纯的看 Laravel 手册的时候会有一些疑惑,比如说系统服务下的授权和事件,这些功能服务的应用场景是什么,其实如果没有经历过一定的开发经验有这些疑惑是很正常的事情,但是当我们在工作中多加思考会发现有时候这些服务其实我们一直都见过。下面就事件、事件监听举一个很简单的例子你就会发现。

? 这个例子是关于文章的浏览数的实现,当用户查看文章的时候文章的浏览数会增加1,用户查看文章就是一个事件,有了事件,就需要一个事件监听器,对监听的事件发生后执行相应的操作(文章浏览数加1),其实这种监听机制在 Laravel 中是通过观察者模式实现的.

注册事件以及监听器

首先我们需要在 app/Providers/目录下的EventServiceProvider.php中注册事件监听器映射关系,如下:

<code class="sourceCode php"><span class="kw">protected</span> <span class="kw">$listen</span> = <span class="ot">[</span>        <span class="st">&#39;App\Events\BlogView&#39;</span> => <span class="ot">[</span>            <span class="st">&#39;App\Listeners\BlogViewListener&#39;</span><span class="ot">,</span>        <span class="ot">],</span>    <span class="ot">];</span></code>
Copier après la connexion

然后项目根目录下执行如下命令

<code class="sourceCode php">php artisan event:generate</code>
Copier après la connexion

该命令完成后,会分别自动在 app/Eventsapp/Listensers目录下生成 BlogView.phpBlogViewListener.php文件。

定义事件

<code class="sourceCode php"><span class="kw"><?php</span><span class="kw">namespace</span> App\Events<span class="ot">;</span><span class="kw">use</span> App\Events\Event<span class="ot">;</span><span class="kw">use</span> App\Post<span class="ot">;</span><span class="kw">use</span> Illuminate\Queue\SerializesModels<span class="ot">;</span><span class="kw">use</span> Illuminate\Contracts\Broadcasting\ShouldBroadcast<span class="ot">;</span><span class="kw">class</span> BlogView <span class="kw">extends</span> Event{    <span class="kw">use</span> SerializesModels<span class="ot">;</span>    <span class="co">/**</span><span class="co">     * Create a new event instance.</span><span class="co">     *</span><span class="co">     * </span><span class="kw">@return</span><span class="co"> void</span><span class="co">     */</span>    <span class="kw">public</span> <span class="kw">function</span> <span class="fu">__construct</span><span class="ot">(</span>Post <span class="kw">$post</span><span class="ot">)</span>    {        <span class="kw">$this</span>->post = <span class="kw">$post</span><span class="ot">;</span>    }    <span class="co">/**</span><span class="co">     * Get the channels the event should be broadcast on.</span><span class="co">     *</span><span class="co">     * </span><span class="kw">@return</span><span class="co"> array</span><span class="co">     */</span>    <span class="kw">public</span> <span class="kw">function</span> broadcastOn<span class="ot">()</span>    {        <span class="kw">return</span> <span class="ot">[];</span>    }}</code>
Copier après la connexion

其实看到这些你会发现该事件类只是注入了一个 Post实例罢了,并没有包含多余的逻辑。

定义监听器

事件监听器在handle方法中接收事件实例,event:generate命令将会自动在handle方法中导入合适的事件类和类型提示事件。在handle方法内,你可以执行任何需要的逻辑以响应事件,我们的代码实现如下:

<code class="sourceCode php"><span class="kw"><?php</span><span class="kw">namespace</span> App\Listeners<span class="ot">;</span><span class="kw">use</span> App\Events\BlogView<span class="ot">;</span><span class="kw">use</span> Illuminate\Queue\InteractsWithQueue<span class="ot">;</span><span class="kw">use</span> Illuminate\Contracts\Queue\ShouldQueue<span class="ot">;</span><span class="kw">use</span> Illuminate\Session\Store<span class="ot">;</span><span class="kw">class</span> BlogViewListener{    <span class="kw">protected</span> <span class="kw">$session</span><span class="ot">;</span>    <span class="co">/**</span><span class="co">     * Create the event listener.</span><span class="co">     *</span><span class="co">     * </span><span class="kw">@return</span><span class="co"> void</span><span class="co">     */</span>    <span class="kw">public</span> <span class="kw">function</span> <span class="fu">__construct</span><span class="ot">(</span>Store <span class="kw">$session</span><span class="ot">)</span>    {        <span class="kw">$this</span>->session = <span class="kw">$session</span><span class="ot">;</span>    }    <span class="co">/**</span><span class="co">     * Handle the event.</span><span class="co">     *</span><span class="co">     * </span><span class="kw">@param</span><span class="co">  </span><span class="kw">BlogView</span><span class="co">  $event</span><span class="co">     * </span><span class="kw">@return</span><span class="co"> void</span><span class="co">     */</span>    <span class="kw">public</span> <span class="kw">function</span> handle<span class="ot">(</span>BlogView <span class="kw">$event</span><span class="ot">)</span>    {        <span class="kw">$post</span> = <span class="kw">$event</span>->post<span class="ot">;</span>        <span class="co">//先进行判断是否已经查看过</span>        <span class="kw">if</span> <span class="ot">(</span>!<span class="kw">$this</span>->hasViewedBlog<span class="ot">(</span><span class="kw">$post</span><span class="ot">))</span> {            <span class="co">//保存到数据库</span>            <span class="kw">$post</span>->view_cache = <span class="kw">$post</span>->view_cache + <span class="dv">1</span><span class="ot">;</span>            <span class="kw">$post</span>->save<span class="ot">();</span>            <span class="co">//看过之后将保存到 Session </span>            <span class="kw">$this</span>->storeViewedBlog<span class="ot">(</span><span class="kw">$post</span><span class="ot">);</span>        }    }    <span class="kw">protected</span> <span class="kw">function</span> hasViewedBlog<span class="ot">(</span><span class="kw">$post</span><span class="ot">)</span>    {        <span class="kw">return</span> <span class="fu">array_key_exists</span><span class="ot">(</span><span class="kw">$post</span>->id<span class="ot">,</span> <span class="kw">$this</span>->getViewedBlogs<span class="ot">());</span>    }    <span class="kw">protected</span> <span class="kw">function</span> getViewedBlogs<span class="ot">()</span>    {        <span class="kw">return</span> <span class="kw">$this</span>->session->get<span class="ot">(</span><span class="st">&#39;viewed_Blogs&#39;</span><span class="ot">,</span> <span class="ot">[]);</span>    }    <span class="kw">protected</span> <span class="kw">function</span> storeViewedBlog<span class="ot">(</span><span class="kw">$post</span><span class="ot">)</span>    {        <span class="kw">$key</span> = <span class="st">&#39;viewed_Blogs.&#39;</span>.<span class="kw">$post</span>->id<span class="ot">;</span>        <span class="kw">$this</span>->session->put<span class="ot">(</span><span class="kw">$key</span><span class="ot">,</span> <span class="fu">time</span><span class="ot">());</span>    }}</code>
Copier après la connexion

注释中也已经说明了一些逻辑。

触发事件

事件和事件监听完成后,我们要做的就是实现整个监听,即触发用户打开文章事件在此我们使用和 Event提供的 fire方法,如下:

<code class="sourceCode php"><span class="kw"><?php</span><span class="kw">namespace</span> App\Http\Controllers<span class="ot">;</span><span class="kw">use</span> Illuminate\Http\Request<span class="ot">;</span><span class="kw">use</span> App\Post<span class="ot">;</span><span class="kw">use</span> Illuminate\Support\Facades\Event<span class="ot">;</span><span class="kw">use</span> App\Http\Requests<span class="ot">;</span><span class="kw">use</span> App\Events\BlogView<span class="ot">;</span><span class="kw">use</span> App\Http\Controllers\Controller<span class="ot">;</span><span class="kw">class</span> BlogController <span class="kw">extends</span> Controller{       <span class="kw">public</span> <span class="kw">function</span> showPost<span class="ot">(</span><span class="kw">$slug</span><span class="ot">)</span>    {        <span class="kw">$post</span> = Post::whereSlug<span class="ot">(</span><span class="kw">$slug</span><span class="ot">)</span>->firstOrFail<span class="ot">();</span>        Event::fire<span class="ot">(</span><span class="kw">new</span> BlogView<span class="ot">(</span><span class="kw">$post</span><span class="ot">));</span>        <span class="kw">return</span> view<span class="ot">(</span><span class="st">&#39;home.blog.content&#39;</span><span class="ot">)</span>->withPost<span class="ot">(</span><span class="kw">$post</span><span class="ot">);</span>    }}</code>
Copier après la connexion

现在打开页面发现数据库中的`view_cache已经正常加1了,这样整个就完成了。

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal