<?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 Refo on Medium]]></title>
        <description><![CDATA[Stories by Refo on Medium]]></description>
        <link>https://medium.com/@styles77?source=rss-fff277be7009------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yRsfbVvbhgjfr_O0KooHxA.png</url>
            <title>Stories by Refo on Medium</title>
            <link>https://medium.com/@styles77?source=rss-fff277be7009------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:47:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@styles77/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[Use This Package to Create Your Service, Action, and Interface classes]]></title>
            <link>https://medium.com/@styles77/use-this-package-to-create-your-service-action-and-interface-classes-36abafdf8a35?source=rss-fff277be7009------2</link>
            <guid isPermaLink="false">https://medium.com/p/36abafdf8a35</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Refo]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 13:45:11 GMT</pubDate>
            <atom:updated>2023-10-19T12:52:37.927Z</atom:updated>
            <content:encoded><![CDATA[<p>Well, as you may know, Laravel doesn’t have built-in support to create service, action, and interface classes.</p><p>So I made a simple package to create those classes with an artisan command like php artisan make:service {YourService}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbsolPbtrGBYAdEUs1lmqA.jpeg" /></figure><p>The package contains a tiny amount of code since I am just extending and overwriting some methods in the base class of GeneratorCommand in Laravel to create a controller, model, etc. with an artisan command.</p><p>You can install the package with the following command:</p><pre>composer require silverhand7/laravel-artisan-maker</pre><h4>Create a Service Class</h4><p>For example, if you want to create a user service class, here’s the command:</p><pre>php artisan make:service UserService</pre><p>The UserService class will be generated in App\Services\UserService.php.</p><p>Here’s an example output:</p><pre>&lt;?php<br><br>namespace App\Services;<br><br>class UserService <br>{<br>    //<br>}</pre><p>There’s also a way that you can create a service class together with the interface class, and the service will automatically implement the interface class. To do that, you can use the following command:</p><pre>php artisan make:service UserService -i UserServiceInterface</pre><p>If the interface class is not available, the package will ask you for permission to create the interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRfUQhJujS4VdqFgTfkzdQ.png" /></figure><p>Here’s an example output of a service class that implements an interface:</p><pre>&lt;?php<br><br>namespace App\Services;<br><br>use App\Contracts\UserServiceInterface;<br><br>class UserService implements UserServiceInterface<br>{<br>    //<br>}</pre><p>Please note that the interface class will be created in app\Contracts folder.</p><h4>Create an Action Class</h4><p>It is the same as what we’ve done previously you only need to change what type you want to make. For example:</p><pre>php artisan make:action UserStoreAction</pre><p>The action class will be created in app/Actions/UserStoreAction.php. Here’s the example output:</p><pre>&lt;?php<br><br>namespace App\Actions;<br><br>class UserStoreAction<br>{<br>    //<br>}</pre><p>Currently, there’s no support to apply an interface for an action class.</p><h4>Create an Interface Class</h4><p>Use the following command to create an interface class:</p><pre>php artisan make:interface UserServiceInterface</pre><p>The interface will be created in app\Contracts\UserServiceInterface.php. Here’s the example output:</p><pre>&lt;?php<br><br>namespace App\Contracts;<br><br>interface UserServiceInterface<br>{<br>    //<br>}</pre><h4>Customize the Created File Location</h4><p>There is also a way that you can customize your desired folder location for those classes. To do that, you need to publish the config file with the following command:</p><pre>php artisan vendor:publish --tag=artisan-maker-config</pre><p>Once you’ve done that, you can find the config file inconfig/artisan-maker.php and change the value according to your needs. Here&#39;s what the config file looks like:</p><pre>&lt;?php<br><br>return [<br>    /**<br>     * Set your default namespace for Service class<br>     */<br>    &#39;service_namespace&#39; =&gt; &#39;App\Services&#39;,<br><br>    /**<br>     * Set the default directory for your service class location<br>     */<br>    &#39;service_directory&#39; =&gt; &#39;app/Services&#39;,<br><br>    /**<br>     * Set your default namespace for Action class<br>     */<br>    &#39;action_namespace&#39; =&gt; &#39;App\Actions&#39;,<br><br>    /**<br>     * Set the default directory for your action class location<br>     */<br>    &#39;action_directory&#39; =&gt; &#39;app/Actions&#39;,<br><br>    /**<br>     * Set your default namespace for Interface class<br>     */<br>    &#39;interface_namespace&#39; =&gt; &#39;App\Contracts&#39;,<br><br>    /**<br>     * Set the default directory for your interface class location<br>     */<br>    &#39;interface_directory&#39; =&gt; &#39;app/Contracts&#39;,<br>];</pre><p>You can explore more about this package on the <a href="https://github.com/silverhand7/laravel-artisan-maker">Github repository</a>.</p><p>I would greatly appreciate it if you reported to me when you found a bug or error. Also, if you have any comments or feedback, please let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36abafdf8a35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilize Strategy Patterns and Dependency Injection in Laravel]]></title>
            <link>https://medium.com/@styles77/utilize-strategy-patterns-and-dependency-injection-in-laravel-178736a4eafb?source=rss-fff277be7009------2</link>
            <guid isPermaLink="false">https://medium.com/p/178736a4eafb</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Refo]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 05:30:34 GMT</pubDate>
            <atom:updated>2023-10-06T05:30:34.305Z</atom:updated>
            <content:encoded><![CDATA[<p>The strategy pattern can be used to enhance the extendability and maintainability of your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQDsmaCm6jrjfdqs2yhQcA.jpeg" /></figure><p>According to <a href="https://refactoring.guru/design-patterns/strategy">Refactoring Guru</a>, a strategy pattern is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.</p><p>If you want to learn more about definitives and study cases about strategy patterns, you can check out <a href="https://refactoring.guru/design-patterns/strategy">Refactoring Guru</a>.</p><p>I believe the easiest way to learn is by looking at real examples of how we can utilize this design pattern.</p><h3>Why and How to Use Strategy Pattern?</h3><p>Why do we need a strategy pattern? Let&#39;s say we have three different payment gateways, which are Stripe, Paypal, and Midtrans. Without strategy patterns, here&#39;s what the code would look like:</p><pre>namespace App\Services;<br><br>class PaymentGatewayService {<br>    public function process(string $paymentType, int $amount) {<br>        if ($paymentType === &#39;Paypal&#39;) {<br>            // Process payment with Paypal<br>        } else if ($paymentType === &#39;Stripe&#39;) {<br>            // Process payment with Stripe<br>        } else if ($paymentType === &#39;Midtrans&#39;) {<br>            // Process payment with Midtrans<br>        }<br>    }<br>}</pre><p>In the code above, I created a service class called PaymentGatewayService. This service handles all the payment processing logic, and it becomes more complex as you add more payment processing. This class becomes hard to maintain, and it violates the<a href="https://en.wikipedia.org/wiki/Single-responsibility_principle"> Single Responsibility Principle</a>.</p><h4>Let’s apply the case above using the strategy pattern in our Laravel project</h4><p>Firstly, I will create a new file in app/Contracts/PaymentGateway. Here&#39;s what the contract would look like:</p><pre>namespace App\Contracts;<br><br>interface PaymentGateway {<br>    public function processPayment(int $amount);<br>}</pre><p>Now, we’ll create a couple of new classes according to our supported payment gateways and implement the PaymentGateway contract above. I prefer to create a new folder for payment gateways. I’ll start with Paypal app/PaymentGateways/PaypalGateway.php</p><pre>namespace App\PaymentGateways;<br><br>use App\Contracts\PaymentGateway;<br><br>class PaypalGateway implements PaymentGateway<br>{<br>    public function processPayment(int $amount) {<br>        // Process payment using PayPal.<br>    }<br>}</pre><p>Next, Stripe app/PaymentGateways/StripeGateway.php</p><pre>namespace App\PaymentGateways;<br><br>use App\Contracts\PaymentGateway;<br><br>class StripeGateway implements PaymentGateway<br>{<br>    public function processPayment(int $amount) {<br>        // Process payment using Stripe.<br>    }<br>}</pre><p>And the last payment gateway is Midtrans app/PaymentGateways/MidtransGateway.php</p><pre>namespace App\PaymentGateways;<br><br>use App\Contracts\PaymentGateway;<br><br>class MidtransGateway implements PaymentGateway<br>{<br>    public function processPayment(int $amount) {<br>        // Process payment using Midtrans.<br>    }<br>}</pre><p>After all of these classes, how do we use them? Well, this is how you can utilize these classes. I’ll create a new service class called PaymentProcessorService to handle the incoming payment requests.</p><pre>namespace App\Services;<br><br>use App\Contracts\PaymentGateway;<br><br>class PaymentProcessorService<br>{<br>    private $gateway;<br><br>    public function __construct(PaymentGateway $gateway) {<br>        $this-&gt;gateway = $gateway;<br>    }<br><br>    public function processPayment($amount) {<br>        return $this-&gt;gateway-&gt;processPayment($amount);<br>    }<br>}</pre><p>In the code above, we accept the PaymentGateway interface or contract as a parameter in the constructor of PaymentProcessorService, meaning that any classes that implement this interface could be sent to this service and proceed with the payment according to the parameter.</p><p>Here’s an example of using Paypal as a payment gateway with PaymentProcessorService</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzXchkX6baRze6XDsiKYJQ.png" /><figcaption>Example of using Paypal payment gateway to payment processor service</figcaption></figure><h3>Strategy Pattern in Laravel</h3><p>I’ll give you another example. Let’s say we have an application that uses an external API to get a Bitcoin price. You can write it without a strategy pattern like this:</p><pre>class CoinMarketCap<br>{<br>    public function getBitcoinPrice(): float<br>    {<br>        // Call CoinMarketCap API<br><br>        return $bitcoinPrice;<br>    }<br>}</pre><p>And then use it in the controller, for example:</p><pre>class BitcoinPriceController extends Controller<br>{<br>    public function __invoke(<br>        CoinMarketCap $coinMarketCap<br>    ): JsonResponse {<br>        return response()-&gt;json([<br>            &#39;coin&#39; =&gt; &#39;Bitcoin&#39;,<br>            &#39;price&#39; =&gt; $coinMarketCap-&gt;getBitcoinPrice()<br>        ]);<br>    }<br>}</pre><p>Well, this code will be working as expected, but we have tightly coupled the CoinMarketCap class to the controller method. That means if we want to switch to another API, like CoinGecko API, we have to replace the codebase that uses the CoinMarketCap class with our new class.</p><p>In large projects, this can be a time-consuming and tedious task. So, to avoid this issue, instead of instantiating a class in the controller method, we can bind and resolve an interface by using the strategy pattern.</p><p>Let’s start by creating a new CryptocurrencyPrice interface:</p><pre>namespace App\Contracts;<br><br>interface CryptocurrencyPrice {<br>    public function getBitcoinPrice(): float;<br>}</pre><p>Now, we update our CoinMarketCap class to implement CryptocurrencyPrice interface:</p><pre>class CoinMarketCap implements CryptocurrencyPrice<br>{<br>    public function getBitcoinPrice(): float<br>    {<br>        // Call CoinMarketCap API<br><br>        return $bitcoinPrice;<br>    }<br>}</pre><p>And update our controller method to inject the interface rather than the class:</p><pre>class BitcoinPriceController extends Controller<br>{<br>    public function __invoke(<br>        CryptocurrencyPrice $cryptoCurrencyPrice<br>    ): JsonResponse {<br>        return response()-&gt;json([<br>            &#39;coin&#39; =&gt; &#39;Bitcoin&#39;,<br>            &#39;price&#39; =&gt; $cryptoCurrencyPrice-&gt;getBitcoinPrice()<br>        ]);<br>    }<br>}</pre><p>As you may know, we cannot instantiate an interface; we want to instantiate CoinMarketCap. To do that, we need to tell Laravel when we try to resolve the CryptocurrencyPrice interface to inject CoinMarketCap class by using a service provider.</p><p>Let’s create a new service provider using the following command:</p><pre>php artisan make:provider CryptocurrencyPriceServiceProvider</pre><p>Don’t forget to register this service provider in the config/app.php:</p><pre>&#39;providers&#39; =&gt; [<br>   ...<br>   App\Providers\CryptocurrencyPriceServiceProvider::class<br>],</pre><p>Now, we can make this service provider to bind the interface and the class:</p><pre>class CryptocurrencyPriceServiceProvider extends ServiceProvider<br>{<br>    public function register(): void<br>    {<br>        $this-&gt;app-&gt;bind(<br>            CryptocurrencyPrice::class,<br>            CoinMarketCap::class<br>        );<br>    }<br><br>    ...<br>}</pre><p>With the code above, whenever we inject the CryptocurrencyPrice interface, we will receive an object from the CoinMarketCap class that we can use.</p><h4>Binding Multiple Classes</h4><p>Back to our previous problem, we want to have the flexibility to switch between the API providers whether it’s CoinMarketCap or CoinGecko.</p><p>Let’s imagine that you already have the CoinGecko class that implements CryptocurrencyPrice like below:</p><pre>class CoinGecko implements CryptocurrencyPrice<br>{<br>    public function getBitcoinPrice(): float<br>    {<br>        // Call CoinGecko API<br><br>        return $bitcoinPrice;<br>    }<br>}</pre><p>Now we can update our service provider to change which class will be returned:</p><pre>class CryptocurrencyPriceServiceProvider extends ServiceProvider<br>{<br>    public function register(): void<br>    {<br>        $this-&gt;app-&gt;bind(<br>            CryptocurrencyPrice::class, function($app) {<br>                $driver = &#39;CoinGecko&#39;;<br><br>                if ($driver === &#39;CoinMarketCap&#39;) {<br>                    return new CoinMarketCap();<br>                }<br><br>                if ($driver === &#39;CoinGecko&#39;) {<br>                    return new CoinGecko();<br>                }<br><br>                throw new Exception(&#39;The driver is not found&#39;);<br>            }<br>        );<br>    }<br><br>    ...<br>}</pre><p>In the code above, you can change the value for the $driver variable to get from your config file.</p><p>Because both classes implement the same interface we can seamlessly switch between CoinMarketCap or CoinGecko without changing other parts of the code anywhere.</p><h3>Conclusion</h3><p>I hope this article has given you an overview of what the strategy pattern is, why we need to apply this pattern, and how you can utilize it in the Laravel app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=178736a4eafb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Multi-languages in Laravel Without Packages]]></title>
            <link>https://medium.com/@styles77/working-with-multi-languages-in-laravel-without-packages-b4dc8bfa9ab8?source=rss-fff277be7009------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4dc8bfa9ab8</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Refo]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 10:27:09 GMT</pubDate>
            <atom:updated>2023-10-04T02:07:42.744Z</atom:updated>
            <content:encoded><![CDATA[<p>Laravel has advantageous features for <a href="https://laravel.com/docs/10.x/localization#main-content">localization</a>. Let’s leverage this feature to build our app. We will not use any packages and make our own handler for translations, routes, models, and everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9twVLF8r-MgIV9oVIS64NQ.jpeg" /></figure><p>In this article, I will cover:</p><ol><li>Set up your supported languages.</li><li>Create multi-language routes.</li><li>Automatically translate the page into the selected language.</li><li>Design and implement a translatable database.</li></ol><p>Let’s get started.</p><h3>1. Set up your supported languages</h3><p>I have a fresh Laravel installed on my machine, and the first thing we will do is set up our supported languages. Create a new file in the config folder called languages.php.</p><pre>&lt;?php <br><br>return [<br>    &#39;en&#39;,<br>    &#39;pt&#39;,<br>    &#39;fr&#39;,<br>    &#39;jp&#39;<br>];</pre><p>Done. Now we will use this config file to work across the app.</p><h3>2. Create multi-language routes</h3><p>According to the Laravel’s <a href="https://laravel.com/docs/10.x/localization#publishing-the-language-files">documentation</a>: “<em>By default, the Laravel application skeleton does not include the lang directory. If you would like to customize Laravel’s language files or create your own, you should scaffold the lang directory via the lang:publish Artisan command.</em>”</p><pre>php artisan lang:publish</pre><p>Now, let’s create routes that support all languages. We will loop through the supported languages to create unique routes for every language.</p><p>But before that, let’s create some folders for our supported languages in the lang directory. I will name the file paths.php since it will store all of our route paths.</p><p>The folder will look something like this:</p><pre>├── lang/       <br>│   ├── en/<br>│   │   ├── paths.php<br>│   ├── fr/<br>│   │   ├── paths.php<br>│   ├── jp/<br>│   │   ├── paths.php<br>│   ├── pt/<br>│   │   ├── paths.php</pre><p>The content inside the paths.php is:</p><p><em>lang/en/paths.php</em></p><pre>&lt;?php<br>return [<br>    &#39;about&#39; =&gt; &#39;about&#39;,<br>];</pre><p><em>lang/fr/paths.php</em></p><pre>&lt;?php<br>return [<br>    &#39;about&#39; =&gt; &#39;a-propos&#39;,<br>];</pre><p><em>lang/jp/paths.php</em></p><pre>&lt;?php<br>return [<br>    &#39;about&#39; =&gt; &#39;about&#39;,<br>];</pre><p><em>lang/pt/paths.php</em></p><pre>&lt;?php<br>return [<br>    &#39;about&#39; =&gt; &#39;sobre&#39;,<br>];</pre><p>Now, we’ll define our routes in web/routes.php:</p><pre>foreach (config(&#39;languages&#39;) as $locale) {<br>    if (config(&#39;app&#39;)[&#39;locale&#39;] == $locale) {<br>        Route::get(__(&#39;paths.about&#39;, [], $locale), AboutController::class)-&gt;name(&quot;about.{$locale}&quot;);<br>    } else {<br>        Route::get(&quot;{$locale}/&quot;.__(&#39;paths.about&#39;, [], $locale), AboutController::class)-&gt;name(&quot;about.{$locale}&quot;);<br>    }<br>}</pre><p>In the code above, you will register some new routes for all available languages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*Tdkdx1_jw2ZcqXGQrvl5IQ.png" /></figure><p>If you want to access the path in the English version use /about but if you want to access the path in other languages use /pt/sobre for example.</p><h3>3. Automatically translate the page into the selected language</h3><p>Now, you probably notice that, when you access the page, the translation won’t be applied. That’s because we haven’t set our locale according to the path.</p><p>Let’s create a middleware to translate the page into the selected locale.</p><pre>php artisan make:middleware SetLocale</pre><p>Paste the following code for the handle method in the app/Http/Middleware/SetLocale.php</p><pre>public function handle(Request $request, Closure $next): Response<br>{<br>    $lang = $request-&gt;segment(1);<br><br>    if(strlen($lang) === 2 &amp;&amp; in_array($lang, config(&#39;languages&#39;))){<br>        app()-&gt;setLocale($lang);<br>    }<br><br>    return $next($request);<br>}</pre><p>The code above will set the language according to segment 1 in the request, if segment 1 is equal to our supported languages we will set it as the current language.</p><p>Now register the middleware in the app/Http/Kernel.php</p><pre>protected $routeMiddleware = [<br>    ...<br>    &#39;set-locale&#39; =&gt; \App\Http\Middleware\SetLocale::class,<br>];</pre><p>Update our routes to use the middleware:</p><pre>Route::group([<br>    &#39;middleware&#39; =&gt; &#39;set-locale&#39;<br>], function() {<br>    foreach (config(&#39;languages&#39;) as $locale) {<br>        if (config(&#39;app&#39;)[&#39;locale&#39;] == $locale) {<br>            Route::get(__(&#39;paths.about&#39;, [], $locale), AboutController::class)-&gt;name(&quot;about.{$locale}&quot;);<br>        } else {<br>            Route::get(&quot;{$locale}/&quot;.__(&#39;paths.about&#39;, [], $locale), AboutController::class)-&gt;name(&quot;about.{$locale}&quot;);<br>        }<br>    }<br>});</pre><p>After that, we are ready to print the page according to the selected language. For example, I have a very simple controller that prints “Hello World” using Laravel Localization.</p><pre>class AboutController extends Controller<br>{<br>    public function __invoke(Request $request)<br>    {<br>        return __(&quot;general.hello_world&quot;);<br>    }<br>}</pre><p>Before we see the output, we need to create new translation files called “general” for all languages. If you don’t create for all languages, the fallback language will be using the English version.</p><pre>├── lang/       <br>│   ├── en/<br>│   │   ├── general.php<br>│   │   ├── paths.php<br>│   ├── fr/<br>│   │   ├── general.php<br>│   │   ├── paths.php<br>│   ├── jp/<br>│   │   ├── general.php<br>│   │   ├── paths.php<br>│   ├── pt/<br>│   │   ├── general.php<br>│   │   ├── paths.php</pre><p><em>lang/en/general.php</em></p><pre>&lt;?php<br>return [<br>    &#39;hello_world&#39; =&gt; &#39;Hello World&#39;,<br>];</pre><p><em>lang/fr/paths.php</em></p><pre>&lt;?php<br>return [<br>    &#39;hello_world&#39; =&gt; &#39;Bonjour le monde&#39;,<br>];</pre><p>You can continue to apply this to the rest of the language.</p><p>Let’s see how it looks when the page is rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*_dTAweJICep1sBUJby4aYA.png" /><figcaption>English Version</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*hHX3PTnM68Eyzc136i9R6w.png" /><figcaption>French Version</figcaption></figure><p>Now you know how to leverage this localization feature for the real project.</p><h3>4. Design and implement a translatable database</h3><p>Let&#39;s say you have normal tables for categories and posts with the following structure:</p><pre>categories<br>- id<br>- name<br>- slug</pre><pre>posts<br>- id<br>- category_id<br>- title<br>- slug<br>- content</pre><p>I know that you can simply add a locale or language column in both tables, but that will cause inconsistency for the category_id. For example:</p><pre>categories<br><br>id: 1<br>name: &quot;News EN&quot;<br>slug: &quot;news-en&quot;<br>locale: &quot;en&quot;<br><br>id: 2<br>name: &quot;Nouvelles&quot;<br>slug: &quot;nouvelles&quot;<br>locale: &quot;fr&quot;</pre><pre>posts<br><br>id: 1<br>category_id: 1<br>title: &quot;Post English&quot;<br>slug: &quot;post-english&quot;<br>locale: &quot;en&quot;<br>content: &quot;Content post in English&quot;<br><br>id: 2<br>category_id: 2<br>title: &quot;Post France&quot;<br>slug: &quot;post-france&quot;<br>locale: &quot;fr&quot;<br>content: &quot;Content post in France&quot;</pre><p>As you can see in the plain text above, both categories cover the same meaning, which is “News” but they have different IDs. If you change the category_id for “Post France” to 1, it will cause a problem because the France post is referenced to the English category.</p><p>Let’s solve that problem by creating a third table for categories called category_translations and changing some columns in the categories table.</p><pre>categories<br>- id</pre><pre>category_translations<br>- id<br>- category_id<br>- name<br>- slug</pre><p>Implement new table structure:</p><pre>categories<br><br>id: 1</pre><pre>category_translations<br><br>id: 1<br>category_id: 1<br>name: &quot;News EN&quot;<br>slug: &quot;news-en&quot;<br>locale: &quot;en&quot;<br><br>id: 2<br>category_id: 1<br>name: &quot;Nouvelles&quot;<br>slug: &quot;nouvelles&quot;<br>locale: &quot;fr&quot;</pre><pre>posts<br><br>id: 1<br>category_id: 1<br>title: &quot;Post English&quot;<br>slug: &quot;post-english&quot;<br>locale: &quot;en&quot;<br>content: &quot;Content post in English&quot;<br><br>id: 2<br>category_id: 1<br>title: &quot;Post France&quot;<br>slug: &quot;post-france&quot;<br>locale: &quot;fr&quot;<br>content: &quot;Content post in France&quot;</pre><p>Now both posts are referenced to the same ID and we can display the category in English or French.</p><h4>Let’s Code it in Laravel</h4><p>I will focus on how we take advantage of the Laravel Relationship for categories and category_translations.</p><p>First, we define the migration files:</p><pre>php artisan make:migration create_categories_table</pre><pre>Schema::create(&#39;categories&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;timestamps();<br>});</pre><pre>php artisan make:migration create_category_translations_table</pre><pre>Schema::create(&#39;category_translations&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;foreignId(&#39;category_id&#39;);<br>    $table-&gt;string(&#39;name&#39;);<br>    $table-&gt;string(&#39;slug&#39;);<br>    $table-&gt;string(&#39;locale&#39;);<br>    $table-&gt;timestamps();<br>});</pre><p>If you don’t know how to make a migration, check out this <a href="https://laravel.com/docs/10.x/migrations#introduction">documentation</a>.</p><p>Now, let’s create our models:</p><pre>php artisan make:model Category</pre><pre>php artisan make:model CategoryTranslation</pre><p>We will give our Category model access to the CategoryTranslation by creating a relationship:</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Database\Eloquent\Model;<br><br>class Category extends Model<br>{<br>    use HasFactory;<br><br>    protected $fillable = [<br>        &#39;id&#39;,<br>    ];<br><br>    public function translations()<br>    {<br>        return $this-&gt;hasMany(CategoryTranslation::class);<br>    }<br><br>    public function en()<br>    {<br>        return $this-&gt;hasOne(CategoryTranslation::class)-&gt;where(&#39;locale&#39;, &#39;en&#39;);<br>    }<br><br>    public function fr()<br>    {<br>        return $this-&gt;hasOne(CategoryTranslation::class)-&gt;where(&#39;locale&#39;, &#39;fr&#39;);<br>    }<br><br>    public function pt()<br>    {<br>        return $this-&gt;hasOne(CategoryTranslation::class)-&gt;where(&#39;locale&#39;, &#39;pt&#39;);<br>    }<br><br>    public function jp()<br>    {<br>        return $this-&gt;hasOne(CategoryTranslation::class)-&gt;where(&#39;locale&#39;, &#39;jp&#39;);<br>    }<br>}</pre><p>In the code above, when you select a single category, you can access the English version of the category using $category-&gt;en as well as other versions like $category-&gt;fr, $category-&gt;jp, etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*8DNTF-pl8MVN3OIQNHr4iA.png" /></figure><p>And you can also be able to access the whole version of the category translations using $category-&gt;translations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60hrUL4X5oMQJl2oAKw8vA.png" /></figure><h4>Conclusion</h4><p>Well, I think that’s all from me. I believe that now you get the idea of how we can leverage the Laravel Localization feature for your real project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4dc8bfa9ab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Clean Up Your Laravel Controller and Implement DTO]]></title>
            <link>https://medium.com/@styles77/lets-clean-up-your-laravel-controller-and-implement-dto-a67c44bf5bb6?source=rss-fff277be7009------2</link>
            <guid isPermaLink="false">https://medium.com/p/a67c44bf5bb6</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[data-transfer-object]]></category>
            <dc:creator><![CDATA[Refo]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 13:29:27 GMT</pubDate>
            <atom:updated>2023-10-10T02:45:50.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyGrXO1CtmCzpfMzuSDuGA.jpeg" /></figure><p>Have you ever wondered why, when you write a controller in Laravel, it can sometimes be bloated with so many logical operations? You know that it is working, but you also realize that it’s getting harder to maintain the project in the future, and there is also so much copy-pasting, especially for the store and update methods.</p><p>If your controller looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQ4Ui9wSGkRfIKI6QmNI3w.png" /></figure><p>I’m not saying that is wrong, but in my opinion, there are many ways that we can optimize it. I’ll show you a couple of ways that I commonly use to simplify the controller and separate the logic to make it easier to maintain in the future. In this article, we will focus on improving the store method.</p><h3>Step 1: Create a Form Request to handle the validation</h3><p>The first thing we can do is leave the validation out of the controller and move it into a <a href="https://laravel.com/docs/10.x/validation#form-request-validation">form request</a>. To create a form request class, you may use the php artisan make:request Artisan CLI command:</p><pre>php artisan make:request ArticleStoreRequest</pre><p>With the command above, you will have created a new file in app/Http/Requests/ArticleStoreRequest.php</p><p>For simplicity, I will assume that every request is always authorized, so we will set the authorize() method to true. Now let’s put our logic for validation in the rules() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8y3Pk2nn4kXhuIuawW06Gw.png" /></figure><p>Now, let’s update our controller, we removed the validation in the controller and used ArticleStoreRequest, so that the request will be handled by ArticleStoreRequest before landing on the controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXACysB_ZxuuAmagOSs1oQ.png" /></figure><h3>Step 2: Move the common logic into Action or Service class</h3><p>We could move our common logic into a separate action or service class. In this case, we will move our logic for inserting data and uploading processes into an action class.</p><p>We will create a new file inapp/Actions/ArticleStoreAction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVkZkCfQsZGuXry2_5NmQA.png" /></figure><p>Now, let’s update the controller to use the new action class that we created above. I believe our controller will look cleaner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLKQ4W0CqLTxfNsmiGVrYA.png" /></figure><p>You can see that we’ve successfully moved the business logic from the controller function into the action. Controllers serve as the “glue” that holds our requests and responses together. So, by maintaining logical separation between the code, we were able to lessen the cognitive load required to grasp what a method accomplishes.</p><h3>Step 3: Implementing DTO with Actions</h3><p>What if you have an API to store an article that accepts different fields than you have in the ArticleStoreAction , for example in the API request changes the column name from content to content_data ? But the technical requirement forces you to use the same ArticleStoreAction in both web and API requests.</p><p>We can solve this problem by using <a href="https://github.com/spatie/data-transfer-object">DTO</a> (data transfer object). To use DTOs in our project, we’ll use Spatie’s spatie/data-transfer-object package. To install the package use the following command:</p><pre>composer require spatie/data-transfer-object</pre><p>After the package is installed, let’s create a DTO by creating a new file in App\DataTransferObjects\ArticleStoreDTO</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bgh800JrC0VHSPQeK5oJ4A.png" /></figure><p>Next, let’s implement our ArticleStoreDTO to our ArticleStoreRequest by creating a new method called ToDTO()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FvJ1UyhJGONZD76udVD8A.png" /></figure><p>After that, let’s update our controller to pass the DTO to the action class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uszDYbknGDP8G3eZlYPxlA.png" /></figure><p>Now let’s change the ArticleStoreAction to accept our DTO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjJV1N4MMp2sa8F7dEcmMQ.png" /></figure><p>As you can see on the code above, we will set the value for our record that comes from the DTOs.</p><p>Now back to our previous problem, how if we want to implement ArticleStoreAction to the API request that has a different column name for content to content_data?</p><p>It’s very simple, there are many ways to accomplish that, one of them is to create a new request and assign the content_data field to the DTO content field like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fem6r6OcVNYNUA9zeZXhgQ.png" /></figure><p>As long as the ArticleStoreAction accepts valid data from DTO, everything will be fine.</p><p>These are highly helpful techniques to decouple data so that it can be sent across the code of your system without being tied to anything (in this case, the request).</p><p>You can now use that logic in many locations without having to duplicate your code, which is yet another fantastic advantage of isolating your business logic into services or action classes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a67c44bf5bb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring httprouter — Go Package for HTTP Router]]></title>
            <link>https://medium.com/@styles77/exploring-httprouter-go-package-for-http-router-af1a22c69f31?source=rss-fff277be7009------2</link>
            <guid isPermaLink="false">https://medium.com/p/af1a22c69f31</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Refo]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 22:44:26 GMT</pubDate>
            <atom:updated>2023-09-20T22:44:26.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring httprouter — Go Package for HTTP Router</h3><p>If you have been working with the built-in HTTP router in Go (ServeMux), you will notice that there are a lot of limitations, such as:</p><ul><li>Limited support for routing parameters.</li><li>Defining complex URL patterns could be challenging.</li><li>Not fully support HTTP Methods (GET, POST, PUT, etc.).</li><li>Lack of Built-in Route naming, and many more</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x_M-W_l_dooW4xN3VNPBQA.jpeg" /></figure><p>In this article, we will explore one of the most popular packages for HTTP Router in Go, which is <a href="https://github.com/julienschmidt/httprouter">julienschmidt/httprouter</a>. The reason I want to explore this package is because it is very lightweight, fast, and straight to the point, focusing only on routing and nothing more.</p><p>In this article, we will cover:</p><ol><li>Installing httprouter in the Go project</li><li>Introduction to httprouter.Handle</li><li>Defining URL paths with and without parameters</li><li>Creating GET and POST requests</li><li>Serving File</li></ol><h3>1. Installing httprouter in the Go project</h3><p>Let’s create a new folder and initialize the Go project by writing go mod init. Now let’s add the package to the project using the following command:</p><pre>go get github.com/julienschmidt/httprouter</pre><p>After the installation is complete, you can check the go.mod file to see if the package julienschmidt/httprouter has been installed.</p><h3>2. Introduction to httprouter.Handle</h3><p>When we’re using ServeMux, we can use http.Handler to add a new route, but with httprouter, we don’t need http.Handler anymore; instead, we are going to use httprouter.Handle. With httprouter.Handle, we will get the third parameter that we can use as a parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKAUb14ueiYAkf5Gz20mbA.png" /></figure><p>Params is the place where we can store the parameters that are sent from the client side. Please note that the Params is not a query parameter but the parameter in the URL, for example: /products/:id the id will be stored in the Params.</p><h3>3. Defining URL path</h3><p>Firstly, to make this tutorial make more sense, I would like to declare some data that we will use throughout this tutorial. In this case, I will create a struct called Products and a variable products and add a couple of data into it.</p><pre>type Product struct {<br> Id    int<br> Name  string<br> Price int<br>}<br><br>var products []Product = []Product{<br> {<br>  Id:    1,<br>  Name:  &quot;Mouse&quot;,<br>  Price: 500,<br> },<br> {<br>  Id:    2,<br>  Name:  &quot;Keyboard&quot;,<br>  Price: 700,<br> },<br> {<br>  Id:    3,<br>  Name:  &quot;Monitor&quot;,<br>  Price: 2000,<br> },<br>}</pre><p>Now, we initiate httprouter.New() into a variable route , and then we add the URL path to the router. In the example below, we have two paths, which are / and /products.</p><pre>func main() {<br>  router := httprouter.New()<br><br>  router.GET(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {<br>    fmt.Fprint(w, &quot;Hello World&quot;)<br>  })<br><br>  router.GET(&quot;/products&quot;, func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {<br>    for i := 0; i &lt; len(products); i++ {<br>      fmt.Fprintf(w, products[i].Name+&quot;\n&quot;)<br>    }<br>  })<br><br>  server := http.Server{<br>    Handler: router,<br>    Addr:    &quot;localhost:8080&quot;,<br>  }<br><br>  server.ListenAndServe()<br>}</pre><p>The output / will be “Hello World” and the output /products will be the list of the product’s name.</p><p>Now let’s try adding a parameter to the route and displaying the data according to the parameter.</p><pre>router.GET(&quot;/products/:id&quot;, func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {<br>  for i := 0; i &lt; len(products); i++ {<br>   if strconv.Itoa(products[i].Id) == p.ByName(&quot;id&quot;) {<br>    fmt.Fprintf(w, &quot;Product: &quot;+products[i].Name)<br>   }<br>  }<br> })</pre><p>We accept the third parameter p from the client and name it as id . If you visit/products/1 you will see product ID 1, which is Mouse.</p><h3>4. Creating POST method URL</h3><p>We used the GET method in our previous example. Making a POST URL is very easy, we only need to change the GET to POST when declaring the path.</p><pre>router.POST(&quot;/products&quot;, func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {<br>  price, _ := strconv.Atoi(r.PostFormValue(&quot;price&quot;))<br>  product := Product{<br>   Id:    len(products) + 1,<br>   Name:  r.PostFormValue(&quot;name&quot;),<br>   Price: price,<br>  }<br><br>  products = append(products, product)<br><br>  for i := 0; i &lt; len(products); i++ {<br>   fmt.Fprintf(w, products[i].Name+&quot;\n&quot;)<br>  }<br> })</pre><p>In the code above, we store the input value from the client and add it to the products variable. You will see the additional data from the input at the bottom of the list.</p><h3>5. Serving File</h3><p>Another interesting thing that you can do with this package is that you can serve your static file easily using `ServeFiles(Path, FileSystem)`. FileSystem can manually load from a folder or use Golang Embed.</p><pre>dir, _ := fs.Sub(resources, &quot;resources&quot;)<br>router.ServeFiles(&quot;/files/*filepath&quot;, http.FS(dir))</pre><p>With that code above, you can access your file inside the “resources” folder using the “/files” path, for example, localhost:8080/files/hello.txt.</p><h3>Closing</h3><p>That’s all from me, after you read this article, I believe you will be able to use the basics of the httprouter package in Golang, and have enough foundation to explore other features that the package has.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af1a22c69f31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding The Basic of Time Complexity with Examples]]></title>
            <link>https://medium.com/@styles77/understanding-the-basic-of-time-complexity-with-examples-238f87f3f519?source=rss-fff277be7009------2</link>
            <guid isPermaLink="false">https://medium.com/p/238f87f3f519</guid>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Refo]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 16:05:28 GMT</pubDate>
            <atom:updated>2023-09-02T16:05:28.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Time complexity is one of the most important things to understand in order to write efficient and reliable algorithms. When I first explored this topic, I was confused and didn&#39;t fully understand it since I’m a complete beginner. In this article, I will share with you how I can easily understand time complexity, and you surely will too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1KsvCTHmrW8VwsESM-23g.jpeg" /></figure><h3>What is time complexity?</h3><p>Time complexity is how long it takes for an algorithm to be executed with certain inputs. This is also known as <strong>Big-O Notation</strong>. Big-O Notation is used to measure how complex an algorithm is.</p><h3>What is Big-O Notation?</h3><p>Big-O notation is a way of expressing an algorithm’s overall steps in algebraic terms while eliminating lower-order constants and coefficients that don’t affect the problem’s overall complexity. Here are some common notations you might encounter:</p><h4>O(1): Constant Time</h4><p>Given an input of size n, it will always take a single step to complete the algorithm. Example:</p><pre>array := []int{1, 2, 3, 4, 5, 6, 7}<br><br>func getFirstElement(array []int) int {<br>  return array[0]<br>}</pre><p>It always takes one step to complete, no matter how much input there is.</p><h4>O(n): Linear Time</h4><p>An algorithm with linear time complexity has a running time that is directly proportional to the input size.</p><pre>n := 8;<br>for i := 1; i &lt;= n; i++ {<br>    fmt.Println(&quot;Hello World&quot;);<br>}</pre><h4>O(log n): Logarithmic Time</h4><p>When you give an input n into a function, the number of steps that it takes to complete the task is decreased by some factor with each step.</p><pre>n := 8;<br>for i := 1; i &lt;= n; i*=2 {<br>    fmt.Println(&quot;Hello World&quot;);<br>}</pre><p>The output will be “Hello World” printed 4 times because the “i” is multiplied by 2 on each iteration.</p><h4>O(n²): Quadratic Time</h4><p>Quadratic time complexity indicates that the running time of an algorithm grows quadratically with the input size. Nested loops and algorithms that involve comparing all pairs of elements in the input often result in this time complexity.</p><pre>n := 5<br>for i := 0; i &lt; n; i++ {<br>    for j := 0; j &lt; n; j++ {<br>        fmt.Println(i, j)<br>    }<br>}</pre><h4>O(2^n): Exponential Time</h4><p>Algorithms with exponential time complexity grow rapidly with the input size. They are generally impractical for all but the smallest inputs. Recursive algorithms with exponential time complexity are those that produce all subsets or permutations of a set.</p><pre>func fibonacci(n int) int {<br>    if n &lt;= 1 {<br>        return n<br>    }<br>    return fibonacci(n-1) + fibonacci(n-2)<br>}<br><br>func main() {<br>    n := 10<br>    result := fibonacci(n)<br>    fmt.Printf(&quot;F(%d) = %d\n&quot;, n, result)<br>}</pre><p>In this example, the fibonacci function recursively computes the nth Fibonacci number by adding the (n-1)th and (n-2)nd Fibonacci numbers. This recursive approach leads to an exponential increase in the number of function calls and calculations as n grows.</p><h3>Conclusion</h3><p>With the understanding of Big-O Notation, we can easily identify which algorithm performs better that we can use in our problem.</p><p>I think that’s from me about the basics of time complexity. There are more examples and types of Big-O notations that I didn’t cover here because I think that is too complex for beginners.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238f87f3f519" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>