?
Sometimes when we simply read the Laravel
manual, we will have some doubts, such as authorization and events under system services, and what are the application scenarios of these functional services. In fact, if you have not experienced certain Development experienceIt is normal to have these doubts, but when we think more about it at work, we will find that sometimes we have actually seen these services before. Below is a very simple example of events and event monitoring and you will find out.
? This example is about the implementation of the number of views of the article. When the user views the article, the number of views of the article will increase by 1. Viewing the article by the user is an event. With an event, an event listener is needed to monitor the event. After the occurrence, perform the corresponding operation (increase the number of article views by 1). In fact, this monitoring mechanism is implemented in Laravel
through the observer mode.
Register events and listeners
First we need to app/Providers/ Register the event listener
mapping relationship in the
EventServiceProvider.php under the directory, as follows:
<code><span>protected</span><span>$listen</span> = <span>[</span><span>'App\Events\BlogView'</span> => <span>[</span><span>'App\Listeners\BlogViewListener'</span><span>,</span><span>],</span><span>];</span></code>
Then execute the following command in the project root directory
<code>php artisan event:generate</code>
After the command is completed, it will automatically be in app respectively The
BlogView.php and
BlogViewListener.php files are generated in the /Events
and app/Listensers
directories.
Define events
<code><span><?php </span><span>namespace</span> App\Events<span>;</span><span>use</span> App\Events\Event<span>;</span><span>use</span> App\Post<span>;</span><span>use</span> Illuminate\Queue\SerializesModels<span>;</span><span>use</span> Illuminate\Contracts\Broadcasting\ShouldBroadcast<span>;</span><span>class</span> BlogView <span>extends</span> Event { <span>use</span> SerializesModels<span>;</span><span>/**</span><span> * Create a new event instance.</span><span> *</span><span> * </span><span>@return</span><span> void</span><span> */</span><span>public</span><span>function</span><span>__construct</span><span>(</span>Post <span>$post</span><span>)</span> { <span>$this</span>->post = <span>$post</span><span>;</span> } <span>/**</span><span> * Get the channels the event should be broadcast on.</span><span> *</span><span> * </span><span>@return</span><span> array</span><span> */</span><span>public</span><span>function</span> broadcastOn<span>()</span> { <span>return</span><span>[];</span> } }</span></code>
In fact, when you see this, you will find that the event class just injects a Post
instance and does not contain redundant logic.
Define the listener
The event listener receives the event instance in the handle
method. The event:generate command will automatically import the appropriate event class and type hint event in the handle method. Within the handle
method, you can perform any required logic in response to the event. Our code is implemented as follows:
<code><span><?php </span><span>namespace</span> App\Listeners<span>;</span><span>use</span> App\Events\BlogView<span>;</span><span>use</span> Illuminate\Queue\InteractsWithQueue<span>;</span><span>use</span> Illuminate\Contracts\Queue\ShouldQueue<span>;</span><span>use</span> Illuminate\Session\Store<span>;</span><span>class</span> BlogViewListener { <span>protected</span><span>$session</span><span>;</span><span>/**</span><span> * Create the event listener.</span><span> *</span><span> * </span><span>@return</span><span> void</span><span> */</span><span>public</span><span>function</span><span>__construct</span><span>(</span>Store <span>$session</span><span>)</span> { <span>$this</span>->session = <span>$session</span><span>;</span> } <span>/**</span><span> * Handle the event.</span><span> *</span><span> * </span><span>@param</span><span>BlogView</span><span> $event</span><span> * </span><span>@return</span><span> void</span><span> */</span><span>public</span><span>function</span> handle<span>(</span>BlogView <span>$event</span><span>)</span> { <span>$post</span> = <span>$event</span>->post<span>;</span><span>//先进行判断是否已经查看过</span><span>if</span><span>(</span>!<span>$this</span>->hasViewedBlog<span>(</span><span>$post</span><span>))</span> { <span>//保存到数据库</span><span>$post</span>->view_cache = <span>$post</span>->view_cache + <span>1</span><span>;</span><span>$post</span>->save<span>();</span><span>//看过之后将保存到 Session </span><span>$this</span>->storeViewedBlog<span>(</span><span>$post</span><span>);</span> } } <span>protected</span><span>function</span> hasViewedBlog<span>(</span><span>$post</span><span>)</span> { <span>return</span><span>array_key_exists</span><span>(</span><span>$post</span>->id<span>,</span><span>$this</span>->getViewedBlogs<span>());</span> } <span>protected</span><span>function</span> getViewedBlogs<span>()</span> { <span>return</span><span>$this</span>->session->get<span>(</span><span>'viewed_Blogs'</span><span>,</span><span>[]);</span> } <span>protected</span><span>function</span> storeViewedBlog<span>(</span><span>$post</span><span>)</span> { <span>$key</span> = <span>'viewed_Blogs.'</span>.<span>$post</span>->id<span>;</span><span>$this</span>->session->put<span>(</span><span>$key</span><span>,</span><span>time</span><span>());</span> } }</span></code>
Some logic has also been explained in the comments.
Trigger event
After the event and event monitoring are completed, what we have to do is to implement the entire monitoring, that is, to trigger the user to open the article event. Here we use the fire
method provided by Event
, as follows:
<code><span><?php </span><span>namespace</span> App\Http\Controllers<span>;</span><span>use</span> Illuminate\Http\Request<span>;</span><span>use</span> App\Post<span>;</span><span>use</span> Illuminate\Support\Facades\Event<span>;</span><span>use</span> App\Http\Requests<span>;</span><span>use</span> App\Events\BlogView<span>;</span><span>use</span> App\Http\Controllers\Controller<span>;</span><span>class</span> BlogController <span>extends</span> Controller { <span>public</span><span>function</span> showPost<span>(</span><span>$slug</span><span>)</span> { <span>$post</span> = Post::whereSlug<span>(</span><span>$slug</span><span>)</span>->firstOrFail<span>();</span> Event::fire<span>(</span><span>new</span> BlogView<span>(</span><span>$post</span><span>));</span><span>return</span> view<span>(</span><span>'home.blog.content'</span><span>)</span>->withPost<span>(</span><span>$post</span><span>);</span> } }</span></code>
Now open the page and find that the `view_cache in the database has been increased by 1 normally, so the whole thing is complete.
The above introduces the simple application of Laravel 51 events and event monitoring, including development experience and mapping relationships. I hope it will be helpful to friends who are interested in PHP tutorials.

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor
