<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Wisdom Ebong</title>
    <description>The latest articles on DEV Community by Wisdom Ebong (@webong).</description>
    <link>https://dev.to/webong</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F46164%2Fbbf5b751-093b-49e7-a985-ea955837aaa0.jpg</url>
      <title>DEV Community: Wisdom Ebong</title>
      <link>https://dev.to/webong</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/webong"/>
    <language>en</language>
    <item>
      <title>Execute an action after Laravel returns response</title>
      <dc:creator>Wisdom Ebong</dc:creator>
      <pubDate>Thu, 13 Feb 2020 15:28:54 +0000</pubDate>
      <link>https://dev.to/webong/execute-an-action-after-laravel-returns-response-4pjc</link>
      <guid>https://dev.to/webong/execute-an-action-after-laravel-returns-response-4pjc</guid>
      <description>&lt;p&gt;In this article, we want to explore the various ways we can execute small tasks or actions in laravel after a response is sent. You will see how these tasks are processed after the application responds to an incoming request. &lt;/p&gt;

&lt;p&gt;Let’s take a peep at the entry point for all requests to a Laravel application, which is the &lt;code&gt;public/index.php&lt;/code&gt; file. We’re only interested in the part where the request is handled through the kernel and a response is sent back to the client (e.g browser).&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// public/index.php
$kernel = $app-&amp;gt;make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel-&amp;gt;handle(
    $request = Illuminate\Http\Request::capture()
);

$response-&amp;gt;send();

$kernel-&amp;gt;terminate($request, $response);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;An Http kernel instance is resolved from the laravel container and is used to handle the incoming request, and then returns a response. This response is sent back to the client, by calling the &lt;code&gt;$response→send()&lt;/code&gt; method on the response variable gotten from handling the request. The &lt;code&gt;send&lt;/code&gt; method outputs the content and sends defined headers for the response, it then tries to close the output buffering by ending the open connection with the client. In a case PHP FPM is used, the &lt;code&gt;fastcgi_finish_request&lt;/code&gt; is used to close the connection.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;fastcgi_finish_request&lt;/code&gt; function flushes all response data to the client and finishes the request. This allows for time-consuming tasks to be performed without leaving the connection to the client open. Read more &lt;a href="https://www.php.net/manual/en/function.fastcgi-finish-request.php"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Just after the &lt;code&gt;$response→send()&lt;/code&gt; line, we have the &lt;code&gt;$kernel→terminate($request, $response)&lt;/code&gt; line next. We know the former sends a response, but what about that of the later.  The latter expression seems self-explaining, indicating the application Http kernel is terminating the request and response.&lt;/p&gt;

&lt;p&gt;After a response has been sent and the client connection closed, the PHP process is still alive to continue execution. In this case, the application Http kernel &lt;code&gt;terminate&lt;/code&gt; method can be used to run little tasks. To run such little task or action, we can achieve them using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Terminable Middleware&lt;/li&gt;
&lt;li&gt;Terminating Callbacks
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php
    public function terminate($request, $response)
    {
        $this-&amp;gt;terminateMiddleware($request, $response);
        $this-&amp;gt;app-&amp;gt;terminate();
    } 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;The above code snippet happens to be the content of the kernel &lt;code&gt;terminate&lt;/code&gt; method. The first line calls the method &lt;code&gt;terminateMiddleware&lt;/code&gt; on the application Http kernel, and the second calls the &lt;code&gt;terminate&lt;/code&gt; method on the application container, which runs through all the terminating callbacks and execute them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Terminable Middlewares
&lt;/h2&gt;

&lt;p&gt;In laravel, we can define middlewares to intercept incoming requests and perform little tasks before reaching the main controller logic. This middleware class usually have a &lt;code&gt;handle&lt;/code&gt; method to run the task. We can also define a &lt;code&gt;terminate&lt;/code&gt; method on this middleware class, this method will perform little tasks after the response has been sent to the client. A middleware class with the &lt;code&gt;terminate&lt;/code&gt; method can be described as a Terminable Middleware. &lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Middleware;

use Closure;

class AfterResponseMiddleware
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Perform tasks after response as been sent to the client
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Remember the method &lt;code&gt;terminateMiddleware&lt;/code&gt; we found being used in the application Http kernel &lt;code&gt;terminate&lt;/code&gt; method. This method is what calls the terminate method on any terminable middleware.&lt;/p&gt;

&lt;p&gt;So in what case would one need to use a terminable middleware: Activity logging, Request logging and Session tracking.&lt;/p&gt;

&lt;h2&gt;
  
  
  Terminating Callbacks
&lt;/h2&gt;

&lt;p&gt;Terminating callbacks are executed just after all terminable middlewares have been executed. These callbacks are functions registered to the laravel application. The snippet below, shows how to register a terminating callback:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;App::terminating(function () {
});

