<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Ahmed on Medium]]></description>
        <link>https://medium.com/@.Chromax?source=rss-e20f09a77d74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UxpZ9KwUpxu71n2f4wyv3g.jpeg</url>
            <title>Stories by Mohamed Ahmed on Medium</title>
            <link>https://medium.com/@.Chromax?source=rss-e20f09a77d74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:39:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@.Chromax/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bridging Laravel Versions: A Polyfill for Http::query() and RFC 10008]]></title>
            <link>https://medium.com/@.Chromax/bridging-laravel-versions-a-polyfill-for-http-query-and-rfc-10008-bf525037c697?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf525037c697</guid>
            <category><![CDATA[query]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[polyfill]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 21:49:45 GMT</pubDate>
            <atom:updated>2026-07-12T21:49:45.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="http query" src="https://cdn-images-1.medium.com/max/1024/0*raZa0o1so7jRKb0i.png" /></figure><p>Laravel 13.19 quietly shipped something bigger than a convenience method: first-class support for the HTTP <strong>QUERY</strong> verb on the HTTP client.</p><p>If you are still on Laravel 10, 11, or early 13 — and you want the same API today without waiting on an upgrade — that is exactly why I built this polyfill.</p><p><strong>Package:</strong> <a href="https://github.com/mohamedahmed01/http-query-polyfill">mohamedahmed01/laravel-http-query-polyfill</a></p><h3>The problem QUERY solves</h3><p>For years, API designers have been stuck between two imperfect options:</p><p>Approach Pros Cons <strong>GET</strong> with a long query string Safe, cacheable, idempotent URL length limits, ugly nested filters, logging noise <strong>POST</strong> with a JSON body Expressive payloads Not safe — intermediaries and caches treat it as a write</p><p>Complex search endpoints are the classic example. You need nested filters, arrays, date ranges, and sorting — but you are not creating or mutating a resource. Stuffing that into a query string is painful. Using POST lies about the semantics.</p><p><strong>RFC 10008</strong> formalizes a better answer: the HTTP QUERY method.</p><ul><li>Safe and idempotent (like GET)</li><li>Carries the query in the <strong>request body</strong> (like POST)</li><li>Designed to be cacheable</li></ul><p>In short: expressive reads without abusing POST.</p><p>Laravel added client support in <a href="https://github.com/laravel/framework/pull/60663">PR #60663</a> as part of <strong>v13.19.0</strong>.</p><h3>What Laravel 13.19 gives you</h3><p>On a modern Laravel app, sending a QUERY request looks like this:</p><pre>use Illuminate\Support\Facades\Http;</pre><pre>$response = Http::query(&#39;https://api.example.com/search&#39;, [<br>    &#39;filter&#39; =&gt; [<br>        &#39;status&#39; =&gt; &#39;active&#39;,<br>        &#39;category&#39; =&gt; [&#39;tech&#39;, &#39;design&#39;],<br>    ],<br>    &#39;sort&#39; =&gt; &#39;created_at&#39;,<br>    &#39;date_from&#39; =&gt; &#39;2026-01-01&#39;,<br>]);</pre><p>Under the hood it mirrors post(): the second argument goes in the body using the pending request’s body format (JSON by default). Call asForm() if you need form-encoded data.</p><p>Important distinction:</p><ul><li>Http::query() → HTTP method QUERY + body</li><li>withQueryParameters() / Http::get($url, $query) → URL query string (unchanged)</li></ul><p>They solve different problems. Do not mix them up.</p><p>Laravel also added testing helpers:</p><pre>$this-&gt;queryJson(&#39;/search&#39;, [&#39;filter&#39; =&gt; &#39;active&#39;])-&gt;assertOk()</pre><h3>Why a polyfill?</h3><p>Not every codebase jumps to 13.19 on day one.</p><p>You might:</p><ul><li>Maintain a package that must support Laravel 10–13</li><li>Run an app stuck on 11 or 12 for a few more sprints</li><li>Want to adopt Http::query() in shared code <strong>before</strong> every consumer upgrades</li></ul><p>Dropping to Http::send(&#39;QUERY&#39;, ...) works, but it scatters a low-level escape hatch through your codebase. When you finally upgrade, you either leave that forever or refactor everything.</p><p>A polyfill lets you write the final API now:</p><pre>Http::query($url, $data);</pre><p>On older Laravel it registers a macro. On 13.19+ it gets out of the way and uses the native method.</p><h3>Introducing the package</h3><pre>composer require mohamedahmed01/laravel-http-query-polyfill</pre><p>That’s it. The service provider is auto-discovered.</p><h3>Behavior by version</h3><p>Laravel What happens <strong>10.x — 13.18</strong> Registers PendingRequest::query() via a macro <strong>13.19+</strong> Detects the native method and registers nothing</p><p>Safe to leave installed after you upgrade. No double registration, no surprises.</p><h3>Usage</h3><p>Same as core:</p><pre>Http::query(&#39;https://api.example.com/search&#39;, [<br>    &#39;filter&#39; =&gt; [&#39;status&#39; =&gt; &#39;active&#39;],<br>]);</pre><pre>Http::asForm()-&gt;query(&#39;https://api.example.com/search&#39;, [<br>    &#39;filter&#39; =&gt; &#39;active&#39;,<br>]);</pre><h3>Testing helpers (pre-13.19)</h3><p>Laravel’s query() / queryJson() live on the MakesHttpRequests trait, so they can’t be auto-registered from a package. On older apps, add the polyfill trait to your base test case:</p><pre>use Illuminate\Foundation\Testing\TestCase as BaseTestCase;<br>use MohamedAhmed01\HttpQueryPolyfill\Testing\MakesHttpQueryRequests;</pre><pre>abstract class TestCase extends BaseTestCase<br>{<br>    use MakesHttpQueryRequests;<br>}</pre><pre>$this-&gt;queryJson(&#39;/search&#39;, [&#39;filter&#39; =&gt; &#39;active&#39;])-&gt;assertOk();</pre><p>Skip this trait on Laravel 13.19+ — the methods already exist and will collide.</p><h3>How the polyfill works (briefly)</h3><p>The implementation intentionally mirrors Laravel’s own method:</p><pre>PendingRequest::macro(&#39;query&#39;, function (string $url, $data = []) {<br>    return $this-&gt;send(&#39;QUERY&#39;, $url, [<br>        $this-&gt;bodyFormat =&gt; $data,<br>    ]);<br>});</pre><p>Before registering, it checks whether PendingRequest already declares a real query() method. If yes, boot is a no-op.</p><p>That “detect native, otherwise macro” pattern is what makes the package <strong>forward-compatible</strong>, not just a temporary hack.</p><h3>When you should (and shouldn’t) use QUERY</h3><p><strong>Good fit</strong></p><ul><li>Complex search / filter APIs</li><li>Reporting or analytics “read” endpoints with large payloads</li><li>Service-to-service calls where you want correct safe semantics</li></ul><p><strong>Be careful</strong></p><ul><li>Browser / CORS clients: QUERY is not CORS-safelisted, so cross-origin calls need a preflight</li><li>Proxies, WAFs, and older HTTP stacks may not understand the method yet</li><li>Public APIs should document support clearly</li></ul><p>QUERY is an ecosystem shift, not a free lunch. Adopt it where the semantics matter and your stack can carry the verb.</p><h3>Requirements</h3><ul><li>PHP 8.1+</li><li>Laravel 10–13 (illuminate/http, illuminate/support)</li><li>Guzzle ^7.8 (needed for Laravel’s HTTP client)</li></ul><h3>Try it</h3><pre>composer require mohamedahmed01/laravel-http-query-polyfill</pre><ul><li>GitHub: <a href="https://github.com/mohamedahmed01/http-query-polyfill">https://github.com/mohamedahmed01/http-query-polyfill</a></li><li>Release: <a href="https://github.com/mohamedahmed01/http-query-polyfill/releases/tag/v1.0.0">https://github.com/mohamedahmed01/http-query-polyfill/releases/tag/v1.0.0</a></li></ul><p>If you are building search-heavy APIs on Laravel and want RFC 10008 semantics without waiting for every app to reach 13.19, this should feel boring in the best way: install it, call Http::query(), move on.</p><p><em>If this was useful, a star on the repo helps others find it. Feedback and PRs welcome.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf525037c697" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Feature Flagging in PHP Using AST Parsers]]></title>
            <link>https://medium.com/@.Chromax/implementing-feature-flagging-in-php-using-ast-parsers-d2feec424b84?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2feec424b84</guid>
            <category><![CDATA[ast]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[feature-flags]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Tue, 21 May 2024 14:02:05 GMT</pubDate>
            <atom:updated>2024-05-21T14:02:05.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*onUtNs91vNrEeP3xbXbK2w.png" /></figure><h4>Introduction</h4><p>Feature flagging is a powerful technique used to enable or disable features in a codebase without deploying new code. While traditional methods involve using conditional statements directly in the source code, a more sophisticated approach involves using Abstract Syntax Tree (AST) parsers. This method allows for precise and automated modifications of the codebase. In this article, we’ll explore how to implement feature flagging in PHP using AST parsers, specifically with the nikic/php-parser library.</p><h4>What is an AST?</h4><p>An Abstract Syntax Tree (AST) is a tree representation of the syntactic structure of source code. Each node in the tree represents a construct occurring in the source code. ASTs are widely used in compilers and interpreters to perform syntax analysis and code transformations.</p><h4>Setting Up the Environment</h4><p>First, ensure you have Composer installed, as we’ll use the nikic/php-parser library. Install it using the following command:</p><pre>composer require nikic/php-parser</pre><h4>Parsing the Source Code</h4><p>Let’s start with a simple PHP file (source_file.php) that contains a function we want to control with a feature flag:</p><pre>&lt;?php<br>function featureFunction() {<br>    echo &quot;New Feature!&quot;;<br>}<br>echo &quot;Hello, World!&quot;;<br>featureFunction();</pre><h4>Modifying the AST</h4><p>To modify the AST and introduce feature flagging, we’ll create a script that:</p><ol><li>Parses the PHP code into an AST.</li><li>Traverses the AST to find the function call we want to control.</li><li>Wraps the function call in a conditional statement checking the feature flag.</li></ol><p>Here’s the script (modify_code.php):</p><pre>&lt;?php<br>require &#39;vendor/autoload.php&#39;;<br>use PhpParser\Error;<br>use PhpParser\Node;<br>use PhpParser\Node\Stmt\If_;<br>use PhpParser\Node\Expr\FuncCall;<br>use PhpParser\Node\Expr\Variable;<br>use PhpParser\NodeTraverser;<br>use PhpParser\NodeVisitorAbstract;<br>use PhpParser\ParserFactory;<br>use PhpParser\PrettyPrinter;<br>class FeatureFlagVisitor extends NodeVisitorAbstract {<br>    public function enterNode(Node $node) {<br>        if ($node instanceof FuncCall &amp;&amp; $node-&gt;name-&gt;toString() === &#39;featureFunction&#39;) {<br>            $featureFlagCheck = new If_(<br>                new Variable(&#39;FEATURE_FLAG&#39;),<br>                [<br>                    &#39;stmts&#39; =&gt; [$node]<br>                ]<br>            );<br>            return $featureFlagCheck;<br>        }<br>    }<br>}<br>$code = file_get_contents(&#39;source_file.php&#39;);<br>$parser = (new ParserFactory)-&gt;create(ParserFactory::PREFER_PHP7);<br>try {<br>    $ast = $parser-&gt;parse($code);<br>    $traverser = new NodeTraverser();<br>    $traverser-&gt;addVisitor(new FeatureFlagVisitor());<br>    $modifiedAst = $traverser-&gt;traverse($ast);<br>    $prettyPrinter = new PrettyPrinter\Standard();<br>    $modifiedCode = $prettyPrinter-&gt;prettyPrintFile($modifiedAst);<br>    file_put_contents(&#39;modified_source_file.php&#39;, $modifiedCode);<br>} catch (Error $e) {<br>    echo &quot;Parse error: {$e-&gt;getMessage()}\n&quot;;<br>}</pre><h4>Generating the Modified Code</h4><p>Running the script generates a new PHP file (modified_source_file.php) with the feature flag check:</p><pre>&lt;?php<br>function featureFunction() {<br>    echo &quot;New Feature!&quot;;<br>}<br>echo &quot;Hello, World!&quot;;<br>if ($FEATURE_FLAG) {<br>    featureFunction();<br>}</pre><h4>Conclusion</h4><p>Using AST parsers for feature flagging allows for precise and automated modifications of your codebase. This method is particularly useful for large projects where manual updates would be error-prone and time-consuming. By leveraging the nikic/php-parser library, we demonstrated how to parse PHP code, modify its AST, and generate the updated code with feature flags. This approach not only ensures code quality but also simplifies feature management and deployment strategies.<br>If you are intrigued by the concept and in the market for a LARAVEL feature flagging library and check <a href="https://github.com/mohamedahmed01/feature-flag">mine</a> , it’s really cool with a tonne of features and if you would like to improve on it, I welcome all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2feec424b84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actor-Based Programming with Laravel: Idempotency and Actor Design Resurrection with a Shopping…]]></title>
            <link>https://medium.com/@.Chromax/actor-based-programming-with-laravel-idempotency-and-actor-design-resurrection-with-a-shopping-352ae950a0ba?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/352ae950a0ba</guid>
            <category><![CDATA[actor-model]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Sat, 18 May 2024 13:38:21 GMT</pubDate>
            <atom:updated>2024-05-18T13:38:21.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Actor-Based Programming with Laravel: Idempotency and Actor Design Resurrection with a Shopping Basket Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lH37I9dPtHyTO24f0KGShA.jpeg" /><figcaption>shopping basket</figcaption></figure><h3>Introduction</h3><p>Actor-based programming is a paradigm that treats “actors” as the fundamental units of computation. Each actor can perform tasks, create new actors, and communicate with other actors asynchronously. This model offers a robust approach for building concurrent and distributed systems. One of the significant challenges in such systems is ensuring idempotency and actor resurrection. In this article, we’ll explore these concepts and demonstrate how to implement them using Laravel, a popular PHP framework, with a practical example of a shopping basket.</p><h3>Understanding Actor-Based Programming</h3><h3>What is an Actor?</h3><p>In the actor model, an actor is an independent entity that encapsulates state and behavior. It interacts with other actors through message passing, ensuring no shared state between actors. This isolation simplifies reasoning about concurrency and state management.</p><h3>Key Characteristics of Actors</h3><ol><li><strong>Encapsulation</strong>: Each actor maintains its state privately.</li><li><strong>Asynchronous Communication</strong>: Actors communicate by sending messages asynchronously.</li><li><strong>Concurrency</strong>: Actors operate concurrently and independently.</li><li><strong>Failure Isolation</strong>: Errors in one actor do not directly affect others.</li></ol><h3>Benefits of Actor-Based Design</h3><ul><li><strong>Scalability</strong>: Easy to distribute actors across multiple nodes.</li><li><strong>Fault Tolerance</strong>: Isolated failures with actor resurrection strategies.</li><li><strong>Simplified Concurrency</strong>: No need for locks or other synchronization mechanisms.</li></ul><h3>Idempotency in Actor Systems</h3><h3>What is Idempotency?</h3><p>Idempotency ensures that performing an operation multiple times produces the same result as performing it once. This is crucial in distributed systems to handle retries without unintended side effects.</p><h3>Achieving Idempotency</h3><ol><li><strong>Unique Identifiers</strong>: Assign unique IDs to messages or operations to detect and discard duplicates.</li><li><strong>State Versioning</strong>: Use version numbers to ensure state changes are applied only once.</li><li><strong>Checkpoints and Snapshots</strong>: Save the state periodically to recover consistently after failures.</li></ol><h3>Actor Resurrection</h3><h3>What is Actor Resurrection?</h3><p>Actor resurrection refers to the process of recovering actors after they fail. This includes restoring their state and ensuring they continue processing from where they left off.</p><h3>Strategies for Actor Resurrection</h3><ol><li><strong>Stateless Actors</strong>: If actors are stateless, they can simply be restarted without state recovery.</li><li><strong>Stateful Actors</strong>: For stateful actors, state persistence mechanisms like databases or distributed caches are used.</li><li><strong>Checkpointing</strong>: Periodically save the actor’s state to persistent storage.</li><li><strong>Message Replaying</strong>: Replay stored messages to bring the actor back to its previous state.</li></ol><h3>Implementing Actor-Based Programming in Laravel</h3><h3>Setting Up Laravel</h3><p>First, ensure you have Laravel installed. You can create a new Laravel project using Composer:</p><pre>composer create-project --prefer-dist laravel/laravel actor-example</pre><h3>Creating an Actor Class</h3><p>Let’s define an Actor class. We’ll use Laravel’s Job system to manage actors and queues.</p><pre>namespace App\Actors;<br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Foundation\Bus\Dispatchable;<br>class Actor implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable;<br>    protected $state;<br>    public function __construct($initialState)<br>    {<br>        $this-&gt;state = $initialState;<br>    }<br>    public function handle()<br>    {<br>        // Actor logic goes here<br>    }<br>    public function getState()<br>    {<br>        return $this-&gt;state;<br>    }<br>    public function setState($state)<br>    {<br>        $this-&gt;state = $state;<br>    }<br>}</pre><h3>Implementing Idempotency</h3><p>To ensure idempotency, we’ll use unique identifiers and state versioning. Let’s modify the Actor class to include these features.</p><pre>use Illuminate\Support\Facades\Cache;<br>class Actor implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable;<br>    protected $state;<br>    protected $actorId;<br>    public function __construct($actorId, $initialState)<br>    {<br>        $this-&gt;actorId = $actorId;<br>        $this-&gt;state = $initialState;<br>    }<br>    public function handle()<br>    {<br>        $stateVersion = Cache::get($this-&gt;actorId . &#39;_version&#39;, 0);<br>        // Logic to process messages idempotently<br>        // For example, apply state changes only if the version matches<br>        // Update state and version<br>        Cache::put($this-&gt;actorId . &#39;_state&#39;, $this-&gt;state);<br>        Cache::put($this-&gt;actorId . &#39;_version&#39;, $stateVersion + 1);<br>    }<br>    public function getState()<br>    {<br>        return $this-&gt;state;<br>    }<br>    public function setState($state)<br>    {<br>        $this-&gt;state = $state;<br>    }<br>}</pre><h3>Actor Resurrection</h3><p>For actor resurrection, we’ll implement checkpointing by periodically saving the actor’s state to persistent storage.</p><pre>use Illuminate\Support\Facades\DB;<br>class Actor implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable;<br>    protected $state;<br>    protected $actorId;<br>    public function __construct($actorId, $initialState)<br>    {<br>        $this-&gt;actorId = $actorId;<br>        $this-&gt;state = $initialState;<br>        $this-&gt;loadState();<br>    }<br>    public function handle()<br>    {<br>        $stateVersion = Cache::get($this-&gt;actorId . &#39;_version&#39;, 0);<br>        // Logic to process messages idempotently<br>        // Update state and version<br>        $this-&gt;saveState();<br>        Cache::put($this-&gt;actorId . &#39;_version&#39;, $stateVersion + 1);<br>    }<br>    public function getState()<br>    {<br>        return $this-&gt;state;<br>    }<br>    public function setState($state)<br>    {<br>        $this-&gt;state = $state;<br>    }<br>    protected function saveState()<br>    {<br>        DB::table(&#39;actors&#39;)-&gt;updateOrInsert(<br>            [&#39;actor_id&#39; =&gt; $this-&gt;actorId],<br>            [&#39;state&#39; =&gt; serialize($this-&gt;state), &#39;updated_at&#39; =&gt; now()]<br>        );<br>    }<br>    protected function loadState()<br>    {<br>        $record = DB::table(&#39;actors&#39;)-&gt;where(&#39;actor_id&#39;, $this-&gt;actorId)-&gt;first();<br>        if ($record) {<br>            $this-&gt;state = unserialize($record-&gt;state);<br>        }<br>    }<br>}</pre><h3>Shopping Basket Example</h3><p>Let’s create an actor that handles a shopping basket. This actor will manage items in the basket, ensuring operations are idempotent and the state can be recovered.</p><h4>Actor Class for Shopping Basket</h4><pre>namespace App\Actors;<br>use Illuminate\Support\Facades\Cache;<br>use Illuminate\Support\Facades\DB;<br>class ShoppingBasketActor implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable;<br>    protected $basket;<br>    protected $actorId;<br>    public function __construct($actorId, $initialBasket = [])<br>    {<br>        $this-&gt;actorId = $actorId;<br>        $this-&gt;basket = $initialBasket;<br>        $this-&gt;loadState();<br>    }<br>    public function handle()<br>    {<br>        // Example logic for handling messages (like adding or removing items)<br>    }<br>    public function addItem($item)<br>    {<br>        $this-&gt;basket[] = $item;<br>        $this-&gt;saveState();<br>    }<br>    public function removeItem($item)<br>    {<br>        $this-&gt;basket = array_filter($this-&gt;basket, function ($basketItem) use ($item) {<br>            return $basketItem !== $item;<br>        });<br>        $this-&gt;saveState();<br>    }<br>    public function getBasket()<br>    {<br>        return $this-&gt;basket;<br>    }<br>    protected function saveState()<br>    {<br>        DB::table(&#39;actors&#39;)-&gt;updateOrInsert(<br>            [&#39;actor_id&#39; =&gt; $this-&gt;actorId],<br>            [&#39;state&#39; =&gt; serialize($this-&gt;basket), &#39;updated_at&#39; =&gt; now()]<br>        );<br>    }<br>    protected function loadState()<br>    {<br>        $record = DB::table(&#39;actors&#39;)-&gt;where(&#39;actor_id&#39;, $this-&gt;actorId)-&gt;first();<br>        if ($record) {<br>            $this-&gt;basket = unserialize($record-&gt;state);<br>        }<br>    }<br>}</pre><h4>Controller for Shopping Basket</h4><pre>namespace App\Http\Controllers;<br>use App\Actors\ShoppingBasketActor;<br>use Illuminate\Http\Request;<br>class ShoppingBasketController extends Controller<br>{<br>    public function addItem(Request $request, $actorId)<br>    {<br>        $item = $request-&gt;input(&#39;item&#39;);<br>        $actor = new ShoppingBasketActor($actorId);<br>        $actor-&gt;addItem($item);<br>        return response()-&gt;json([&#39;message&#39; =&gt; &#39;Item added to basket&#39;, &#39;basket&#39; =&gt; $actor-&gt;getBasket()]);<br>    }<br>    public function removeItem(Request $request, $actorId)<br>    {<br>        $item = $request-&gt;input(&#39;item&#39;);<br>        $actor = new ShoppingBasketActor($actorId);<br>        $actor-&gt;removeItem($item);<br>        return response()-&gt;json([&#39;message&#39; =&gt; &#39;Item removed from basket&#39;, &#39;basket&#39; =&gt; $actor-&gt;getBasket()]);<br>    }<br>    public function getBasket($actorId)<br>    {<br>        $actor = new ShoppingBasketActor($actorId);<br>        return response()-&gt;json([&#39;basket&#39; =&gt; $actor-&gt;getBasket()]);<br>    }<br>}</pre><p>In routes/api.php, define the routes:</p><pre>use App\Http\Controllers\ShoppingBasketController;<br><br>Route::post(&#39;/basket/{actorId}/add&#39;, [ShoppingBasketController::class, &#39;addItem&#39;]);<br>Route::post(&#39;/basket/{actorId}/remove&#39;, [ShoppingBasketController::class, &#39;removeItem&#39;]);<br>Route::get(&#39;/basket/{actorId}&#39;, [ShoppingBasketController::class, &#39;getBasket&#39;]);</pre><h3>Finally,</h3><p>Actor-based programming offers a powerful paradigm for building scalable, resilient software that can hadle scalability with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=352ae950a0ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Strategy Pattern in PHP and Laravel: A Comprehensive Guide]]></title>
            <link>https://medium.com/@.Chromax/the-strategy-pattern-in-php-and-laravel-a-comprehensive-guide-87a066778893?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a066778893</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[desing-pattern]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Mon, 06 May 2024 05:39:20 GMT</pubDate>
            <atom:updated>2024-05-19T09:58:10.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*iomr5owrr9A4wJZn_iMb5g.jpeg" /></figure><p>The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate them, and make them interchangeable. This pattern enables the algorithm to vary independently from the clients that use it. In simpler terms, the Strategy pattern is a way to define a collection of algorithms and select the appropriate one at runtime.</p><p>This article provides an overview of the Strategy pattern, discusses its key components, and demonstrates how to implement it in PHP. Additionally, we’ll implement a similar strategy in Laravel to show its versatility in different contexts.</p><h3>Why Use the Strategy Pattern?</h3><ul><li><strong>Flexibility</strong>: You can switch algorithms at runtime without altering the structure of the codebase.</li><li><strong>Code Reusability</strong>: Algorithms can be used in different contexts without modification.</li><li><strong>Separation of Concerns</strong>: Business logic is decoupled from the algorithm’s implementation.</li></ul><h3>Key Components of the Strategy Pattern</h3><ol><li><strong>Context</strong>: The object that uses a Strategy to perform its task. It doesn’t implement the algorithm itself but rather uses a Strategy object to do so.</li><li><strong>Strategy</strong>: The interface or abstract class that defines a contract for all concrete strategies.</li><li><strong>Concrete Strategies</strong>: Classes that implement the Strategy interface and provide specific algorithms.</li></ol><h3>Implementing the Strategy Pattern in PHP</h3><p>Let’s consider an example where we need to calculate the cost of shipping packages with different strategies. We’ll have the following classes:</p><ul><li>ShippingContext: The context that uses different shipping strategies.</li><li>ShippingStrategy: The interface for shipping strategies.</li><li>StandardShipping, ExpressShipping, InternationalShipping: Concrete strategies implementing different shipping algorithms.</li></ul><h3>Step 1: Define the Strategy Interface</h3><pre>&lt;?php<br>interface ShippingStrategy {<br>    public function calculateShippingCost(float $weight, float $distance): float;<br>}</pre><h3>Step 2: Implement Concrete Strategies</h3><pre>&lt;?php<br>class StandardShipping implements ShippingStrategy {<br>    public function calculateShippingCost(float $weight, float $distance): float {<br>        // A simple cost calculation for standard shipping<br>        return 0.5 * $weight + 0.1 * $distance;<br>    }<br>}<br>class ExpressShipping implements ShippingStrategy {<br>    public function calculateShippingCost(float $weight, float $distance): float {<br>        // A more expensive calculation for express shipping<br>        return 1.0 * $weight + 0.2 * $distance;<br>    }<br>}<br>class InternationalShipping implements ShippingStrategy {<br>    public function calculateShippingCost(float $weight, float $distance): float {<br>        // An even more expensive calculation for international shipping<br>        return 1.5 * $weight + 0.3 * $distance;<br>    }<br>}</pre><h3>Step 3: Implement the Context Class</h3><pre>&lt;?php<br>class ShippingContext {<br>    private ShippingStrategy $strategy;<br>    public function __construct(ShippingStrategy $strategy) {<br>        $this-&gt;strategy = $strategy;<br>    }<br>    public function setStrategy(ShippingStrategy $strategy): void {<br>        $this-&gt;strategy = $strategy;<br>    }<br>    public function calculateCost(float $weight, float $distance): float {<br>        return $this-&gt;strategy-&gt;calculateShippingCost($weight, $distance);<br>    }<br>}</pre><h3>Step 4: Test the Strategy Pattern</h3><pre>&lt;?php<br>$weight = 10.0; // weight in kilograms<br>$distance = 100.0; // distance in kilometers<br>// Use standard shipping<br>$standardShipping = new StandardShipping();<br>$shippingContext = new ShippingContext($standardShipping);<br>echo &quot;Standard Shipping Cost: &quot; . $shippingContext-&gt;calculateCost($weight, $distance) . &quot;\n&quot;;<br>// Switch to express shipping<br>$expressShipping = new ExpressShipping();<br>$shippingContext-&gt;setStrategy($expressShipping);<br>echo &quot;Express Shipping Cost: &quot; . $shippingContext-&gt;calculateCost($weight, $distance) . &quot;\n&quot;;<br>// Switch to international shipping<br>$internationalShipping = new InternationalShipping();<br>$shippingContext-&gt;setStrategy($internationalShipping);<br>echo &quot;International Shipping Cost: &quot; . $shippingContext-&gt;calculateCost($weight, $distance) . &quot;\n&quot;;</pre><h3>Implementing the Strategy Pattern in Laravel</h3><p>Now let’s see how to implement the Strategy pattern in a Laravel application. In this case, let’s imagine you want to apply different tax calculation strategies based on the user’s region.</p><h3>Step 1: Define the Strategy Interface</h3><p>In Laravel, you can create the strategy interface in the app folder or within a specific namespace, such as App\Tax.</p><pre>&lt;?php<br>namespace App\Tax;<br>interface TaxStrategy {<br>    public function calculateTax(float $amount): float;<br>}</pre><h3>Step 2: Implement Concrete Strategies</h3><p>Here are a couple of concrete strategies for different regions:</p><pre>&lt;?php<br>namespace App\Tax;<br>class USATaxStrategy implements TaxStrategy {<br>    public function calculateTax(float $amount): float {<br>        // Assume 7% tax for the USA<br>        return $amount * 0.07;<br>    }<br>}<br>class CanadaTaxStrategy implements TaxStrategy {<br>    public function calculateTax(float $amount): float {<br>        // Assume 5% tax for Canada<br>        return $amount * 0.05;<br>    }<br>}</pre><h3>Step 3: Implement the Context Class</h3><p>The context class can be used to switch between different tax strategies based on certain conditions.</p><pre>&lt;?php<br>namespace App\Tax;<br>class TaxContext {<br>    private TaxStrategy $strategy;<br>    public function __construct(TaxStrategy $strategy) {<br>        $this-&gt;strategy = $strategy;<br>    }<br>    public function setStrategy(TaxStrategy $strategy): void {<br>        $this-&gt;strategy = $strategy;<br>    }<br>    public function calculateTax(float $amount): float {<br>        return $this-&gt;strategy.calculateTax($amount);<br>    }<br>}</pre><h3>Step 4: Use the Strategy Pattern in a Laravel Controller</h3><p>To demonstrate how the Strategy pattern can be used in a Laravel controller, let’s create a simple controller to calculate tax based on a given region.</p><pre>&lt;?php<br>namespace App\Http\Controllers;<br>use Illuminate\Http\Request;<br>use App\Tax\TaxContext;<br>use App\Tax\USATaxStrategy;<br>use App\Tax\CanadaTaxStrategy;<br>class TaxController extends Controller {<br>    public function calculate(Request $request) {<br>        $amount = $request-&gt;input(&#39;amount&#39;, 100.0);<br>        $region = $request-&gt;input(&#39;region&#39;, &#39;USA&#39;);<br>        $taxContext = null;<br>        if ($region === &#39;USA&#39;) {<br>            $taxContext = new TaxContext(new USATaxStrategy());<br>        } else if ($region === &#39;Canada&#39;) {<br>            $taxContext = new TaxContext(new CanadaTaxStrategy());<br>        }<br>        if ($taxContext) {<br>            $tax = $taxContext.calculateTax($amount);<br>            return response()-&gt;json([&#39;amount&#39; =&gt; $amount, &#39;tax&#39; =&gt; $tax]);<br>        }<br>        return response()-&gt;json([&#39;error&#39; =&gt; &#39;Invalid region&#39;], 400);<br>    }<br>}</pre><p>In this example, the TaxController uses the Strategy pattern to calculate tax based on the user&#39;s region. It demonstrates the flexibility and ease of switching strategies in Laravel.</p><h3>Conclusion</h3><p>The Strategy pattern allows you to switch algorithms at runtime, providing a flexible and maintainable way to manage different behaviors in your codebase. By encapsulating the algorithm logic in separate classes, you can promote code reusability and separation of concerns. This guide demonstrated how to implement the Strategy pattern in both pure PHP and Laravel, showing its versatility and practical applications in real-world scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a066778893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a UDP Server, Gaming Client, and Tic-Tac-Toe Game with PHP]]></title>
            <link>https://medium.com/@.Chromax/building-a-udp-server-gaming-client-and-tic-tac-toe-game-with-php-83409d89896e?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/83409d89896e</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[udp]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Sat, 06 Apr 2024 02:04:43 GMT</pubDate>
            <atom:updated>2024-04-06T02:09:03.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*fj1lcwphXwWRYU89F35Nag.png" /><figcaption>tic tac toe using command line interface</figcaption></figure><p>In the realm of networking, UDP (User Datagram Protocol) plays a crucial role, particularly in scenarios where speed and efficiency are paramount, such as online gaming. In this guide, we’ll not only explore the creation of a UDP server and gaming client using PHP but also delve into building a Tic-Tac-Toe game that communicates between the client and server. PHP, primarily known for web development, can be harnessed with its Socket extension to create networked applications, making it a versatile tool for a variety of purposes, including gaming.</p><p>Understanding UDP:</p><p>Before proceeding, let’s reinforce our understanding of UDP. Unlike TCP (Transmission Control Protocol), UDP is connectionless and lacks guaranteed delivery or packet ordering. However, this lightweight nature makes UDP ideal for real-time applications like online gaming, where a little packet loss is acceptable in exchange for reduced latency.</p><p>Setting Up PHP Environment:</p><p>Firstly, ensure PHP is installed on your system. You can check your PHP version by running `php -v` in your terminal. If PHP isn’t installed, download and install it from the official PHP website or via a package manager like apt or Homebrew.</p><p>Creating the UDP Server:</p><p>Let’s start by creating a UDP server using PHP, as explained in the previous section. We’ll name our server script `udp_server.php` and follow the steps outlined before.</p><pre>&lt;?php<br>// Create a UDP socket<br>$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);<br>// Bind the socket to an address and port<br>socket_bind($socket, &#39;0.0.0.0&#39;, 1234);<br>echo &quot;UDP Server Started…\n&quot;;<br>// Infinite loop to handle incoming data<br>while (true) {<br> // Receive data from client<br> socket_recvfrom($socket, $buffer, 1024, 0, $client_ip, $client_port);<br> <br> echo &quot;Received from $client_ip:$client_port: $buffer\n&quot;;<br> <br> // You can add your custom processing logic here<br> <br> // Respond back to the client (optional)<br> // socket_sendto($socket, &quot;Acknowledged&quot;, strlen(&quot;Acknowledged&quot;), 0, $client_ip, $client_port);<br>}<br>// Close the socket<br>socket_close($socket);<br>?&gt;</pre><p>Testing the UDP Server:<br>Save the `udp_server.php` file and run it in your terminal using:</p><pre>php udp_server.php</pre><p>Your UDP server should now be listening for incoming data on port 1234.</p><p>Creating the UDP Gaming Client:<br>Now, let’s proceed with building our UDP gaming client using PHP. We’ll name our client script `udp_client.php`</p><pre>&lt;?php<br>// Create a UDP socket<br>$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);<br>// Server address and port<br>$server_address = &#39;127.0.0.1&#39;;<br>$server_port = 1234;<br>// Data to send<br>$data = &quot;Hello from UDP Client!&quot;;<br>// Send data to server<br>socket_sendto($socket, $data, strlen($data), 0, $server_address, $server_port);<br>echo &quot;Data sent to server: $data\n&quot;;<br>// Close the socket<br>socket_close($socket);<br>?&gt;</pre><p>In the code above:<br>- We create a UDP socket using `socket_create`.<br>- Define the server address and port.<br>- Prepare the data to send.<br>- Send the data to the server using `socket_sendto`.<br>- Close the socket.</p><p>Testing the UDP Gaming Client:<br>Save the `udp_client.php` file and run it in your terminal:</p><pre>php udp_client.php</pre><p>You should see the message “Data sent to server: Hello from UDP Client!” indicating successful communication with the server.</p><p>Building Tic-Tac-Toe Game:<br>Now, let’s extend our example to include a simple Tic-Tac-Toe game that communicates between the client and server. We’ll start by implementing the game logic on the server-side.</p><pre>&lt;?php<br>// Create a UDP socket<br>$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);<br>// Bind the socket to an address and port<br>socket_bind($socket, &#39;0.0.0.0&#39;, 1234);<br>echo &quot;UDP Server Started…\n&quot;;<br>// Game variables<br>$board = [&#39;-&#39;, &#39;-&#39;, &#39;-&#39;, &#39;-&#39;, &#39;-&#39;, &#39;-&#39;, &#39;-&#39;, &#39;-&#39;, &#39;-&#39;];<br>$current_player = &#39;X&#39;;<br>// Infinite loop to handle incoming data<br>while (true) {<br> // Receive data from client<br> socket_recvfrom($socket, $data, 1024, 0, $client_ip, $client_port);<br> <br> echo &quot;Received from $client_ip:$client_port: $data\n&quot;;<br> <br> // Process client&#39;s move<br> $move = intval($data);<br> if ($move &gt;= 0 &amp;&amp; $move &lt;= 8 &amp;&amp; $board[$move] == &#39;-&#39;) {<br> $board[$move] = $current_player;<br> $current_player = ($current_player == &#39;X&#39;) ? &#39;O&#39; : &#39;X&#39;;<br> }<br> <br> // Send updated board to client<br> $response = implode(&#39;,&#39;, $board);<br> socket_sendto($socket, $response, strlen($response), 0, $client_ip, $client_port);<br>}<br>// Close the socket<br>socket_close($socket);<br>?&gt;</pre><p>Now, let’s create the client-side logic for the Tic-Tac-Toe game:</p><pre>&lt;?php<br>// Create a UDP socket<br>$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);<br>// Server address and port<br>$server_address = &#39;127.0.0.1&#39;;<br>$server_port = 1234;<br>// Initial request to start the game<br>socket_sendto($socket, &quot;start&quot;, strlen(&quot;start&quot;), 0, $server_address, $server_port);<br>// Game loop<br>while (true) {<br> // Receive updated board from server<br> socket_recvfrom($socket, $board, 1024, 0, $server_ip, $server_port);<br> <br> // Display the board<br> echo &quot;Tic-Tac-Toe Board:\n&quot;;<br> $rows = explode(&#39;,&#39;, $board);<br> for ($i = 0; $i &lt; 3; $i++) {<br> echo $rows[$i * 3] . &#39; | &#39; . $rows[$i * 3 + 1] . &#39; | &#39; . $rows[$i * 3 + 2] . &quot;\n&quot;;<br> if ($i &lt; 2) {<br> echo &quot; - - - - -\n&quot;;<br> }<br> }<br> <br> // Check for game over condition or prompt player for move<br> // Add your game logic here<br> <br> // Example: Prompting player for move<br> echo &quot;Enter your move (0–8): &quot;;<br> $move = intval(trim(fgets(STDIN)));<br> <br> // Send player&#39;s move to server<br> socket_sendto($socket, strval($move), strlen(strval($move)), 0, $server_address, $server_port);<br>}<br>?&gt;</pre><p>Conclusion:<br>In this comprehensive guide, we’ve covered the creation of a UDP server, gaming client, and even implemented a simple Tic-Tac-Toe game that communicates between the client and server using PHP. By leveraging PHP’s Socket extension, we’ve demonstrated the versatility of PHP in building networked applications, including real-time gaming scenarios. Experiment with different game mechanics and expand on it and let me know :D .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83409d89896e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Debugging: Navigating Unknown Environments]]></title>
            <link>https://medium.com/@.Chromax/test-driven-debugging-navigating-unknown-environments-757338e7ea1?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/757338e7ea1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[complex-systems]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 22:34:31 GMT</pubDate>
            <atom:updated>2023-08-27T22:34:31.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*YP-QrUnKxl5S3jP7VV6Wcw.jpeg" /></figure><p>In the ever-evolving world of software engineering, encountering unknown environments can be an inevitable part of the job. These situations can be challenging, particularly when it comes to debugging issues. In this article, we will explore the concept of test-driven debugging in unknown environments by using a broken fan sound in a refrigerator as an example. We will provide a step-by-step walkthrough to help engineers tackle such problems effectively.</p><p>Step 1: Understand the Problem Before diving into the debugging process, it is crucial to understand the problem at hand. In this case, we have a broken fan sound emanating from a refrigerator. Gather all available information, such as when the problem started, any recent changes made to the refrigerator, and specific observations about the broken fan sound.</p><p>Step 2: Formulate and Run Initial Tests Begin with a hypothesis about the possible causes of the issue and devise a set of initial tests. For example:</p><ol><li>Disconnect the power supply to the refrigerator and check if the broken fan sound still persists. If it does, it indicates a possible electrical or mechanical issue unrelated to the fan.</li><li>Check if this issue is isolated to a specific temperature range by setting various temperatures and monitoring the fan sound.</li><li>Observe the intensity of the broken fan sound with different refrigerator settings, such as changing the temperature, switching modes, or altering the airflow pattern.</li></ol><p>Document the results of each test, as this information will be fundamental for narrowing down the potential causes.</p><p>Step 3: Repeatable Test Case Creation Based on the initial tests, identify a specific scenario that consistently reproduces the broken fan sound. This helps create a repeatable test case to focus the debugging efforts. For example, if setting the refrigerator to a specific temperature consistently triggers the sound, it becomes the primary test case.</p><p>Step 4: Divide and Conquer Now that we have a repeatable test case, divide the system into smaller components, focusing on the fan, in order to isolate the problem. Test each component individually to determine if the broken fan sound involves an interaction between multiple parts. This approach helps narrow down the potential causes and eliminates any unrelated components as potential sources of the issue.</p><p>Step 5: Analyze Error Logs and Related Documentation Consult available error logs, service manuals, documentation, or follow similar cases reported by others. These resources may provide insights into recurring issues or specific troubleshooting techniques related to the refrigerator’s fan. The collective knowledge of the community can be incredibly helpful in solving complex issues.</p><p>Step 6: Implement Additional Tests Based on the insights garnered in the previous steps, conduct more specific tests to validate or eliminate potential causes. For instance, if the documentation indicated a recent firmware update for the refrigerator, test it on another refrigerator running the previous version of firmware to see if it exhibits similar behavior.</p><p>Step 7: Narrowing Down the Cause Continue systematically eliminating potential causes until the root cause is identified. Depending on the complexity of the issue and the available resources, this process may require multiple iterations of test-driven debugging.</p><p>Step 8: Implement a Solution Once the root cause is identified, develop and implement a solution accordingly. In this case, it could involve repairing or replacing the fan or performing some necessary maintenance to troubleshoot the broken fan sound.</p><p>Test-driven debugging in unknown environments demands a systematic approach to isolate and resolve issues effectively. By following the steps outlined in this walkthrough, software engineers can enhance their debugging skills and confidently tackle problems encountered in unfamiliar systems. Remember, patience, perseverance, and a logical approach will help you navigate through any unknown environment and conquer even the most complex of debugging challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757338e7ea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide for Laravel Middleware]]></title>
            <link>https://medium.com/@.Chromax/comprehensive-guide-for-laravel-middleware-bf8b5e487cbf?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8b5e487cbf</guid>
            <category><![CDATA[laravel-middleware]]></category>
            <category><![CDATA[guidelines]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[walkthrough]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 23:12:23 GMT</pubDate>
            <atom:updated>2023-08-25T23:12:23.009Z</atom:updated>
            <content:encoded><![CDATA[<p>Comprehensive Guide for Laravel Middleware</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*cjMnM8xy02-CuT7Ez1EnIg.jpeg" /><figcaption>laravel middleware</figcaption></figure><ol><li>What is Laravel Middleware?</li></ol><ul><li>Laravel middleware acts as a bridge between incoming HTTP requests and your application, providing a convenient mechanism for filtering and modifying these requests.</li><li>Middleware allows you to perform tasks before and after a request, such as authentication, authorization, rate limiting, and other request manipulations.</li></ul><p>2. Understanding the Middleware Flow:</p><ul><li>In Laravel, middleware is executed in a sequential flow.</li><li>It is executed before and/or after the request reaches the route handler.</li><li>Middleware can alter the request, add attributes to it, or even terminate the request.</li></ul><p>3. Creating and Registering Middleware in Laravel:</p><ul><li>Run the php artisan make:middleware command to create a new middleware class.</li><li>The newly created middleware class will be located in the app/Http/Middleware directory.</li><li>To register the middleware, you need to add it to the $middleware array in the app/Http/Kernel.php file.</li></ul><p>4. Configuring Middleware Groups:</p><ul><li>Laravel provides the ability to group multiple middleware under a single key.</li><li>Define middleware groups in the app/Http/Kernel.php file in the $middlewareGroups array.</li><li>Groups can be useful when applying multiple middleware to multiple routes.</li></ul><p>5. Executing Middleware on Route Level:</p><ul><li>To assign middleware to a specific route, you can use the middleware method in the route definition.</li><li>For example: Route::get(&#39;/example&#39;, function () {})-&gt;middleware(&#39;auth&#39;).</li><li>Middleware can also be applied to a route group or controller.</li></ul><p>6. Middleware Parameters and Arguments:</p><ul><li>Middleware can accept additional parameters or arguments for customization.</li><li>To pass parameters, you need to define them in the middleware’s handle method signature.</li><li>For example: handle($request, Closure $next, $parameter).</li><li>You can then pass the parameter when assigning middleware to a route.</li></ul><p>7. Order of Middleware Execution:</p><ul><li>The order of middleware execution is defined in the $middlewarePriority array in the app/Http/Kernel.php file.</li><li>Middlewares with lower index values are executed first, followed by middlewares with higher index values.</li><li>The order is important, as some middleware may depend on the execution of other middleware.</li></ul><p>8. Terminable Middleware:</p><ul><li>Laravel provides Terminable Middleware, which is executed after the response is sent to the browser.</li><li>Terminable Middleware needs to implement the terminable interface and define the terminate method.</li><li>This allows for cleanup tasks or additional actions after the response is handled.</li></ul><p>9. Middleware for Authentication and Authorization:</p><ul><li>Laravel ships with built-in middleware for authentication and authorization, such as auth and can.</li><li>The auth middleware verifies if the user is authenticated, while the can middleware checks if the user has specific permissions.</li></ul><p>10. Middleware for Rate Limiting:</p><ul><li>Laravel provides throttle middleware for rate limiting.</li><li>This middleware allows you to limit the number of requests a user can make within a certain time period.</li><li>You can configure the throttle middleware with parameters like maximum requests and time window.</li></ul><p>11. Creating Custom Middleware:</p><ul><li>To create custom middleware, run the php artisan make:middleware command and implement the desired logic in the handle method.</li><li>Custom middleware classes should be registered in the app/Http/Kernel.php file.</li><li>You can then assign your custom middleware to routes, groups, or controllers.</li></ul><p>12. Middleware Best Practices:</p><ul><li>Keep middleware logic focused on a specific task and avoid mixing unrelated functionalities.</li><li>Use middleware groups to group related middleware for easier management.</li><li>Document your middleware thoroughly, explaining its purpose and any expected parameters or arguments.</li><li>Test your middleware to ensure it functions as intended and doesn’t introduce any unexpected side effects.</li><li>Follow naming conventions and make sure your middleware class names are descriptive and follow proper naming conventions.</li></ul><p>By following these guidelines, you can effectively utilize Laravel middleware to handle authentication, authorization, rate limiting, and other request manipulations in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8b5e487cbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A guideline to learn Laravel framework for beginners :]]></title>
            <link>https://medium.com/@.Chromax/a-guideline-to-learn-laravel-framework-for-beginners-2e0741538d8?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0741538d8</guid>
            <category><![CDATA[laravel-developer]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 22:55:02 GMT</pubDate>
            <atom:updated>2023-08-25T22:55:28.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>A guideline to learn Laravel framework for beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Not8lbjLNJwX6uAobwk4mg.jpeg" /><figcaption>laravel logo</figcaption></figure><p>Familiarize Yourself with PHP: Before diving into Laravel, ensure you have a strong grasp on PHP fundamentals. Understanding concepts like variables, functions, loops, arrays, and object-oriented programming will make learning Laravel easier.</p><ol><li>Learn the Basics of Laravel: Start by familiarizing yourself with Laravel’s basic concepts, such as routes, views, controllers, and models. Laravel’s official documentation is an excellent resource for this. Read through the documentation to understand how these components fit together.</li><li>Setup Environment: Install a local development environment like XAMPP, WAMP, or Laravel Homestead according to your preference. This will provide you with a server environment to run your Laravel projects.</li><li>Install Laravel: Once your environment is set up, install Laravel using Composer. Composer is a dependency management tool for PHP. The Laravel documentation provides detailed instructions on how to install Laravel using Composer.</li><li>Build Simple Projects: Start by building small projects using Laravel. Create routes to handle HTTP requests, create views to display content, and use controllers to handle logic. Building small projects will help you understand the basic components of Laravel and reinforce your understanding.</li><li>Understand Blade Templating Engine: Laravel uses Blade as its templating engine. Learn the Blade syntax, including directives, control structures, and layouts. Blade makes it easier to generate dynamic content within your views.</li><li>Database Integration: Laravel provides an intuitive database abstraction layer called Eloquent. Learn how to define and work with database models, create migrations, and perform common database operations like querying and inserting data.</li><li>Explore Middleware and Authentication: Laravel’s middleware feature allows you to add additional layers of protection and functionality to your routes. Learn how to create custom middleware and understand how authentication works in Laravel.</li><li>Utilize Packages and Third-Party Libraries: Laravel has a vast ecosystem with various packages and libraries that can enhance your development. Explore the Laravel Package website and discover packages that could be useful for your projects.</li><li>Dive Deeper: Once you have a good understanding of the basics, start exploring more advanced concepts in Laravel, such as API development, queues, caching, events, and testing. Laravel documentation and online tutorials can help you with this.</li><li>Join the Community: Engage with the Laravel community by joining forums, attending Laravel conferences, and participating in online discussions. This will help you stay up to date with the latest developments in the framework and expand your network of fellow Laravel developers.</li></ol><p>Remember, learning Laravel or any framework takes time and practice. Be patient, keep building projects, and continuously seek to improve your skills. Good luck on your journey to becoming a Laravel developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0741538d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Architecture for Your PHP Web Application]]></title>
            <link>https://medium.com/@.Chromax/choosing-the-right-architecture-for-your-php-web-application-7b13202da38c?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b13202da38c</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[monolith]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 22:39:18 GMT</pubDate>
            <atom:updated>2023-08-25T23:13:13.338Z</atom:updated>
            <content:encoded><![CDATA[<p>Choosing the Right Architecture for Your PHP Web Application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ft4LrR18KwUr1nVMwKjuA.png" /></figure><p>Selecting the correct architecture for a PHP web application is crucial for its long-term success and scalability. The architecture forms the foundation upon which the application is built, determining its flexibility, maintainability, and performance. In this article, we will explore various options for PHP web application architecture and discuss their benefits, drawbacks, and suitable use cases.</p><ol><li>Monolithic Architecture: A monolithic architecture involves building the entire application as a single, self-contained unit. All components, such as the user interface, business logic, and data access layer, are tightly coupled and deployed together. Advantages:</li></ol><ul><li>Simplified development, as no complex communication protocols are required.</li><li>Easier code reuse and refactoring within the same codebase.</li><li>Ideal for small to medium-sized applications with limited scalability requirements.</li></ul><p>Drawbacks:</p><ul><li>Lack of scalability makes it challenging to handle an increasing number of users or growing functionality.</li><li>Limited flexibility for deploying different components separately.</li><li>Maintenance becomes difficult as the application grows and evolves.</li></ul><p>2. Layered Architecture: In a layered architecture, the application is divided into distinct layers, enabling a separation of concerns and more modular development.</p><ul><li>Presentation Layer: Handles user interaction and UI rendering.</li><li>Business Logic Layer: Contains application-specific rules and workflows.</li><li>Data Access Layer: Connects to the database and performs data operations. Advantages:</li><li>Improved maintainability and testability due to clear separation of concerns.</li><li>Different layers can be modified or replaced without affecting others.</li><li>Scalability is possible by horizontally scaling specific layers (e.g., web servers separate from database servers).</li></ul><p>Drawbacks:</p><ul><li>Increased complexity and potential communication overhead between layers.</li><li>Can lead to performance issues with excessive inter-layer communication.</li></ul><p>3. Service-Oriented Architecture (SOA): SOA focuses on the concept of designing the application as a set of self-contained, loosely coupled services that communicate over well-defined interfaces (usually through APIs). Advantages:</p><ul><li>Highly scalable and flexible, as services can be developed and deployed independently.</li><li>Reusability of services leads to faster development and better maintainability.</li><li>Supports various technologies, making it suitable for distributed environments.</li></ul><p>Drawbacks:</p><ul><li>Increased complexity in managing service dependencies and communications.</li><li>Performance impacts due to network communication between services.</li></ul><p>4. Microservices Architecture: Microservices take the idea of SOA a step further by breaking down the application into small, independent services that are responsible for specific functionalities. Each service can be developed, deployed, and scaled independently. Advantages:</p><ul><li>Extreme scalability and flexibility, allowing applications to quickly adapt to changing requirements.</li><li>Improved fault isolation, as issues in one microservice do not impact others.</li><li>Encourages the use of modern technologies and frameworks for each service.</li></ul><p>Drawbacks:</p><ul><li>Higher development and operational complexity compared to monolithic or layered architectures.</li><li>Requires a robust service discovery mechanism to handle inter-service communication.</li></ul><p>Choosing the right architecture for your PHP web application is critical to its success. While there is no one-size-fits-all solution, understanding the pros and cons of different options can help you make an informed decision. Consider the size and complexity of your application, anticipated scalability needs, development team expertise, and long-term goals when selecting an architecture. Whether you opt for a monolithic, layered, SOA, or microservices architecture, always prioritize modular design, maintainability, and scalability to ensure a robust and future-proof PHP web application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b13202da38c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Here is a step-by-step walkthrough to use Neo4j with PHP:]]></title>
            <link>https://medium.com/@.Chromax/here-is-a-step-by-step-walkthrough-to-use-neo4j-with-php-b4a699f80e9b?source=rss-e20f09a77d74------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a699f80e9b</guid>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[walkthrough]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Mohamed Ahmed]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 22:21:25 GMT</pubDate>
            <atom:updated>2023-08-25T22:21:25.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkNebQIboQqxdpbAhOzjhg.png" /></figure><p>Step 1: Install Neo4j</p><ul><li>Visit the Neo4j website (<a href="https://neo4j.com/">https://neo4j.com/</a>) and download the Community Edition for your operating system.</li><li>Follow the installation instructions provided for your specific OS.</li><li>Start the Neo4j server.</li></ul><p>Step 2: Install Neo4j PHP Driver</p><ul><li>Open your terminal or command prompt.</li><li>Install Composer if you haven’t already. Composer is a dependency manager for PHP.</li><li>Run the following command to create a new PHP project and generate the autoload file:</li></ul><pre>composer init --require=neo4j/neo4j &quot;dev-master&quot;</pre><ul><li>Install the Neo4j PHP driver using Composer:</li></ul><pre>composer require neo4j/neo4j</pre><p>Step 3: Connect to the Neo4j Database</p><ul><li>Create a new PHP file, e.g., index.php.</li><li>Add the following code to establish a connection to the Neo4j database:</li></ul><pre>&lt;?php <br>require_once &#39;vendor/autoload.php&#39;; <br>use Neo4j\Driver\GraphDatabase;<br><br>$uri = &quot;bolt://localhost:7687&quot;; <br>$driver = GraphDatabase::driver($uri, \Neo4j\Driver\Auth::basic(&quot;username&quot;, &quot;password&quot;)); <br>$session = $driver-&gt;session(); <br>?&gt;<br>// Make sure to replace `localhost` with the appropriate Neo4j server address, and `username` and `password` with your Neo4j credentials.</pre><ul><li>Perform Neo4j Database Operations:</li></ul><pre>// create new node<br>$session-&gt;run(&quot;CREATE (n:Person {name: &#39;John Doe&#39;})&quot;);</pre><ul><li>Retrieve nodes:</li></ul><pre>$result = $session-&gt;run(&quot;MATCH (n:Person) RETURN n.name AS name&quot;); <br>foreach ($result-&gt;records() as $record) {   <br>echo $record-&gt;get(&quot;name&quot;) . &quot;&lt;br&gt;&quot;; <br>}</pre><ul><li>Create relationships between nodes:</li></ul><pre>$session-&gt;run(&quot;MATCH (n:Person {name: &#39;John Doe&#39;}), (m:Person {name: &#39;Jane Smith&#39;}) CREATE (n)-[:FRIENDS]-&gt;(m)&quot;);</pre><p>Step 5: Close the Database Connection</p><ul><li>Add the following code at the end of your PHP script:</li></ul><pre>$session-&gt;close(); <br>$driver-&gt;close();</pre><p>That’s it! You now have a basic understanding of how to use Neo4j with PHP. You can further explore the <a href="https://neo4j.com/developer/php/">Neo4j PHP driver </a>documentation to learn about more advanced features and functionalities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a699f80e9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>