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">'App\Events\BlogView'</span> => <span class="ot">[</span> <span class="st">'App\Listeners\BlogViewListener'</span><span class="ot">,</span> <span class="ot">],</span> <span class="ot">];</span></code>
然后项目根目录下执行如下命令
<code class="sourceCode php">php artisan event:generate</code>
该命令完成后,会分别自动在 app/Events
和app/Listensers
目录下生成 BlogView.php
和BlogViewListener.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>
其实看到这些你会发现该事件类只是注入了一个 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">'viewed_Blogs'</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">'viewed_Blogs.'</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>
注释中也已经说明了一些逻辑。
触发事件
事件和事件监听完成后,我们要做的就是实现整个监听,即触发用户打开文章事件在此我们使用和 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">'home.blog.content'</span><span class="ot">)</span>->withPost<span class="ot">(</span><span class="kw">$post</span><span class="ot">);</span> }}</code>
现在打开页面发现数据库中的`view_cache已经正常加1了,这样整个就完成了。

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