app()-&amp;gt;terminating(function () {

});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;From the above code block, we can observe the use of a &lt;code&gt;terminating&lt;/code&gt; method to register the callback function. This terminating &lt;code&gt;method&lt;/code&gt; also exists in the application container. When the &lt;code&gt;terminate&lt;/code&gt; method is called after the terminable middleware execution, all the terminating callbacks are then executed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  foreach ($this-&amp;gt;terminatingCallbacks as $terminating) {
      $this-&amp;gt;call($terminating);
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;A pretty much use case for a terminating callback is reporting on guzzle requests made during an Http request in laravel. Also, &lt;a href="https://twitter.com/themsaid"&gt;Mohamed Said&lt;/a&gt; contributed a new method that allows a job to dispatch after the response is sent back to the client, he wrote about this on his blog &lt;a href="https://divinglaravel.com/running-a-task-after-the-response-is-sent"&gt;here&lt;/a&gt;. This is needed to dispatch a short job instantly instead of sending it to the regular queue system.&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ShortInstantJob::dispatchAfterResponse();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;dispatchAfterResponse&lt;/code&gt; attaches the Job class as a terminating callback to the laravel application which is then executed when the application &lt;code&gt;terminate&lt;/code&gt; is called.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Right here, we have seen the possible ways there is to execute actions after a response is sent in laravel and how this is achieved. Note that the kind of actions or tasks we want to execute after returning a response are meant to be a short-lived process.&lt;/p&gt;

</description>
      <category>php</category>
      <category>laravel</category>
    </item>
    <item>
      <title>Using Asynchronous Processes in PHP.</title>
      <dc:creator>Wisdom Ebong</dc:creator>
      <pubDate>Sat, 08 Feb 2020 08:33:38 +0000</pubDate>
      <link>https://dev.to/webong/using-asynchronous-processes-in-php-7io</link>
      <guid>https://dev.to/webong/using-asynchronous-processes-in-php-7io</guid>
      <description>&lt;p&gt;For most programs written in PHP, its sole purpose is to execute a simple process consisting of multiple tasks, where the tasks must be executed in sequence such as data processing. We always have to tolerate the stop and wait aspect of synchronous programming. The synchronous style of code execution is referred to as blocking, this implies that tasks will be executed one by one. So what if we want to run tasks without them blocking each other, that means we need to have a non-blocking process? This approach would require applying asynchronous programming approaches in PHP, here tasks will be executed without depending on of each other. &lt;/p&gt;

&lt;p&gt;A common approach to achieve a non-blocking execution in PHP is to implement queue processing. Tasks are persisted to a transport system e.g MySQL, Redis, Amazon SQS e.t.c, which is retrieved by a background worker and executed accordingly, thereby not blocking the main process in which it was created. A laravel application provides a queue mechanism that allows tasks in this case called jobs to be deferred for to a later time for processing.&lt;/p&gt;

&lt;p&gt;Another approach would be to run all defined tasks in parallel. What we get out of this approach is that a particular task is done it can return control back to the main process immediately with a promise to execute code and notify us about the result later(e.g. callback). One might see little use case for the parallel processing approach; example use case could be performing image processing and making a get request to some external service. &lt;/p&gt;

&lt;p&gt;Let’s see the difference between synchronous and asynchronous (parallel) process in PHP using a very simple use case.&lt;/p&gt;

&lt;p&gt;Synchronous code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;  &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
     &lt;span class="nv"&gt;$output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$i&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
     &lt;span class="k"&gt;echo&lt;/span&gt; &lt;span class="nv"&gt;$output&lt;/span&gt; &lt;span class="mf"&gt;.&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Asynchronous code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;    &lt;span class="kn"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Spatie\Async\Pool&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$pool&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Pool&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$pool&lt;/span&gt;&lt;span class="p"&gt;[]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;async&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
           &lt;span class="nv"&gt;$output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$i&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
           &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$output&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$output&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
           &lt;span class="k"&gt;echo&lt;/span&gt; &lt;span class="nv"&gt;$output&lt;/span&gt; &lt;span class="mf"&gt;.&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;});&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="nf"&gt;await&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$pool&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we execute the first code we will get the output values in this order:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;2
4
6
8
10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Retrying the execution, we will get the output in this same sequence above … hence each multiplication operation waits to execute before the next one. Next, running the second code block, let’s see what we get.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;6
10
2
8
4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Retrying the execution for the second time:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;2
6
4
10
8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One process happens to produce two different results. This exactly is what we get for utilising the asynchronous approach … our little tasks can be executed in a fashion they don’t block each other. Each multiplication task executes independently, some faster than others hence the disorderliness in the output. Also, notice our async function as a then method attached to it, this method is responsible for taking back control and it accepts a callback function as its parameter which can now perform extra operations with the received output.&lt;/p&gt;

&lt;p&gt;The folks at Spatie made this nice &lt;code&gt;spatie/async&lt;/code&gt; package, which helps in performing tasks in parallel. You can install the package via composer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require spatie/async
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The package provides a neat way to interact with the tasks created, that are to be executed in parallel. The Event Listeners on the tasks are described below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Performing another operation when the task is done as the callback is achievable with its &lt;code&gt;then&lt;/code&gt; method.&lt;/li&gt;
&lt;li&gt;Error handling is easier to control when a particular task throws an exception using the &lt;code&gt;catch&lt;/code&gt; method.&lt;/li&gt;
&lt;li&gt;Take for instance a task does not complete its operation, a &lt;code&gt;timeout&lt;/code&gt; method allows one to handle such a scenario.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The event listeners are hooked to a task as shown below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;    &lt;span class="nv"&gt;$pool&lt;/span&gt;
        &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Task to be performed in a Parallel process&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
        &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$output&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// On success, `$output` is returned by the process or callable you passed to           the queue.&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
        &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$exception&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// When an exception is thrown from within a process, it's caught and passed here.&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
        &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="c1"&gt;// Ohh No! A process took too long to finish. Let's do something &lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
    &lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To learn more about the &lt;code&gt;spatie/async&lt;/code&gt; package read this article from one of its contributors &lt;a href="https://stitcher.io/blog/asynchronous-php"&gt;here&lt;/a&gt; and you can also refer to the &lt;a href="https://github.com/spatie/async"&gt;GitHub repo&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>php</category>
      <category>async</category>
      <category>parallel</category>
    </item>
  </channel>
</rss>
