<?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"><channel><title><![CDATA[Building Portfolio Apps]]></title><description><![CDATA[Building Portfolio Apps]]></description><link>https://codewitholgun.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 11 May 2026 17:37:25 GMT</lastBuildDate><atom:link href="https://codewitholgun.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Ultimate Guide to Setting Up a Web Development Environment on Linux Ubuntu 24 LTS]]></title><description><![CDATA[Last week, I encountered issues with my existing Ubuntu setup. It was slow and lagging, and I couldn't resolve the problem. Then, I remembered that my laptop had two operating systems installed: Windows and Linux on separate partitions. Suspecting a ...]]></description><link>https://codewitholgun.com/ultimate-guide-to-setting-up-a-web-development-environment-on-linux-ubuntu-24-lts</link><guid isPermaLink="true">https://codewitholgun.com/ultimate-guide-to-setting-up-a-web-development-environment-on-linux-ubuntu-24-lts</guid><category><![CDATA[Linux]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[nginx]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Crowdstrike]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Mon, 22 Jul 2024 15:19:08 GMT</pubDate><content:encoded><![CDATA[<p>Last week, I encountered issues with my existing Ubuntu setup. It was slow and lagging, and I couldn't resolve the problem. Then, I remembered that my laptop had two operating systems installed: Windows and Linux on separate partitions. Suspecting a bug in CrowdStrike, I checked the Windows partition but realized I hadn't used Windows in a long time and didn't need it.</p>
<p>Since I was having problems with my Ubuntu setup, I decided to download the latest version of Ubuntu from the official website. I created a bootable flash disk, backed up my important files, and restarted my laptop. I deleted all partitions for a clean install and installed Ubuntu 24 LTS.</p>
<p>It had been a long time since I set up my web development environment from scratch, so I decided to document the process.</p>
<p>You can find the entire setup process below:</p>
<h4 id="heading-requirements-for-web-development-with-php-nginx-and-mysql">Requirements for Web Development with PHP, Nginx, and MySQL</h4>
<ul>
<li><p>Latest PHP (8.3 at the time of writing this)</p>
</li>
<li><p>Composer (to install PHP dependencies)</p>
</li>
<li><p>Nginx</p>
</li>
<li><p>MySQL</p>
</li>
<li><p>NodeJS (to install NPM packages)</p>
</li>
<li><p>PNPM (I decided to use this for my new setup)</p>
</li>
<li><p>Git Client</p>
</li>
</ul>
<h2 id="heading-before-installation">Before installation</h2>
<p>I always update my OS before installing anything to ensure all dependencies are up-to-date. Here are the commands I used:</p>
<pre><code class="lang-plaintext">sudo apt update # Update OS packages
sudo apt upgrade # Upgrade OS packages if any needed
sudo apt autoremove # Remove any unnecessary packages
sudo apt autoclean # Clean any broken, or already removed packages
</code></pre>
<h2 id="heading-install-php">Install PHP</h2>
<p>It's straightforward to install PHP on Ubuntu. The following command installs PHP and the required extensions:</p>
<p>Since current up to date PHP version is 8.3, it will install it and all dependencies automatically.</p>
<p>We also need <strong>unzip</strong> and <strong>curl</strong> extensions since we will download something from internet, unzip it to install.</p>
<pre><code class="lang-plaintext">sudo apt install php-cli unzip curl
</code></pre>
<h2 id="heading-install-composer">Install Composer</h2>
<p>Composer is a package management tool for PHP and we can install all dependent packages with it easily without spending a lots of time.</p>
<p>So, I decided to install it globally to my system thus I don't need to run it with <strong>root</strong> user which is not <strong>suggested</strong> by composer itself too.</p>
<p>First of all I needed to download it, so I run following command.</p>
<pre><code class="lang-plaintext">curl -sS https://getcomposer.org/installer -o composer-setup.php
</code></pre>
<p>Then, I needed to verify if downloaded setup file is correct one so I run following commands to verify it which is also officially documented in the composer's website.</p>
<pre><code class="lang-plaintext">HASH=`curl -sS https://composer.github.io/installer.sig`
php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
</code></pre>
<p>After I've been sure that it's valid file, I run following command to install it globally so every user in the system can use it, not only <strong>root.</strong></p>
<pre><code class="lang-plaintext">sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
</code></pre>
<p>Installation done, and I just check if it's really works with my normal user by running following command. Of course I had to open a new terminal otherwise it doesn't work :)</p>
<pre><code class="lang-plaintext">composer --version
</code></pre>
<h2 id="heading-install-nginx">Install Nginx</h2>
<p>I really like the simplicity and event-driven architecture of Nginx so, I prefer it over Apache to run my PHP projects.</p>
<p>Event-driven architecture makes it much performant reverse-proxy than Apache and you can feel the advantages of it on big projects.</p>
<p>I run following command to install it on my machine.</p>
<pre><code class="lang-plaintext">sudo apt install nginx
</code></pre>
<p>After installation completed I run following commands to make sure it's running.</p>
<p>Also following <strong>enable</strong> command make it as systemd program so whenever computer is restarted nginx automatically starts to run.</p>
<pre><code class="lang-plaintext">sudo systemctl start nginx
sudo systemctl enable nginx # enables it to run as default program
</code></pre>
<h2 id="heading-install-mysql">Install MySQL</h2>
<p>MySQL is always my go to database whenever I start new project however nowadays I am thinking to go with SQLite as a first-hand database.</p>
<p>But, I'll be think about that on other projects :)</p>
<p>To install MySQL I run following command.</p>
<pre><code class="lang-plaintext">sudo apt install mysql-server
</code></pre>
<p>After it's installed I needed to put a password for my <strong>root</strong> user in database, so I run following command to do that.</p>
<p>It asks many easy to followup questions and I fill them up according to my setup however you can select the ones most fits you.</p>
<pre><code class="lang-plaintext">sudo mysql_secure_installation
</code></pre>
<p>Sometimes that doesn't work enough, and I always try to change password after I connect to database as a <strong>root</strong> Linux user, so I run following command to connect it.</p>
<pre><code class="lang-plaintext">sudo mysql
</code></pre>
<p>After I connected to the MySQL database via terminal, I run following commands to change the <strong>root</strong> user password.</p>
<pre><code class="lang-plaintext">ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'my_lovely_password';
FLUSH PRIVILEGES;
</code></pre>
<p>At this point, MySQL is running and I changed the password of <strong>root</strong> user for database so I could go to next step to install <strong>NodeJS</strong> which I'll be use alongside PHP.</p>
<h2 id="heading-install-nodejs">Install NodeJS</h2>
<p>It's actually becomes so much easier to install NodeJS than 2-3 years ago. So, I just run following commands to install it.</p>
<p>This commands are in the official documentation of NodeJS, so you can read about them at following link;</p>
<p><a target="_blank" href="https://nodejs.org/en/download/package-manager">https://nodejs.org/en/download/package-manager</a></p>
<pre><code class="lang-plaintext"># installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 20

# verifies the right Node.js version is in the environment
node -v # should print `v20.15.1`

# verifies the right npm version is in the environment
npm -v # should print `10.7.0`
</code></pre>
<p>At this point in my Linux environment I've had NodeJS + NPM running but I decided to try something else instead of <strong>npm</strong> because I've seen that packages that I install with <strong>npm</strong> really takes a lot of size on my disk.</p>
<p>So, I found that <strong>pnpm</strong> works a little bit different than <strong>npm</strong>, which essentially installs all <strong>packages</strong> into the storage but if another project requires the same package then it doesn't install it again, instead uses <strong>symbolic link</strong> to run it through project.</p>
<p>So, I installed globally with following command.</p>
<pre><code class="lang-plaintext">npm install -g pnpm
</code></pre>
<p>And from now on, I started to use <strong>pnpm install</strong> command instead of <strong>npm install</strong> and I am really happy with that :)</p>
<p>I almost completed all setup, except <strong>git client</strong> which is very important for me because I really like to use <strong>GitHub</strong> and <strong>GitLab</strong> to keep different versions of my projects by creating different branches, making pull requests, writing good comments and pushing to my production server via single line of command <strong>git pull</strong></p>
<p>So, I needed to install <strong>git</strong>.</p>
<h2 id="heading-install-git-client">Install Git Client</h2>
<p>It's actually very straight forward to install <strong>git</strong> on Linux, I just had to run following command to install <strong>client</strong>.</p>
<pre><code class="lang-plaintext">sudo apt install git
</code></pre>
<p>Then I setup my <strong>global</strong> git user information with following commands.</p>
<pre><code class="lang-plaintext">git config --global user.name "Your Name"
git config --global user.email "you@example.com"
</code></pre>
<p>After that point, I just needed one more thing to install <strong>PHP-FPM</strong>.</p>
<p>I need to install it because Nginx requires PHP-FPM to load configuration files for the PHP projects.</p>
<h2 id="heading-install-php-fpm">Install PHP-FPM</h2>
<p>I just run following command to install it.</p>
<pre><code class="lang-plaintext">sudo systemctl restart php8.3-fpm
</code></pre>
<p>That installed PHP-FPM for PHP8.3 however if you have different version of PHP on your computer you needed to install right version.</p>
<p>And finally I completed my setup :)</p>
<h2 id="heading-follow-me">Follow Me :)</h2>
<p>You can follow me on X/Twitter at; <a target="_blank" href="https://x.com/codewitholgun">https://x.com/codewitholgun</a></p>
<h4 id="heading-domains">Domains</h4>
<p>I have some domains that I don't use anymore and want to sell them. You can find the domains list in following link.</p>
<p><a target="_blank" href="https://dan.com/domain-seller/domain-seller-799eece2-55fa-4ba5-8d70-7ff99c8d2e5c?&amp;results=50&amp;order_by=relevance">List Here</a>  </p>
<p>You can reach out me If you interested with one.</p>
]]></content:encoded></item><item><title><![CDATA[How to use Computed Property Names in console.log?]]></title><description><![CDATA[Introduction
If you want to learn about how to use console.log as a professional developer then you have to learn computer property names.
Let's Start
Assume that we have 4 different objects and each one is assigned to a variable. How can we log thos...]]></description><link>https://codewitholgun.com/how-to-use-computed-property-names-in-consolelog</link><guid isPermaLink="true">https://codewitholgun.com/how-to-use-computed-property-names-in-consolelog</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[console.log]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Wed, 01 May 2024 22:41:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xkBaqlcqeb4/upload/3b89e4d2a4014203f8eb0abbbffd9cb7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>If you want to learn about how to use <em>console.log</em> as a professional developer then you have to learn <em>computer property names</em>.</p>
<h2 id="heading-lets-start">Let's Start</h2>
<p>Assume that we have 4 different objects and each one is assigned to a variable. How can we log those objects to see what are they?</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj1 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'Joe'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">21</span>, <span class="hljs-attr">happy</span>: <span class="hljs-literal">true</span>}
<span class="hljs-keyword">const</span> obj2 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">20</span>, <span class="hljs-attr">happy</span>: <span class="hljs-literal">true</span>}
<span class="hljs-keyword">const</span> obj3 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'Jona'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">happy</span>: <span class="hljs-literal">false</span>}
<span class="hljs-keyword">const</span> obj4 = {<span class="hljs-attr">name</span>: <span class="hljs-string">'Jake'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">happy</span>: <span class="hljs-literal">true</span>}
</code></pre>
<h3 id="heading-common-way">Common Way</h3>
<p>Of course, the first thing that comes into mind is to use pretty <strong>console.log</strong> :)</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(obj1);
<span class="hljs-built_in">console</span>.log(obj2);
<span class="hljs-built_in">console</span>.log(obj3);
<span class="hljs-built_in">console</span>.log(obj4);
</code></pre>
<p>Result;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660824858747/DXXx-KFzU.png" alt="image.png" /></p>
<p>As you can see we could log all variables. If I ask you which of those logs represents a variable named <strong>obj2</strong> can you tell me that without looking and remembering the code? <strong><em>Of course not!</em></strong> Because you don't know that.</p>
<h3 id="heading-better-way">Better Way</h3>
<p>But hey look there is a better way called <strong>Computed Property Names</strong> and basically, we put all those variables into an object in <strong>console.log</strong> like as below;</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log({obj1, obj2, obj3, obj4})
</code></pre>
<p>As a result, we have 1 line of code and 1 log that represents the whole data as below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660825377155/6uWQsb2YL.png" alt="image.png" /></p>
<p>If I ask you the same question again <strong>Which one of those data represents the variable named obj2?</strong></p>
<p>Then you tell me the object which has a name attribute as <strong>Jane</strong> is the <strong>obj2</strong> without requiring to check the code.</p>
]]></content:encoded></item><item><title><![CDATA[How to use Query Scopes in Laravel efficiently?]]></title><description><![CDATA[Hello artisans,
Today I'll be writing about how to use Query Scopes efficiently in Laravel projects.
Query Scopes are very useful to encapsulate the logic you want to apply to database queries while using Models.
Let's start with an example and under...]]></description><link>https://codewitholgun.com/how-to-use-query-scopes-in-laravel-efficiently</link><guid isPermaLink="true">https://codewitholgun.com/how-to-use-query-scopes-in-laravel-efficiently</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[query-optimization]]></category><category><![CDATA[Query]]></category><category><![CDATA[Databases]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Mon, 29 Apr 2024 13:17:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/m_HRfLhgABo/upload/fdb9bd46ed1ef8d63c0738296fb426ff.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello artisans,</p>
<p>Today I'll be writing about how to use Query Scopes efficiently in Laravel projects.</p>
<p>Query Scopes are very useful to encapsulate the logic you want to apply to database queries while using Models.</p>
<p>Let's start with an example and understand it step by step together.</p>
<p>Assume that there is a model called <em>Post</em> and we need to get only active posts. As you know it's simple and we only need to add a query condition to the <em>Post</em> model and get the results we needed. You can see the example below;</p>
<pre><code class="lang-php">$activePosts = Post::where(<span class="hljs-string">'is_active'</span>, <span class="hljs-string">'='</span>, <span class="hljs-literal">true</span>)-&gt;get();
</code></pre>
<p>However, if we require to get <em>active posts</em> in multiple places that means we need to write the same code in multiple places too. Also, we might need to add some other conditions like <em>getting posts published after a specific date and</em> that means the code is going to be more complex over time.</p>
<p>How about making that much simpler and we can add the query conditions once needed simply by calling them?</p>
<p>Alright! That's possible because we can create simple Query Scope functions in the <em>Post</em> model and use them whenever we need them.</p>
<p>The following example shows how to create those two query scope functions that apply the query conditions we need to filter results.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{

    <span class="hljs-comment">// applies active filter condition</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">scopeActive</span>(<span class="hljs-params">$query</span>) </span>{
        $query-&gt;where(<span class="hljs-string">'is_active'</span>, <span class="hljs-string">'='</span>, <span class="hljs-number">1</span>);
    }

    <span class="hljs-comment">// applies date filter condition</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">scopePublishedAfterDate</span>(<span class="hljs-params">$query, $date</span>) </span>{
        $query-&gt;where(<span class="hljs-string">'published_date'</span>, <span class="hljs-string">'&gt;'</span>, $date);
    }
}
</code></pre>
<p>Every Query Scope must be a function, starting with a <em>scope</em> keyword, and we need to place the name after the <em>scope</em> keyword.</p>
<p>Let's go back to the place where we needed to get only <em>active</em> posts and call the <em>scope</em> we needed to filter results.</p>
<pre><code class="lang-php">$activePosts = Post::active()-&gt;get();
</code></pre>
<p>As you might notice the query scope function that we created to filter results to get only <em>active posts</em> from the database was called <em>scopeActive</em> but we used <em>active</em> instead because while calling query scope functions we must use the name defined after the <em>scope</em> keyword.</p>
<p>Now let's go back to the place where we need to get only <em>active posts</em> that are published <em>after a date</em>.</p>
<pre><code class="lang-php">$activePosts = Post::active()-&gt;publishedAfterDate(<span class="hljs-string">'2024-04-01'</span>)-&gt;get();
</code></pre>
<p>And simple that will also work.</p>
<p>That's all for Query Scopes in Laravel, if you need to ask anything just send me a message on Twitter.</p>
]]></content:encoded></item><item><title><![CDATA[Laravel Sanctum Way To Authenticates different Models rather than Users.]]></title><description><![CDATA[Laravel Sanctum is one way to authenticate different models to use your application but there are many other ways.
In this article, I'll be explain how to authenticate team/team members with a Laravel Sanctum.
Assume that we have following Model;
cla...]]></description><link>https://codewitholgun.com/laravel-sanctum-way-to-authenticates-different-models-rather-than-users</link><guid isPermaLink="true">https://codewitholgun.com/laravel-sanctum-way-to-authenticates-different-models-rather-than-users</guid><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Sun, 10 Dec 2023 17:54:24 GMT</pubDate><content:encoded><![CDATA[<p>Laravel Sanctum is one way to authenticate different models to use your application but there are many other ways.</p>
<p>In this article, I'll be explain how to authenticate team/team members with a Laravel Sanctum.</p>
<p>Assume that we have following Model;</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Team</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{ ... }
</code></pre>
<p>If we add Laravel Sanctum's Trait "use HasApiTokens" then we can easily use all API authentication features on Team model too.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Team</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    use HasApiTokens;
}
</code></pre>
<p>From now on, we are ready to authenticate Team Model.</p>
<p>Create an API token to use for that Team Model;</p>
<pre><code>$team = Team::query()-&gt;find(<span class="hljs-number">1</span>);
$token = $team-&gt;createToken(<span class="hljs-string">'debug-token'</span>, [<span class="hljs-string">'all'</span>])-&gt;plainTextToken; <span class="hljs-comment">// save plain Text token to use later on.</span>
</code></pre><p>Let's have a create an API route in api.php;</p>
<pre><code class="lang-javascript">Route::post(<span class="hljs-string">'authenticate/team'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Request $request</span>) </span>{
    <span class="hljs-keyword">return</span> $request-&gt;user(); <span class="hljs-comment">// this is going to return the Team not User Model</span>
})-&gt;middleware(<span class="hljs-string">'auth:sanctum'</span>);
</code></pre>
<p>Be careful about adding 'auth:sanctum' middleware to the route otherwise it will not work.</p>
<p>Now let's have a try it sending a request to this API using Postman; Always include plain text token in the header as a Bearer Token.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1702231007213/7c79967b-507b-49bc-9179-530581714637.png" alt class="image--center mx-auto" /></p>
<p>Now it's good and we could access to the team.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering Form Management with React useForm Plugin Library]]></title><description><![CDATA[Introduction:
Managing forms in web applications can be a complex task, especially when dealing with validation rules, error handling, and form submissions. The React useForm plugin library offers a powerful and elegant solution to simplify form mana...]]></description><link>https://codewitholgun.com/mastering-form-management-with-react-useform-plugin-library</link><guid isPermaLink="true">https://codewitholgun.com/mastering-form-management-with-react-useform-plugin-library</guid><category><![CDATA[React]]></category><category><![CDATA[react js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[useform]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Tue, 02 May 2023 08:11:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/FGXqbqbGt5o/upload/da66afcb68ab5bb4686a380ad0c54cdf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Introduction:</p>
<p>Managing forms in web applications can be a complex task, especially when dealing with validation rules, error handling, and form submissions. The React <code>useForm</code> plugin library offers a powerful and elegant solution to simplify form management in React applications. In this tutorial, we will walk through a comprehensive example of using the <code>useForm</code> library to handle form lifecycle events, such as validations, rules, and form submissions. By the end of this tutorial, you will have a solid understanding of how to use the React <code>useForm</code> plugin library to efficiently manage forms in your React applications.</p>
<p>Prerequisites:</p>
<ul>
<li><p>Basic understanding of JavaScript and React</p>
</li>
<li><p>Familiarity with React functional components and hooks</p>
</li>
<li><p>Knowledge of form validation and handling in web applications</p>
</li>
</ul>
<p>Getting Started:</p>
<p>To begin, let's install the React <code>useForm</code> plugin library by running the following command:</p>
<pre><code class="lang-javascript">npm install react-hook-form
</code></pre>
<p>Now that we have the library installed, let's dive into a practical example of using the <code>useForm</code> library to manage a form lifecycle.</p>
<p>Example: Create and Update Client Action Items</p>
<p>In this example, we will create a form to create and update client action items. The form will include fields for <code>title</code>, <code>category</code>, <code>description</code>, and <code>target_date</code>. We will use the <code>useForm</code> library to manage form state, handle validations, and submit the form data to an API.</p>
<p>Full Code Example;</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CreateClientActionItem</span>(<span class="hljs-params">{item}</span>) </span>{
    <span class="hljs-keyword">const</span> {
        register,
        handleSubmit,
        <span class="hljs-attr">formState</span>: {
            errors
        }
    } = useForm({
        <span class="hljs-attr">defaultValues</span>: {
            <span class="hljs-attr">title</span>: item?.title ?? <span class="hljs-string">''</span>,
            <span class="hljs-attr">category</span>: item?.category ?? <span class="hljs-string">''</span>,
            <span class="hljs-attr">description</span>: item?.description ?? <span class="hljs-string">''</span>,
            <span class="hljs-attr">target_date</span>: item?.target_date ?? <span class="hljs-string">''</span>,
        }
    });

    <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-keyword">let</span> url = <span class="hljs-string">'/test/store-url'</span>;
        axios.post(url, data).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
            <span class="hljs-keyword">if</span> (res.data.status === <span class="hljs-string">'success'</span>) {
                alert(<span class="hljs-string">"Success"</span>);
            } <span class="hljs-keyword">else</span> {
                alert(<span class="hljs-string">"Error"</span>);
            }
        }).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
            notifyError(<span class="hljs-string">"Unknown error occurred while creating action item"</span>)
        });
    }

    <span class="hljs-keyword">const</span> onUpdate = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-keyword">let</span> url = <span class="hljs-string">'/test/update-url'</span>;
        axios.put(url, data).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
            <span class="hljs-keyword">if</span> (res.data.status === <span class="hljs-string">'success'</span>) {
                alert(<span class="hljs-string">"Success"</span>);
            } <span class="hljs-keyword">else</span> {
                alert(<span class="hljs-string">"Error"</span>);
            }
        }).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
            notifyError(<span class="hljs-string">"Unknown error occurred while updating action item"</span>)
        });
    }

    <span class="hljs-keyword">const</span> onError = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(data);
    }

    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit((item</span> == <span class="hljs-string">null)</span> ? <span class="hljs-attr">onSubmit</span> <span class="hljs-attr">:</span> <span class="hljs-attr">onUpdate</span>, <span class="hljs-attr">onError</span>)}&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
                <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-[24px] rounded-[5px] w-full"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-[16px]"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-[16px]"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"title"</span>&gt;</span>Title<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">title</span>', {
                            <span class="hljs-attr">required:</span> "<span class="hljs-attr">Title</span> <span class="hljs-attr">is</span> <span class="hljs-attr">required</span>",
                            <span class="hljs-attr">minLength:</span> {
                                <span class="hljs-attr">value:</span> <span class="hljs-attr">2</span>,
                                <span class="hljs-attr">message:</span> "<span class="hljs-attr">Title</span> <span class="hljs-attr">must</span> <span class="hljs-attr">be</span> <span class="hljs-attr">at</span> <span class="hljs-attr">least</span> <span class="hljs-attr">2</span> <span class="hljs-attr">characters</span>"
                            },
                            <span class="hljs-attr">maxLength:</span> {
                                <span class="hljs-attr">value:</span> <span class="hljs-attr">50</span>,
                                <span class="hljs-attr">message:</span> '<span class="hljs-attr">Title</span> <span class="hljs-attr">can</span> <span class="hljs-attr">be</span> <span class="hljs-attr">maximum</span> <span class="hljs-attr">50</span> <span class="hljs-attr">characters</span>'
                            }
                        })} <span class="hljs-attr">name</span>=<span class="hljs-string">"title"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"title"</span>
                               <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-[10px] border border-gray-500 rounded-[5px] pl-10 pr-12 f-16-400-g-sans"</span>
                               <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Title"</span>/&gt;</span>
                        {errors.title ?
                            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-red-500"</span>&gt;</span>{errors.title.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> : null}
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-[16px]"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"category"</span>&gt;</span>Category (optional)<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">category</span>', {
                            <span class="hljs-attr">minLength:</span> {
                                <span class="hljs-attr">value:</span> <span class="hljs-attr">2</span>,
                                <span class="hljs-attr">message:</span> "<span class="hljs-attr">Category</span> <span class="hljs-attr">must</span> <span class="hljs-attr">be</span> <span class="hljs-attr">at</span> <span class="hljs-attr">least</span> <span class="hljs-attr">2</span> <span class="hljs-attr">characters</span>"
                            },
                            <span class="hljs-attr">maxLength:</span> {
                                <span class="hljs-attr">value:</span> <span class="hljs-attr">50</span>,
                                <span class="hljs-attr">message:</span> '<span class="hljs-attr">Category</span> <span class="hljs-attr">can</span> <span class="hljs-attr">be</span> <span class="hljs-attr">maximum</span> <span class="hljs-attr">50</span> <span class="hljs-attr">characters</span>'
                            }
                        })} <span class="hljs-attr">name</span>=<span class="hljs-string">"category"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"category"</span>
                               <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-[10px] border border-gray-500 rounded-[5px] pl-10 pr-12 f-16-400-g-sans"</span>
                               <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Category"</span>/&gt;</span>
                        {errors.category ?
                            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-red-500"</span>&gt;</span>{errors.category.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> : null}
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-[16px]"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"description"</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">description</span>', {
                            <span class="hljs-attr">required:</span> "<span class="hljs-attr">Description</span> <span class="hljs-attr">is</span> <span class="hljs-attr">required</span>",
                            <span class="hljs-attr">minLength:</span> {
                                <span class="hljs-attr">value:</span> <span class="hljs-attr">2</span>,
                                <span class="hljs-attr">message:</span> "<span class="hljs-attr">Description</span> <span class="hljs-attr">must</span> <span class="hljs-attr">be</span> <span class="hljs-attr">at</span> <span class="hljs-attr">least</span> <span class="hljs-attr">2</span> <span class="hljs-attr">characters</span>"
                            },
                        })} <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"description"</span>
                                  <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-[10px] border border-gray-500 rounded-[5px] pl-10 pr-12 f-16-400-g-sans"</span>
                                  <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Description"</span>/&gt;</span>
                        {errors.description ?
                            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-red-500"</span>&gt;</span>{errors.description.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> : null}
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-[16px]"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"target_date"</span>&gt;</span>Target date (optional)<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"date"</span> {<span class="hljs-attr">...register</span>('<span class="hljs-attr">target_date</span>')} <span class="hljs-attr">name</span>=<span class="hljs-string">"target_date"</span>
                               <span class="hljs-attr">id</span>=<span class="hljs-string">"target_date"</span>
                               <span class="hljs-attr">className</span>=<span class="hljs-string">"w-full p-[10px] border border-gray-500 rounded-[5px] pl-10 pr-12 f-16-400-g-sans"</span>
                               <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Description"</span>/&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-row items-center gap-[40px]"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"primary-button bg-defaultPrimary"</span>&gt;</span>{!item ? 'Create action item' : 'Update action item'}<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{closeHandler}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-defaultPrimary cursor-pointer"</span>&gt;</span>Cancel<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
}
</code></pre>
<p>Code Explanation:</p>
<p><strong>1. Import</strong> <code>useForm</code><strong>:</strong></p>
<p>Start by importing the <code>useForm</code> hook from the library:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;
</code></pre>
<p><strong>2. Initialize</strong> <code>useForm</code><strong>:</strong></p>
<p>In the <code>CreateClientActionItem</code> functional component, initialize the <code>useForm</code> hook and destructure its returned properties:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> {
    register,
    handleSubmit,
    <span class="hljs-attr">formState</span>: {
        errors
    }
} = useForm({
    <span class="hljs-attr">defaultValues</span>: {
        <span class="hljs-attr">title</span>: item?.title ?? <span class="hljs-string">''</span>,
        <span class="hljs-attr">category</span>: item?.category ?? <span class="hljs-string">''</span>,
        <span class="hljs-attr">description</span>: item?.description ?? <span class="hljs-string">''</span>,
        <span class="hljs-attr">target_date</span>: item?.target_date ?? <span class="hljs-string">''</span>,
    }
});
</code></pre>
<p>The <code>defaultValues</code> option allows you to set initial values for the form fields.</p>
<p>In this example, we use the optional chaining operator “<code>?”</code> and the nullish coalescing operator “<code>??”</code> to set the default values to empty strings if <code>item</code> is not provided.</p>
<p><strong>3. Register form fields:</strong></p>
<p>To register form fields with the <code>useForm</code> hook, use the <code>register</code> function provided by the hook. The <code>register</code> function takes two arguments: the field name and an optional configuration object. The configuration object can include validation rules, such as <code>required</code>, <code>minLength</code>, and <code>maxLength</code>. If a validation rule fails, an error message is provided and stored in the <code>errors</code> object.</p>
<p>For example, registering the <code>title</code> field with validation rules:</p>
<pre><code class="lang-javascript">&lt;input type=<span class="hljs-string">"text"</span> {...register(<span class="hljs-string">'title'</span>, {
    <span class="hljs-attr">required</span>: <span class="hljs-string">"Title is required"</span>,
    <span class="hljs-attr">minLength</span>: {
        <span class="hljs-attr">value</span>: <span class="hljs-number">2</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">"Title must be at least 2 characters"</span>
    },
    <span class="hljs-attr">maxLength</span>: {
        <span class="hljs-attr">value</span>: <span class="hljs-number">50</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'Title can be maximum 50 characters'</span>
    }
})} ... /&gt;
</code></pre>
<p>Similarly, register the <code>category</code>, <code>description</code>, and <code>target_date</code> fields with appropriate validation rules.</p>
<p><strong>4. Handle form submission:</strong></p>
<p>The <code>handleSubmit</code> function is used to manage form submissions. It takes two arguments: a function to be executed on a successful submission and a function to be executed if there are any errors.</p>
<p>In our example, we use the <code>onSubmit</code> function for creating a new action item and the <code>onUpdate</code> function for updating an existing one:</p>
<pre><code class="lang-javascript">&lt;form onSubmit={handleSubmit((item == <span class="hljs-literal">null</span>) ? onSubmit : onUpdate, onError)}&gt;
</code></pre>
<p>The ternary operator checks if <code>item</code> is <code>null</code>, which indicates a new action item should be created. If <code>item</code> is not <code>null</code>, it means we are updating an existing action item.</p>
<p><strong>- Display error messages:</strong></p>
<p>If there are any validation errors, they are stored in the <code>errors</code> object. To display error messages, check if an error exists for a specific form field and render the error message accordingly:</p>
<pre><code class="lang-javascript">{errors.title ?
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-red-500"</span>&gt;</span>{errors.title.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span> : <span class="hljs-literal">null</span>}
</code></pre>
<p>In this example, if there is an error for the <code>title</code> field, the error message is displayed in a paragraph element with a <code>text-red-500</code> class. Similarly, error messages are displayed for other fields such as <code>category</code> and <code>description</code>.</p>
<p><strong>- Form submission logic:</strong></p>
<p>In the <code>onSubmit</code> and <code>onUpdate</code> functions, we use the <code>axios</code> library to send HTTP requests to the API for creating or updating an action item.</p>
<p>The response is checked for the <code>status</code> property to determine if the request was successful.</p>
<p>If successful, we display a success notification, update the item, and close the form. If unsuccessful, we display an error notification:</p>
<pre><code class="lang-javascript">axios.post(url, data).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (res.data.status === <span class="hljs-string">'success'</span>) {
        alert(<span class="hljs-string">'success'</span>);
    } <span class="hljs-keyword">else</span> {
        alert(<span class="hljs-string">'error'</span>);
    }
}).catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    notifyError(<span class="hljs-string">"Unknown error occurred while creating action item"</span>)
});
</code></pre>
<p>In the <code>onError</code> function, we log the error data to the console. In a real-world scenario, you might want to handle the errors differently, such as by displaying a user-friendly error message.</p>
<p><strong>Conclusion:</strong></p>
<p>In this tutorial, we have explored how to use the React <code>useForm</code> plugin library to handle form lifecycle events, including validations, rules, and form submissions.</p>
<p>By using this powerful library, you can streamline form management in your React applications and build robust, user-friendly forms with ease.</p>
<p>The provided code example demonstrates a practical use case that can be adapted to suit your specific requirements. With this knowledge, you can now confidently tackle form management challenges in your React projects.</p>
<p>Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[How React Hooks Can Improve Your Code Quality and Reusability]]></title><description><![CDATA[React Hooks are a new feature in React 16.8 that allow developers to use state and other React features without writing a class component. In this blog post, we will explore the benefits of using React Hooks and why every React developer should learn...]]></description><link>https://codewitholgun.com/how-react-hooks-can-improve-your-code-quality-and-reusability</link><guid isPermaLink="true">https://codewitholgun.com/how-react-hooks-can-improve-your-code-quality-and-reusability</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ReactHooks]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Tue, 06 Dec 2022 17:25:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670347352854/iEB429Z7z.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>React Hooks are a new feature in React 16.8 that allow developers to use state and other React features without writing a class component. In this blog post, we will explore the benefits of using React Hooks and why every React developer should learn them.</p>
<p>One of the key benefits of using React Hooks is that they allow developers to write cleaner and more concise code. By using Hooks, developers can avoid the need to write lengthy class components and instead use simple functions to manage state and handle other tasks. This can help improve the readability and maintainability of your code.</p>
<p>Another advantage of React Hooks is that they enable developers to reuse logic across different components. With Hooks, developers can extract common logic into reusable functions that can be shared across multiple components. This can help reduce duplication and make it easier to maintain and update your codebase.</p>
<p>Furthermore, React Hooks can make it easier to manage state in your application. With Hooks, developers can use the useState Hook to add state to a function component, and the useReducer Hook to manage complex state transitions. This can help improve the performance and scalability of your application.</p>
<p>In conclusion, React Hooks are a valuable tool for any React developer. They allow developers to write cleaner, more concise code, reuse logic across different components, and manage state more effectively. If you are not already using React Hooks in your development process, we highly recommend learning them and incorporating them into your workflow.</p>
<h1 id="heading-lets-take-a-look-some-very-useful-react-hooks">Let's Take A Look Some Very Useful React Hooks</h1>
<h2 id="heading-useeffect">UseEffect</h2>
<p>useEffect is a hook that lets you perform side effects in function components. It is called after every render, including the first render. You can use it to fetch data, manipulate the DOM, or subscribe to events. </p>
<p>| Here is an example of useEffect:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">document</span>.title = <span class="hljs-string">`You clicked <span class="hljs-subst">${count}</span> times`</span>;
  });

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You clicked {count} times<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-usecontext">useContext</h2>
<p>useContext is a hook that lets you access the React context in a function component. The context is a way to pass data through the component tree without having to pass props down manually at every level. </p>
<p>| Here is an example of useContext:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> themes = {
  <span class="hljs-attr">light</span>: {
    <span class="hljs-attr">foreground</span>: <span class="hljs-string">"#000000"</span>,
    <span class="hljs-attr">background</span>: <span class="hljs-string">"#eeeeee"</span>
  },
  <span class="hljs-attr">dark</span>: {
    <span class="hljs-attr">foreground</span>: <span class="hljs-string">"#ffffff"</span>,
    <span class="hljs-attr">background</span>: <span class="hljs-string">"#222222"</span>
  }
};

<span class="hljs-keyword">const</span> ThemeContext = React.createContext(themes.light);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{themes.dark}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Toolbar</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContext.Provider</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Toolbar</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> theme = useContext(ThemeContext);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ThemedButton</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemedButton</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">background:</span> <span class="hljs-attr">props.theme.background</span>, <span class="hljs-attr">color:</span> <span class="hljs-attr">props.theme.foreground</span> }}&gt;</span>
      I am styled by theme context!
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-useref">useRef</h2>
<p>useRef is a hook that lets you get a reference to a DOM element in a function component. It is similar to React.createRef and ref in class components. </p>
<p>| Here is an example of useRef:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputEl = useRef(<span class="hljs-literal">null</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
    inputEl.current.focus();
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputEl}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Focus the input<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-usereducer">useReducer</h2>
<p>useReducer is a hook that lets you manage state in a function component. It is similar to redux and is often used when you have complex state logic or when the next state depends on the previous state. </p>
<p>| Here is an example of useReducer:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useReducer } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'increment'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'decrement'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>();
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      Count: {state.count}
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'decrement' })}&gt;-<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'increment' })}&gt;+<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre><h2 id="heading-uselayouteffect">useLayoutEffect</h2>
<p>useLayoutEffect is a hook that is similar to useEffect, but it fires synchronously after all DOM mutations. It is useful when you need to read or modify the DOM immediately after a render.</p>
<p>| Here is an example of useLayoutEffect:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useState, useLayoutEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [width, setWidth] = useState(<span class="hljs-number">0</span>);

  useLayoutEffect(<span class="hljs-function">() =&gt;</span> {
    setWidth(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>).offsetWidth);
  });

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The width of this paragraph is: {width}px<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre><h2 id="heading-usedebugvalue">useDebugValue</h2>
<p>useDebugValue is a hook that lets you display a custom label for a hook in the React DevTools. It is only called in development mode, and it has no effect in production. </p>
<p>| Here is an example of useDebugValue:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useState, useDebugValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useFriendStatus</span>(<span class="hljs-params">friendID</span>) </span>{
  <span class="hljs-keyword">const</span> [isOnline, setIsOnline] = useState(<span class="hljs-literal">null</span>);
  useDebugValue(isOnline ? <span class="hljs-string">'Online'</span> : <span class="hljs-string">'Offline'</span>);

  <span class="hljs-comment">// ...</span>
}
</code></pre><h2 id="heading-usememo">useMemo</h2>
<p>useMemo is a hook that lets you optimize the performance of a function component by memorizing the output of an expensive function. It is called on every render, but it only recomputes the memoized value if one of the dependencies has changed. </p>
<p>| Here is an example that shows how useMemo can be used to avoid recalculating the sum of two numbers on every render:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useMemo } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [a, setA] = useState(<span class="hljs-number">1</span>);
  <span class="hljs-keyword">const</span> [b, setB] = useState(<span class="hljs-number">2</span>);

  <span class="hljs-keyword">const</span> sum = useMemo(<span class="hljs-function">() =&gt;</span> a + b, [a, b]);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The sum of {a} and {b} is {sum}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setA(a + 1)}&gt;Increment A<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setB(b + 1)}&gt;Increment B<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-usecallback">useCallback</h2>
<p>useCallback is a hook that lets you optimize the performance of a function component by memoizing the callback function. It is similar to useMemo, but it is used for functions instead of values. </p>
<p>| Here is an example that shows how useCallback can be used to avoid creating a new callback function on every render:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">const</span> increment = useCallback(<span class="hljs-function">() =&gt;</span> {
    setCount(<span class="hljs-function"><span class="hljs-params">c</span> =&gt;</span> c + <span class="hljs-number">1</span>);
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You clicked {count} times<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-useimperativehandle">useImperativeHandle</h2>
<p>useImperativeHandle is a hook that lets you customize the instance value that is exposed to parent components when using ref. It is often used to expose methods on a custom component that can be called by the parent. </p>
<p>| Here is an example that shows how useImperativeHandle can be used to expose a focus method on a custom Input component:</p>
<pre><code><span class="hljs-keyword">import</span> React, { useRef, useImperativeHandle } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Input</span>(<span class="hljs-params">{ forwardedRef }</span>) </span>{
  <span class="hljs-keyword">const</span> inputRef = useRef();
  useImperativeHandle(forwardedRef, <span class="hljs-function">() =&gt;</span> ({
    <span class="hljs-attr">focus</span>: <span class="hljs-function">() =&gt;</span> {
      inputRef.current.focus();
    }
  }));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Parent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputRef = useRef();
  <span class="hljs-keyword">const</span> onButtonClick = <span class="hljs-function">() =&gt;</span> {
    inputRef.current.focus();
  };
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onButtonClick}</span>&gt;</span>Focus the input<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>]]></content:encoded></item><item><title><![CDATA[Common Design Patterns for PHP Developers: Essential Knowledge for Successful Projects]]></title><description><![CDATA[As a PHP developer, it is important to have a strong understanding of common design patterns and how to apply them in your projects. Some design patterns that you should be familiar with as a PHP developer include:
Singleton Pattern
Singleton pattern...]]></description><link>https://codewitholgun.com/common-design-patterns-for-php-developers-essential-knowledge-for-successful-projects</link><guid isPermaLink="true">https://codewitholgun.com/common-design-patterns-for-php-developers-essential-knowledge-for-successful-projects</guid><category><![CDATA[Common design patterns]]></category><category><![CDATA[PHP]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[best practices]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Mon, 05 Dec 2022 08:00:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670227478790/kFq7NfI7v.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a PHP developer, it is important to have a strong understanding of common design patterns and how to apply them in your projects. Some design patterns that you should be familiar with as a PHP developer include:</p>
<h2 id="heading-singleton-pattern">Singleton Pattern</h2>
<p>Singleton pattern: This design pattern ensures that a class has only one instance and provides a global point of access to it. It can be useful in situations where you want to limit the number of instances of a class, such as when working with database connections or shared resources.</p>
<p>| Here is an example of the singleton pattern in PHP:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Connection</span>
</span>{
    <span class="hljs-comment">// store the single instance of the connection</span>
    private <span class="hljs-keyword">static</span> $instance;

    <span class="hljs-comment">// private constructor to prevent external instantiation</span>
    private <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"></span>) </span>{}

    <span class="hljs-comment">// get the single instance of the connection</span>
    public <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getInstance</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">if</span> (!self::$instance) {
            <span class="hljs-attr">self</span>::$instance = <span class="hljs-keyword">new</span> Connection();
        }

        <span class="hljs-keyword">return</span> self::$instance;
    }
}

<span class="hljs-comment">// example usage</span>
$connection = Connection::getInstance();
</code></pre><p>In this example, the Connection class is defined with a private constructor, which prevents it from being instantiated directly. Instead, the getInstance method is used to create and return the single instance of the Connection class. This method uses the self keyword to access the $instance property and check if it has been instantiated. If it has not, a new instance of the Connection class is created and stored in the $instance property. If it has, the existing instance is returned.
By using this pattern, we can ensure that only one instance of the Connection class is created, and that all parts of the application can access it through the getInstance method. This can be useful, for example, in situations where you want to limit the number of database connections or shared resources in your application.</p>
<h2 id="heading-factory-pattern">Factory Pattern</h2>
<p>Factory pattern: This design pattern provides a way to create objects without specifying the exact class to be instantiated. It can be useful in situations where you need to create objects based on user input or configuration settings.</p>
<p>| Here is an example of the factory pattern in PHP:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductFactory</span>
</span>{
    <span class="hljs-comment">// create a product instance based on the given type</span>
    public <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createProduct</span>(<span class="hljs-params">$type</span>)
    </span>{
        <span class="hljs-keyword">switch</span> ($type) {
            <span class="hljs-keyword">case</span> <span class="hljs-string">'book'</span>:
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Book();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">'toy'</span>:
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Toy();
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">'Invalid product type.'</span>);
        }
    }
}

<span class="hljs-comment">// example usage</span>
$product1 = ProductFactory::createProduct(<span class="hljs-string">'book'</span>);
$product2 = ProductFactory::createProduct(<span class="hljs-string">'toy'</span>);
</code></pre><p>In this example, the ProductFactory class defines a createProduct method that accepts a product type as an argument and returns an instance of the corresponding product class. The method uses a switch statement to determine which product class to instantiate based on the given type, and returns the corresponding object. If an invalid product type is provided, an exception is thrown.
By using the factory pattern, we can create a flexible and modular way to create objects without specifying the exact class to be instantiated. This can be useful, for example, in situations where you need to create objects based on user input or configuration settings. The factory pattern also allows you to easily add or remove product types without modifying the existing code.</p>
<h2 id="heading-observer-pattern">Observer Pattern</h2>
<p>Observer pattern: This design pattern defines a one-to-many dependency between objects, such that when one object changes state, all of its dependents are notified and updated automatically. It can be useful in situations where you need to maintain consistent data across multiple objects or components.</p>
<p>| Here is an example of the observer pattern in PHP:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Observable</span>
</span>{
    <span class="hljs-comment">// array to store registered observers</span>
    private $observers = [];

    <span class="hljs-comment">// register an observer</span>
    public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">registerObserver</span>(<span class="hljs-params">$observer</span>)
    </span>{
        $this-&gt;observers[] = $observer;
    }

    <span class="hljs-comment">// notify all registered observers</span>
    public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">notifyObservers</span>(<span class="hljs-params"></span>)
    </span>{
        foreach ($this-&gt;observers <span class="hljs-keyword">as</span> $observer) {
            $observer-&gt;update();
        }
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Observer</span>
</span>{
    <span class="hljs-comment">// update the observer</span>
    public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">update</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-comment">// ...</span>
    }
}

<span class="hljs-comment">// example usage</span>
$observable = <span class="hljs-keyword">new</span> Observable();
$observer1 = <span class="hljs-keyword">new</span> Observer();
$observer2 = <span class="hljs-keyword">new</span> Observer();

$observable-&gt;registerObserver($observer1);
$observable-&gt;registerObserver($observer2);

$observable→notifyObservers();
</code></pre><p>In this example, the Observable class defines an registerObserver method that allows other objects to register as observers. The notifyObservers method is used to notify all registered observers when the state of the Observable object changes. The Observer class defines an update method that is called when the Observable object is notified.
By using the observer pattern, we can define a one-to-many dependency between objects, such that when the state of the Observable object changes, all of its registered observers are notified and updated automatically. This can be useful, for example, in situations where you need to maintain consistent data across multiple objects or components. The observer pattern also allows you to add or remove observers dynamically, without modifying the existing code.</p>
<h2 id="heading-decorator-pattern">Decorator Pattern</h2>
<p>Decorator pattern: This design pattern allows you to add new behavior to an existing object dynamically, without modifying its class. It can be useful in situations where you want to extend the functionality of an existing object without changing its implementation.</p>
<p>| Here is an example of the decorator pattern in PHP:</p>
<pre><code><span class="hljs-comment">// This is the base component that can be decorated</span>
abstract <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Window</span>
</span>{
  abstract public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">draw</span>(<span class="hljs-params"></span>);
}

// <span class="hljs-title">This</span> <span class="hljs-title">is</span> <span class="hljs-title">the</span> <span class="hljs-title">abstract</span> <span class="hljs-title">decorator</span> <span class="hljs-title">class</span> <span class="hljs-title">that</span> <span class="hljs-title">contains</span> <span class="hljs-title">a</span> <span class="hljs-title">reference</span> <span class="hljs-title">to</span> <span class="hljs-title">the</span> <span class="hljs-title">window</span> <span class="hljs-title">being</span> <span class="hljs-title">decorated</span>
<span class="hljs-title">abstract</span> <span class="hljs-title">class</span> <span class="hljs-title">WindowDecorator</span> <span class="hljs-title">extends</span> <span class="hljs-title">Window</span>
</span>{
  protected $window;

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">Window $window</span>)
  </span>{
    $this-&gt;<span class="hljs-built_in">window</span> = $window;
  }

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">draw</span>(<span class="hljs-params"></span>)
  </span>{
    $this-&gt;<span class="hljs-built_in">window</span>-&gt;draw();
  }
}

<span class="hljs-comment">// This is a concrete decorator that adds a border to the window</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BorderDecorator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WindowDecorator</span>
</span>{
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">draw</span>(<span class="hljs-params"></span>)
  </span>{
    $this-&gt;drawBorder();
    $this-&gt;<span class="hljs-built_in">window</span>-&gt;draw();
  }

  private <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">drawBorder</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Draws a border around the window</span>
  }
}

<span class="hljs-comment">// This is a concrete decorator that adds a scroll bar to the window</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ScrollDecorator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WindowDecorator</span>
</span>{
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">draw</span>(<span class="hljs-params"></span>)
  </span>{
    $this-&gt;drawScroll();
    $this-&gt;<span class="hljs-built_in">window</span>-&gt;draw();
  }

  private <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">drawScroll</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Draws a scroll bar on the window</span>
  }
}
</code></pre><p>To use the decorator pattern, you would create a Window object and then decorate it with one or more decorators, like this:</p>
<pre><code><span class="hljs-comment">// Create a simple window</span>
$window = <span class="hljs-keyword">new</span> Window();

<span class="hljs-comment">// Decorate the window with a border and scroll bar</span>
$decoratedWindow = <span class="hljs-keyword">new</span> BorderDecorator(<span class="hljs-keyword">new</span> ScrollDecorator($window));

<span class="hljs-comment">// Draw the decorated window</span>
$decoratedWindow→draw();
</code></pre><p>In this example, the $decoratedWindow object has both a border and a scroll bar, because it has been decorated with both the BorderDecorator and ScrollDecorator classes.</p>
<p>In addition to these design patterns, it is also important to have a strong understanding of object-oriented programming principles and how to apply them in your PHP projects. This includes concepts such as encapsulation, inheritance, polymorphism, and abstractions, as well as best practices for organizing and organizing your code.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering SOLID Principles in PHP: Real-World Examples]]></title><description><![CDATA[The SOLID principles are a set of best practices in object-oriented programming that can help developers to create more maintainable and scalable code. In PHP, these principles can be applied in the following ways:
Single Responsibility Principle
The...]]></description><link>https://codewitholgun.com/mastering-solid-principles-in-php-real-world-examples</link><guid isPermaLink="true">https://codewitholgun.com/mastering-solid-principles-in-php-real-world-examples</guid><category><![CDATA[SOLID principles]]></category><category><![CDATA[PHP]]></category><category><![CDATA[oop]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[design principles]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Mon, 05 Dec 2022 07:08:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670227469524/fFq6Q0fnf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The SOLID principles are a set of best practices in object-oriented programming that can help developers to create more maintainable and scalable code. In PHP, these principles can be applied in the following ways:</p>
<h2 id="heading-single-responsibility-principle">Single Responsibility Principle</h2>
<p>The Single Responsibility Principle states that a class should have only one reason to change. In PHP, this can be achieved by ensuring that each class has a clear and well-defined purpose, and that it only contains code that is directly related to that purpose. For example, a User class might contain methods for storing and retrieving user information, but it should not include code for sending email notifications or handling payment transactions.</p>
<p>| Here is an example of how to apply the Single Responsibility Principle in PHP:</p>
<pre><code>&lt;?php

<span class="hljs-comment">// A class that represents a user</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
  private $name;
  private $email;

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$name, $email</span>)
  </span>{
    $this-&gt;name = $name;
    $this-&gt;email = $email;
  }

  <span class="hljs-comment">// A method that returns the user's name</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-keyword">return</span> $this-&gt;name;
  }

  <span class="hljs-comment">// A method that returns the user's email</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getEmail</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-keyword">return</span> $this-&gt;email;
  }
}

<span class="hljs-comment">// A class that represents a user repository</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRepository</span>
</span>{
  <span class="hljs-comment">// A method that saves a user to the database</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>)
  </span>{
    <span class="hljs-comment">// Save the user to the database</span>
  }
}

<span class="hljs-comment">// A class that sends email notifications</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailNotifier</span>
</span>{
  <span class="hljs-comment">// A method that sends an email to a user</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendEmail</span>(<span class="hljs-params">User $user, $message</span>)
  </span>{
    <span class="hljs-comment">// Send the email to the user</span>
  }
}

<span class="hljs-comment">// Create a new user and save it to the database</span>
$user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"John Doe"</span>, <span class="hljs-string">"john.doe@example.com"</span>);
$repository = <span class="hljs-keyword">new</span> UserRepository();
$repository-&gt;save($user);

<span class="hljs-comment">// Send an email notification to the user</span>
$notifier = <span class="hljs-keyword">new</span> EmailNotifier();
$notifier-&gt;sendEmail($user, <span class="hljs-string">"Welcome to our website!"</span>);
</code></pre><p>In this example, the User class has a single responsibility, which is to represent a user and provide methods for getting their name and email. The UserRepository class has a single responsibility, which is to save users to the database. And the EmailNotifier class has a single responsibility, which is to send email notifications to users. By following the Single Responsibility Principle, these classes are easier to maintain and extend, and their code is more readable and organized.</p>
<h2 id="heading-open-closed-principle">Open-Closed Principle</h2>
<p>The Open-Closed Principle states that a class should be open for extension but closed for modification. In PHP, this can be achieved by designing classes that have clear, well-defined interfaces and that use inheritance and abstraction to allow for flexibility and extensibility. For example, a Shape class might define an area() method that calculates the area of a shape, and subclasses such as Circle and Rectangle could override this method to provide their own implementation.</p>
<p>| Here is an example of how to apply the Open-Closed Principle in PHP:</p>
<pre><code>&lt;?php

<span class="hljs-comment">// An abstract shape class that defines a common interface for all shapes</span>
abstract <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span>
</span>{
  <span class="hljs-comment">// An abstract method that calculates the area of a shape</span>
  abstract public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">area</span>(<span class="hljs-params"></span>);
}

// <span class="hljs-title">A</span> <span class="hljs-title">class</span> <span class="hljs-title">that</span> <span class="hljs-title">represents</span> <span class="hljs-title">a</span> <span class="hljs-title">circle</span>
<span class="hljs-title">class</span> <span class="hljs-title">Circle</span> <span class="hljs-title">extends</span> <span class="hljs-title">Shape</span>
</span>{
  private $radius;

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$radius</span>)
  </span>{
    $this-&gt;radius = $radius;
  }

  <span class="hljs-comment">// An implementation of the area() method that calculates the area of a circle</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">area</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">3.14</span> * $this-&gt;radius * $this-&gt;radius;
  }
}

<span class="hljs-comment">// A class that represents a rectangle</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Shape</span>
</span>{
  private $width;
  private $height;

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$width, $height</span>)
  </span>{
    $this-&gt;width = $width;
    $this-&gt;height = $height;
  }

  <span class="hljs-comment">// An implementation of the area() method that calculates the area of a rectangle</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">area</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-keyword">return</span> $this-&gt;width * $this-&gt;height;
  }
}

<span class="hljs-comment">// A class that calculates the total area of a collection of shapes</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AreaCalculator</span>
</span>{
  private $shapes;

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">$shapes</span>)
  </span>{
    $this-&gt;shapes = $shapes;
  }

  <span class="hljs-comment">// A method that calculates the total area of all shapes</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getTotalArea</span>(<span class="hljs-params"></span>)
  </span>{
    $totalArea = <span class="hljs-number">0</span>;
    foreach ($this-&gt;shapes <span class="hljs-keyword">as</span> $shape) {
      $totalArea += $shape-&gt;area();
    }
    <span class="hljs-keyword">return</span> $totalArea;
  }
}

<span class="hljs-comment">// Create some shapes and calculate their total area</span>
$circle = <span class="hljs-keyword">new</span> Circle(<span class="hljs-number">5</span>);
$rectangle = <span class="hljs-keyword">new</span> Rectangle(<span class="hljs-number">10</span>, <span class="hljs-number">5</span>);
$calculator = <span class="hljs-keyword">new</span> AreaCalculator([$circle, $rectangle]);
$totalArea = $calculator-&gt;getTotalArea();

<span class="hljs-comment">// Output the total area</span>
echo <span class="hljs-string">"Total area: "</span> . $totalArea . <span class="hljs-string">"\n"</span>;
</code></pre><p>In this example, the Shape class is an abstract class that defines a common interface for all shapes. The Circle and Rectangle classes extend Shape and provide their own implementation of the area() method. The AreaCalculator class calculates the total area of a collection of shapes, without knowing or caring about the specific types of shapes that are passed to it. This allows the AreaCalculator to be easily extended to support additional shape types, without modifying its existing code. By following the Open-Closed Principle, the code is more flexible and maintainable.</p>
<h2 id="heading-liskov-substitution-principle">Liskov Substitution Principle</h2>
<p>The Liskov Substitution Principle states that derived classes should be substitutable for their base classes. In PHP, this can be achieved by ensuring that subclasses conform to the same contracts and behave in the same way as their base classes. For example, if a Car class defines a start() method that starts the car's engine, a Truck class that extends Car should also have a start() method that starts the truck's engine in the same way.</p>
<p>| Here is an example of how to apply the Liskov Substitution Principle in PHP:</p>
<pre><code>&lt;?php

<span class="hljs-comment">// An abstract vehicle class that defines a common interface for all vehicles</span>
abstract <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span>
</span>{
  <span class="hljs-comment">// An abstract method that starts the vehicle</span>
  abstract public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">start</span>(<span class="hljs-params"></span>);
}

// <span class="hljs-title">A</span> <span class="hljs-title">class</span> <span class="hljs-title">that</span> <span class="hljs-title">represents</span> <span class="hljs-title">a</span> <span class="hljs-title">car</span>
<span class="hljs-title">class</span> <span class="hljs-title">Car</span> <span class="hljs-title">extends</span> <span class="hljs-title">Vehicle</span>
</span>{
  <span class="hljs-comment">// An implementation of the start() method that starts the car's engine</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">start</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Start the car's engine</span>
  }
}

<span class="hljs-comment">// A class that represents a truck</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Truck</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span>
</span>{
  <span class="hljs-comment">// An implementation of the start() method that starts the truck's engine</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">start</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Start the truck's engine</span>
  }
}

<span class="hljs-comment">// A class that controls a vehicle</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VehicleController</span>
</span>{
  private $vehicle;

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">Vehicle $vehicle</span>)
  </span>{
    $this-&gt;vehicle = $vehicle;
  }

  <span class="hljs-comment">// A method that starts the vehicle</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">startVehicle</span>(<span class="hljs-params"></span>)
  </span>{
    $this-&gt;vehicle-&gt;start();
  }
}

<span class="hljs-comment">// Create a car and a truck, and control them</span>
$car = <span class="hljs-keyword">new</span> Car();
$truck = <span class="hljs-keyword">new</span> Truck();
$carController = <span class="hljs-keyword">new</span> VehicleController($car);
$truckController = <span class="hljs-keyword">new</span> VehicleController($truck);
$carController-&gt;startVehicle();
$truckController→startVehicle();
</code></pre><p>In this example, the Vehicle class is an abstract class that defines a common interface for all vehicles. The Car and Truck classes extend Vehicle and provide their own implementation of the start() method. The VehicleController class controls a vehicle without knowing or caring about the specific type of vehicle that it is controlling. This allows the VehicleController to be used with any type of vehicle that extends Vehicle, and ensures that all subclasses of Vehicle are substitutable for their base class. By following the Liskov Substitution Principle, the code is more flexible and maintainable.</p>
<h2 id="heading-interface-segregation-principle">Interface Segregation Principle</h2>
<p>The Interface Segregation Principle states that clients should not be forced to depend on methods that they do not use. In PHP, this can be achieved by defining separate interfaces for different groups of related methods, and having classes implement only the interfaces that are relevant to their functionality. For example, a PaymentProcessor class might implement an AuthorizePayment interface that defines methods for authorizing payment transactions, and a RefundProcessor class might implement a ProcessRefund interface that defines methods for processing refunds.</p>
<p>| Here is an example of how to apply the Interface Segregation Principle in PHP:</p>
<pre><code>&lt;?php

<span class="hljs-comment">// An interface that defines methods for managing user accounts</span>
interface UserAccountManager
{
  <span class="hljs-comment">// A method that creates a new user account</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createAccount</span>(<span class="hljs-params">string $username, string $password</span>);

  // <span class="hljs-title">A</span> <span class="hljs-title">method</span> <span class="hljs-title">that</span> <span class="hljs-title">updates</span> <span class="hljs-title">a</span> <span class="hljs-title">user</span>'<span class="hljs-title">s</span> <span class="hljs-title">password</span>
  <span class="hljs-title">public</span> <span class="hljs-title">function</span> <span class="hljs-title">updatePassword</span>(<span class="hljs-params">string $username, string $password</span>);

  // <span class="hljs-title">A</span> <span class="hljs-title">method</span> <span class="hljs-title">that</span> <span class="hljs-title">deletes</span> <span class="hljs-title">a</span> <span class="hljs-title">user</span> <span class="hljs-title">account</span>
  <span class="hljs-title">public</span> <span class="hljs-title">function</span> <span class="hljs-title">deleteAccount</span>(<span class="hljs-params">string $username</span>);
}

// <span class="hljs-title">An</span> <span class="hljs-title">interface</span> <span class="hljs-title">that</span> <span class="hljs-title">defines</span> <span class="hljs-title">methods</span> <span class="hljs-title">for</span> <span class="hljs-title">managing</span> <span class="hljs-title">user</span> <span class="hljs-title">profiles</span>
<span class="hljs-title">interface</span> <span class="hljs-title">UserProfileManager</span>
</span>{
  <span class="hljs-comment">// A method that gets a user's profile</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getProfile</span>(<span class="hljs-params">string $username</span>);

  // <span class="hljs-title">A</span> <span class="hljs-title">method</span> <span class="hljs-title">that</span> <span class="hljs-title">updates</span> <span class="hljs-title">a</span> <span class="hljs-title">user</span>'<span class="hljs-title">s</span> <span class="hljs-title">profile</span>
  <span class="hljs-title">public</span> <span class="hljs-title">function</span> <span class="hljs-title">updateProfile</span>(<span class="hljs-params">string $username, array $profile</span>);
}

// <span class="hljs-title">An</span> <span class="hljs-title">interface</span> <span class="hljs-title">that</span> <span class="hljs-title">defines</span> <span class="hljs-title">methods</span> <span class="hljs-title">for</span> <span class="hljs-title">managing</span> <span class="hljs-title">user</span> <span class="hljs-title">payments</span>
<span class="hljs-title">interface</span> <span class="hljs-title">UserPaymentManager</span>
</span>{
  <span class="hljs-comment">// A method that gets a user's payment information</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPaymentInfo</span>(<span class="hljs-params">string $username</span>);

  // <span class="hljs-title">A</span> <span class="hljs-title">method</span> <span class="hljs-title">that</span> <span class="hljs-title">updates</span> <span class="hljs-title">a</span> <span class="hljs-title">user</span>'<span class="hljs-title">s</span> <span class="hljs-title">payment</span> <span class="hljs-title">information</span>
  <span class="hljs-title">public</span> <span class="hljs-title">function</span> <span class="hljs-title">updatePaymentInfo</span>(<span class="hljs-params">string $username, array $paymentInfo</span>);
}

// <span class="hljs-title">A</span> <span class="hljs-title">class</span> <span class="hljs-title">that</span> <span class="hljs-title">manages</span> <span class="hljs-title">user</span> <span class="hljs-title">accounts</span>, <span class="hljs-title">profiles</span>, <span class="hljs-title">and</span> <span class="hljs-title">payments</span>
<span class="hljs-title">class</span> <span class="hljs-title">UserManager</span> <span class="hljs-title">implements</span> <span class="hljs-title">UserAccountManager</span>, <span class="hljs-title">UserProfileManager</span>, <span class="hljs-title">UserPaymentManager</span>
</span>{
  <span class="hljs-comment">// An implementation of the createAccount() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createAccount</span>(<span class="hljs-params">string $username, string $password</span>)
  </span>{
    <span class="hljs-comment">// Create the user account</span>
  }

  <span class="hljs-comment">// An implementation of the updatePassword() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updatePassword</span>(<span class="hljs-params">string $username, string $password</span>)
  </span>{
    <span class="hljs-comment">// Update the user's password</span>
  }

  <span class="hljs-comment">// An implementation of the deleteAccount() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deleteAccount</span>(<span class="hljs-params">string $username</span>)
  </span>{
    <span class="hljs-comment">// Delete the user account</span>
  }

  <span class="hljs-comment">// An implementation of the getProfile() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getProfile</span>(<span class="hljs-params">string $username</span>)
  </span>{
    <span class="hljs-comment">// Get the user's profile</span>
  }

  <span class="hljs-comment">// An implementation of the updateProfile() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateProfile</span>(<span class="hljs-params">string $username, array $profile</span>)
  </span>{
    <span class="hljs-comment">// Update the user's profile</span>
  }

  <span class="hljs-comment">// An implementation of the getPaymentInfo() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPaymentInfo</span>(<span class="hljs-params">string $username</span>)
  </span>{
    <span class="hljs-comment">// Get the user's payment information</span>
  }

  <span class="hljs-comment">// An implementation of the updatePaymentInfo() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updatePaymentInfo</span>(<span class="hljs-params">string $username, array $paymentInfo</span>)
  </span>{
    <span class="hljs-comment">// Update the user's payment information</span>
  }
}

<span class="hljs-comment">// Create a new user manager and use its methods</span>
$userManager = <span class="hljs-keyword">new</span> UserManager();
$userManager-&gt;createAccount(<span class="hljs-string">"john.doe"</span>, <span class="hljs-string">"password123"</span>);
$userManager-&gt;updateProfile(<span class="hljs-string">"john.doe"</span>, [<span class="hljs-string">"name"</span> =&gt; <span class="hljs-string">"John Doe"</span>]);
$userManager-&gt;updatePaymentInfo(<span class="hljs-string">"john.doe"</span>, [<span class="hljs-string">"card_number"</span> =&gt; <span class="hljs-string">"1234567890"</span>]);
</code></pre><p>In this example, the UserManager class implements three separate interfaces for managing user accounts, profiles, and payments. Each interface defines a group of related methods, and the UserManager class only implements the methods that are relevant to its functionality. This allows the UserManager to be easily unit tested and extended, and it also makes the code more readable and organized. By following the Interface Segregation Principle, the code is more flexible and maintainable.</p>
<h2 id="heading-dependency-inversion-principle">Dependency Inversion Principle</h2>
<p>The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, but rather both should depend on abstractions. In PHP, this can be achieved by using dependency injection to provide an object with its dependencies, rather than creating the dependencies directly within the object. For example, a UserService class might accept a DatabaseConnection object in its constructor, rather than creating the connection itself. This allows the UserService to be easily unit tested, and also allows for greater flexibility if the underlying implementation of the DatabaseConnection class changes.</p>
<p>| Here is an example of how to apply the Dependency Inversion Principle in PHP:</p>
<pre><code>&lt;?php

<span class="hljs-comment">// An interface that defines methods for connecting to a database</span>
interface DatabaseConnection
{
  <span class="hljs-comment">// A method that opens a connection to the database</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">connect</span>(<span class="hljs-params"></span>);

  // <span class="hljs-title">A</span> <span class="hljs-title">method</span> <span class="hljs-title">that</span> <span class="hljs-title">closes</span> <span class="hljs-title">the</span> <span class="hljs-title">connection</span> <span class="hljs-title">to</span> <span class="hljs-title">the</span> <span class="hljs-title">database</span>
  <span class="hljs-title">public</span> <span class="hljs-title">function</span> <span class="hljs-title">disconnect</span>(<span class="hljs-params"></span>);
}

// <span class="hljs-title">A</span> <span class="hljs-title">class</span> <span class="hljs-title">that</span> <span class="hljs-title">provides</span> <span class="hljs-title">a</span> <span class="hljs-title">MySQL</span> <span class="hljs-title">database</span> <span class="hljs-title">connection</span>
<span class="hljs-title">class</span> <span class="hljs-title">MySQLDatabaseConnection</span> <span class="hljs-title">implements</span> <span class="hljs-title">DatabaseConnection</span>
</span>{
  <span class="hljs-comment">// An implementation of the connect() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">connect</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Connect to the MySQL database</span>
  }

  <span class="hljs-comment">// An implementation of the disconnect() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">disconnect</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Close the MySQL database connection</span>
  }
}

<span class="hljs-comment">// A class that provides a PostgreSQL database connection</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostgreSQLDatabaseConnection</span> <span class="hljs-title">implements</span> <span class="hljs-title">DatabaseConnection</span>
</span>{
  <span class="hljs-comment">// An implementation of the connect() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">connect</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Connect to the PostgreSQL database</span>
  }

  <span class="hljs-comment">// An implementation of the disconnect() method</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">disconnect</span>(<span class="hljs-params"></span>)
  </span>{
    <span class="hljs-comment">// Close the PostgreSQL database connection</span>
  }
}

<span class="hljs-comment">// A class that uses a database connection to query the database</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">QueryExecutor</span>
</span>{
  private $databaseConnection;

  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">DatabaseConnection $databaseConnection</span>)
  </span>{
    $this-&gt;databaseConnection = $databaseConnection;
  }

  <span class="hljs-comment">// A method that queries the database and returns the result</span>
  public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">query</span>(<span class="hljs-params">string $query</span>)
  </span>{
    <span class="hljs-comment">// Connect to the database</span>
    $this-&gt;databaseConnection-&gt;connect();

    <span class="hljs-comment">// Execute the query and get the result</span>
    $result = <span class="hljs-comment">// Query the database</span>

    <span class="hljs-comment">// Close the database connection</span>
    $this-&gt;databaseConnection-&gt;disconnect();

    <span class="hljs-keyword">return</span> $result;
  }
}

<span class="hljs-comment">// Create a query executor with a MySQL database connection</span>
$mysqlConnection = <span class="hljs-keyword">new</span> MySQLDatabaseConnection();
$queryExecutor = <span class="hljs-keyword">new</span> QueryExecutor($mysqlConnection);

<span class="hljs-comment">// Query the database using the MySQL connection</span>
$result = $queryExecutor-&gt;query(<span class="hljs-string">"SELECT * FROM users"</span>);

<span class="hljs-comment">// Create a query executor with a PostgreSQL database connection</span>
$postgresConnection = <span class="hljs-keyword">new</span> PostgreSQLDatabaseConnection();
$queryExecutor = <span class="hljs-keyword">new</span> QueryExecutor($postgresConnection);

<span class="hljs-comment">// Query the database using the PostgreSQL connection</span>
$result = $queryExecutor-&gt;query(<span class="hljs-string">"SELECT * FROM users"</span>);
</code></pre><p>In this example, the QueryExecutor class depends on an abstract DatabaseConnection interface, rather than a concrete MySQLDatabaseConnection or PostgreSQLDatabaseConnection class. This allows the QueryExecutor to be easily unit tested and extended, and it also allows for greater flexibility if the underlying implementation of the DatabaseConnection class changes. By following the Dependency Inversion Principle, the code is more flexible and maintainable.</p>
]]></content:encoded></item><item><title><![CDATA[Changing the state of a JSON object in React]]></title><description><![CDATA[In this code example, we see how to change the state of a JSON object in a React component. This is a common task when building interactive user interfaces because it allows us to update the data that we display in response to user actions.
import Re...]]></description><link>https://codewitholgun.com/changing-the-state-of-a-json-object-in-react</link><guid isPermaLink="true">https://codewitholgun.com/changing-the-state-of-a-json-object-in-react</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[ReactHooks]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Sun, 04 Dec 2022 15:53:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670169079268/6dEZLQwrW.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this code example, we see how to change the state of a JSON object in a React component. This is a common task when building interactive user interfaces because it allows us to update the data that we display in response to user actions.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Declare a new state variable, which we'll call "json"</span>
  <span class="hljs-keyword">const</span> [json, setJson] = useState({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'John Doe'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">42</span>,
    <span class="hljs-attr">address</span>: {
      <span class="hljs-attr">street</span>: <span class="hljs-string">'123 Main St.'</span>,
      <span class="hljs-attr">city</span>: <span class="hljs-string">'Boston'</span>,
      <span class="hljs-attr">state</span>: <span class="hljs-string">'MA'</span>
    }
  });

  <span class="hljs-comment">// This function updates the "json" state by changing the "name" property</span>
  <span class="hljs-keyword">const</span> updateName = <span class="hljs-function">() =&gt;</span> {
    setJson({
      ...json, <span class="hljs-comment">// copy the current properties of "json"</span>
      <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane Doe'</span> <span class="hljs-comment">// update the "name" property</span>
    });
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Name: {json.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateName}</span>&gt;</span>Update Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>In this example, the <code>Example</code> component has a state variable called <code>json</code> that is initialized with a JSON object containing some data. The component renders the <code>name</code> property of the <code>json</code> object, and has a button that, when clicked, updates the <code>name</code> property of the <code>json</code> object.</p>
<p>To update the <code>json</code> state, the code uses a common pattern in React: it creates a new <code>json</code> object by copying the current properties of the existing <code>json</code> object, and then updating the <code>name</code> property with a new value. This allows us to keep the existing state and only change the properties that we want to update.</p>
<p>Overall, this code shows how to use React's state mechanism to manage data in a JSON object and update it in response to user actions. This is a valuable skill for any front-end developer building interactive user interfaces with React.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Arrays - Introduction in 2022 / Part 1]]></title><description><![CDATA[Introduction
Hello reader, if you are a web developer like me or wanted to become one then you always have to deal with JavaScript there is no other chance.
Today I want to make an introduction to arrays in JavaScript. So, maybe at least you can find...]]></description><link>https://codewitholgun.com/javascript-arrays-introduction-in-2022-part-1</link><guid isPermaLink="true">https://codewitholgun.com/javascript-arrays-introduction-in-2022-part-1</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Thu, 25 Aug 2022 22:50:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/cckf4TsHAuw/upload/v1661467726358/UYCTJUAhz.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Hello reader, if you are a web developer like me or wanted to become one then you always have to deal with JavaScript there is no other chance.</p>
<p>Today I want to make an introduction to <strong>arrays</strong> in JavaScript. So, maybe at least you can find the things that you still don't know about arrays.</p>
<h2 id="heading-what-are-the-arrays">What are the Arrays?</h2>
<p>Let's make it simple for everyone,</p>
<p>Basically, you have a variable that can store multiple data inside and makes a list of data. That's what actually array is :)</p>
<p>That's a widely used data structure technique in computer science and almost every programming language has arrays. <strong>(Not all of them!)</strong></p>
<h2 id="heading-what-are-the-arrays-in-javascript">What are the Arrays in JavaScript?</h2>
<p>Arrays in JavaScript are a little bit different than arrays in other programming languages. If you check the definition you can understand the difference because they are a kind of special type objects in JavaScript.</p>
<p>Let's make it more simple to understand;</p>
<p>Normally arrays store only one kind of data type but multiple of them inside. For example, you can put multiple strings, integers, booleans, or objects into the array but only one type in one array.</p>
<p>But in JavaScript, you can put any kind of element into the array at once. <strong>(That's the difference).</strong></p>
<h2 id="heading-how-to-create-an-array-in-javascript">How to create an Array in JavaScript?</h2>
<p>There are multiple ways to create an array but you know what let's learn the generally used simple one because you don't need other ways to create an array unless you're developing a Framework or big libraries.</p>
<p>Just declare a variable, open square bracket, and ta-da you have a beautiful empty array like in the example below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArray = [];
</code></pre>
<h2 id="heading-lets-make-some-fun">Let's make some fun :)</h2>
<p>I am a little bit of a nerd and always want to check the type of the variables I have, let's check the type of this variable.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> myArray);
</code></pre>
<p>If you run this code probably you remember something like "arrays in javascript is a special type of objects" because you have a message like "object".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661466124380/4T7H4Tzqm.png" alt="image.png" /></p>
<h2 id="heading-how-to-create-an-array-with-multiple-elements">How to create an Array with multiple elements?</h2>
<p>We actually created an array before but let's create another one and put 6 different data types into it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArray2 = [<span class="hljs-number">1</span>, <span class="hljs-string">'string'</span>, <span class="hljs-literal">true</span>, {}, [], <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params"></span>) </span>{<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hello'</span>)}]
</code></pre>
<p>If you check the array we created above, we put 6 different data types (integer, string, boolean, object, array, and function).</p>
<p>Did you read <strong>function?</strong> Be careful because you can put a <strong>function</strong> inside of the array in JavaScript.</p>
<h2 id="heading-how-to-print-specific-elements-of-the-array">How to print specific elements of the Array?</h2>
<p>In order to print specific elements of the Array, you have to know the location of the element.</p>
<p>Remember that <strong>arrays are zero-based indexed data structures.</strong></p>
<p>Let's make it simple;</p>
<ul>
<li><p>The first element of the array is in the location <strong>0</strong>.</p>
</li>
<li><p>The second element of the array is in the location <strong>1</strong>.</p>
</li>
<li><p>The third element of the array is in the location <strong>2</strong>.</p>
</li>
</ul>
<p>Did you get the point? <strong>We always start to count the element's location from 0</strong> and that's the reason that arrays are known as <strong>zero-based indexed data structures</strong>.</p>
<p>Simple example;</p>
<p>Print the fourth element of the array.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(myArray2[<span class="hljs-number">3</span>]);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661467159837/GHCNHDy55.png" alt="image.png" /></p>
<p>If you check the image above, you can see that an empty <strong>object</strong> is printed because in our array we have the following elements.</p>
<pre><code class="lang-javascript"> [<span class="hljs-number">1</span>, <span class="hljs-string">'string'</span>, <span class="hljs-literal">true</span>, {}, [], <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hello</span>(<span class="hljs-params"></span>) </span>{<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hello'</span>)}]

<span class="hljs-comment">// index 0 = 1</span>
<span class="hljs-comment">// index 1 = 'string'</span>
<span class="hljs-comment">// index 2 = true</span>
--&gt; index <span class="hljs-number">3</span> = {}
<span class="hljs-comment">// index 4 = []</span>
<span class="hljs-comment">// index 5 = function hello() {console.log('hello')}</span>
</code></pre>
<p>That's all for array's introduction :)</p>
<p>Also, you can watch this tutorial on <a target="_blank" href="https://www.youtube.com/watch?v=DDczYFidFSA">youtube</a>;</p>
<p>Don't forget to follow me on;</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/channel/UCH-xplaz-cmloIUkYspcEhQ">Youtube</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to create a modal with ReactJS and style it with TailwindCSS.]]></title><description><![CDATA[Introduction
ReactJS is a great library and If you combine it with TailwindCSS they become the best couple in the programming world :)
Today I will write about how to create a modal using ReactJS and style it with TailwindCSS.

Caution: ReactJS versi...]]></description><link>https://codewitholgun.com/how-to-create-a-modal-with-reactjs-and-style-it-with-tailwindcss</link><guid isPermaLink="true">https://codewitholgun.com/how-to-create-a-modal-with-reactjs-and-style-it-with-tailwindcss</guid><category><![CDATA[React]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Tailwind CSS Tutorial]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Wed, 17 Aug 2022 14:35:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/cckf4TsHAuw/upload/v1660746873766/_ZK1GioIN.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>ReactJS is a great library and If you combine it with TailwindCSS they become the best couple in the programming world :)</p>
<p>Today I will write about how to create a modal using ReactJS and style it with TailwindCSS.</p>
<blockquote>
<p>Caution: ReactJS version <strong>^18.2.0</strong> is used in this tutorial.</p>
</blockquote>
<h2 id="heading-create-a-new-react-project-with-tailwindcss">Create A New React Project with TailwindCSS</h2>
<p>To create a react project on your computer please make sure that <strong>NPM</strong> is already installed.</p>
<p>If you're ready, let's run the following command on your terminal or command prompt to create a react project called <strong>my-project</strong>.</p>
<pre><code class="lang-javascript">npx create-react-app my-project
</code></pre>
<p>Change your current directory into the project folder by using the following command.</p>
<pre><code class="lang-javascript">cd my-project
</code></pre>
<p>Since you're now in the project folder let's run the following command to include <strong>TailwindCSS with other dependencies</strong> into the project.</p>
<pre><code class="lang-javascript">npm install -D tailwindcss postcss autoprefixer
</code></pre>
<p>Once this command is completed and the <strong>TailwindCSS</strong> is installed then run the following command to create <strong>configuration files for TailwindCSS and PostCSS</strong>.</p>
<pre><code class="lang-javascript">npx tailwindcss init -p
</code></pre>
<p>If you've done everything correctly then you'll have the same following project structure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660607624126/9Q18O0F8k.png" alt="image.png" /></p>
<p>At this point, we have to make some configuration changes in the <strong>tailwind.config.js</strong> file to tell which files will have <strong>TailwindCSS</strong> classes on them.</p>
<p>Let's add the following configuration to the file.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** <span class="hljs-doctag">@type <span class="hljs-type">{import('tailwindcss').Config}</span> </span>*/</span> 
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">content</span>: [
    <span class="hljs-string">"./src/**/*.{js,jsx,ts,tsx}"</span>,
  ],
  <span class="hljs-attr">theme</span>: {
    <span class="hljs-attr">extend</span>: {},
  },
  <span class="hljs-attr">plugins</span>: [],
}
</code></pre>
<p>Also we need to add <strong>TailwindCSS directives</strong> into the <strong>src/index.css</strong> file to include <strong>TailwindCSS</strong>.</p>
<pre><code class="lang-javascript">@tailwind base;
@tailwind components;
@tailwind utilities;
</code></pre>
<p>We're almost done with <strong>TailwindCSS</strong> integration, So just run the following command to run the application.</p>
<pre><code class="lang-javascript">npm run start
</code></pre>
<p>If everything goes right then you'll see some messages in terminal like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660718121070/8oVL1ksqs.png" alt="image.png" /></p>
<p>If you go to one of the URLs provided to you (your URLs can be different than mine) then you'll see the following screen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660718320121/cTQ_JEK5h.png" alt="image.png" /></p>
<p>Congratulations 👏👏</p>
<h3 id="heading-create-modal-component">Create Modal Component</h3>
<p>Our application is running and we are ready to create a lovely modal component.</p>
<p>So, let's create a file named <strong>modal.jsx</strong> in <strong>src</strong> folder.</p>
<p>After you created the file add the following piece of code into this file to convert it into the simple <strong>react</strong> component.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Modal</span>(<span class="hljs-params">{children}</span>) </span>{
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"relative z-50"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"fixed inset-0 bg-black/10"</span> <span class="hljs-attr">aria-hidden</span>=<span class="hljs-string">"true"</span>/&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"fixed inset-0 flex items-center justify-center p-4"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex min-h-full items-center justify-center"</span>&gt;</span>
                    {children}
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}
</code></pre>
<p>Anywhere in our application, we can inject this component by calling it with the tag of <strong>Modal</strong>.</p>
<p>Let's add the following code into <strong>App.js</strong> to show the modal component whenever we click <strong>Open Modal</strong> button.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {Modal} <span class="hljs-keyword">from</span> <span class="hljs-string">"./modal"</span>;
<span class="hljs-keyword">import</span> {useState} <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [open, setOpen] = useState(<span class="hljs-literal">false</span>);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"relative min-h-screen"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col items-center my-24"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setOpen(!open)} className="py-2 px-4 bg-blue-500 hover:bg-blue-600 text-white font-bold text-lg rounded-full"&gt;Open Modal<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

            {open ? <span class="hljs-tag">&lt;<span class="hljs-name">Modal</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-2 bg-white px-4 pb-4 rounded-lg"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-lg text-black mt-2 pr-48"</span>&gt;</span>This is my modal title<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">hr</span>/&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-col gap-2"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"email"</span>&gt;</span>Please enter your email address.<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"py-2 px-4 border border-gray-200 rounded-lg"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"E.g: test@gmail.com"</span>/&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">hr</span>/&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex flex-row gap-2"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setOpen(!open)} className="flex-1 py-2 px-4 bg-gray-500 hover:bg-gray-600 text-white font-bold text-lg rounded-full"&gt;Close<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setOpen(!open)} className="flex-1 py-2 px-4 bg-blue-500 hover:bg-blue-600 text-white font-bold text-lg rounded-full"&gt;Save<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">Modal</span>&gt;</span> : null}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Let's understand how does actually it works;</p>
<ul>
<li><p>First of all, we created a state <strong>open</strong> and we surrounded it with <strong>useState</strong> hook. So we can change the state of the <strong>open</strong> by calling <strong>setState</strong> method.</p>
</li>
<li><p>We created a button and named it as <strong>Open Modal</strong>, whenever it's clicked we change the state of <strong>open</strong> to true.</p>
</li>
<li><p>Whenever the state of the <strong>open</strong> becomes true, then we inject <strong>Modal</strong> component into our page.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Step By Step Guide To Upload Files With Laravel Framework]]></title><description><![CDATA[As a full-stack web developer, I've always needed to implement a file upload feature in my projects. Today, I'll show you how it's easy to upload files to the server with Laravel Framework.
Step 1
Let's run the following artisan command to create a c...]]></description><link>https://codewitholgun.com/step-by-step-guide-to-upload-files-with-laravel-framework</link><guid isPermaLink="true">https://codewitholgun.com/step-by-step-guide-to-upload-files-with-laravel-framework</guid><category><![CDATA[Laravel]]></category><category><![CDATA[File Upload]]></category><category><![CDATA[file system]]></category><category><![CDATA[PHP]]></category><category><![CDATA[PHP7]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Wed, 10 Aug 2022 05:56:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/Y5yxdx2a4PI/upload/v1660075604804/etisl2_Mu.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a full-stack web developer, I've always needed to implement a file upload feature in my projects. Today, I'll show you how it's easy to upload files to the server with Laravel Framework.</p>
<p>Step 1</p>
<p>Let's run the following artisan command to create a controller called <strong>FileUploadController</strong>. This controller will be used along the tutorial to show the file upload page to the users and store the uploaded files on the server.</p>
<pre><code class="lang-javascript">php artisan make:controller FileUploadController
</code></pre>
<p>Step 2</p>
<p>Since we created our controller in step 1, in this step we will create a route in <strong>web.php</strong> to show the page to the users.</p>
<pre><code class="lang-javascript">    Route::get(<span class="hljs-string">'/file-upload-test'</span>, [FileUploadController::<span class="hljs-class"><span class="hljs-keyword">class</span>, '<span class="hljs-title">index</span>'])-&gt;<span class="hljs-title">name</span>('<span class="hljs-title">file</span>-<span class="hljs-title">upload</span>.<span class="hljs-title">index</span>')</span>;
</code></pre>
<p>Step 3</p>
<p>In step 2 we created a route with the URL of <strong>file-upload-test</strong> which calls the <strong>index</strong> method in <strong>FileUploadController</strong> to show a page to the users.</p>
<p>But we didn't create this method yet. So, let's create this <strong>index</strong> method in the <strong>FileUploadController</strong> which will render a blade file that we named as <strong>file-upload.blade.php</strong> to show the file upload page.</p>
<pre><code class="lang-javascript">&lt;?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FileUploadController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">index</span>(<span class="hljs-params"></span>): <span class="hljs-title">Factory</span>|<span class="hljs-title">View</span>|<span class="hljs-title">Application</span>
    </span>{
        <span class="hljs-keyword">return</span> view(<span class="hljs-string">'file-upload'</span>);
    }
}
</code></pre>
<p>Step 4</p>
<p>In step 3 we created the <strong>index</strong> method in <strong>FileUploadController</strong> which renders a blade file called <strong>file-upload.blade.php</strong> to show the file upload page.</p>
<p>But we didn't create the <strong>file-upload.blade.php</strong> file yet. Let's create this file in the <strong>resources/views</strong> folder and put the following HTML into the file.</p>
<pre><code class="lang-javascript">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt;
    &lt;title&gt;Document&lt;/title&gt;

    &lt;style&gt;
        .flex {
            display: flex;
        }

        .flex-col {
            flex-direction: column;
        }

        .mt-2 {
                margin-top: 20px;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form action="{{ route('file-upload.store') }}" enctype="multipart/form-data" method="POST"&gt;
        @csrf
        &lt;div class="flex flex-col shadow"&gt;
            &lt;label for="file_selector"&gt;Select a file to upload&lt;/label&gt;
            &lt;input type="file" id="file_selector" name="file"&gt;
        &lt;/div&gt;

        &lt;button type="submit" class="mt-2"&gt;Upload File&lt;/button&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Once this blade file is rendered we see the following page. (If you visit <strong>file-upload-test</strong> URL now you will get an error, <strong>move to the step 5</strong>)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660079461981/BBDWadKMH.png" alt="image.png" /></p>
<p>Basically, we have a simple form with a label, an input field with the file type, and a button used to submit the form.</p>
<p>Let's explore the following form element a little bit to understand what's going on.</p>
<pre><code class="lang-javascript">    &lt;form action=<span class="hljs-string">"{{ route('file-upload.store') }}"</span> enctype=<span class="hljs-string">"multipart/form-data"</span> method=<span class="hljs-string">"POST"</span>&gt;
        @csrf
        &lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"flex flex-col shadow"</span>&gt;
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"file_selector"</span>&gt;</span>Select a file to upload<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span></span>
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"file_selector"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"uploaded_file"</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>

        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-2"</span>&gt;</span>Upload File<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
    &lt;/form&gt;
</code></pre>
<ul>
<li><p>We need an endpoint on the form element to send the submitted data to some URL in our app. So, we put <strong>action={{ route('file-upload.store') }}</strong> which means that whenever the form is submitted the data will be sent to this route (we didn't create it yet).</p>
</li>
<li><p>Since we are aiming to upload a file we put <strong>enctype="multipart/form-data"</strong> otherwise the file is not submitted to the back-end.</p>
</li>
<li><p>The <strong>method=POST</strong> attribute is specified in the form because we are going to send a <strong>POST</strong> request to the endpoint.</p>
</li>
<li><p>In order to pass CSRF validation on Laravel we call ** @csrf** blade directive in the form element which creates a hidden CSRF token field.</p>
</li>
</ul>
<p>Step 5</p>
<p>In step 4 we created an HTML form in the <strong>file-upload.blade.php</strong> file and now we are going to create a route named <strong>file-upload.store</strong> in the <strong>web.php</strong> file.</p>
<pre><code class="lang-javascript">    Route::get(<span class="hljs-string">'/file-upload-test'</span>, [FileUploadController::<span class="hljs-class"><span class="hljs-keyword">class</span>, '<span class="hljs-title">index</span>'])-&gt;<span class="hljs-title">name</span>('<span class="hljs-title">file</span>-<span class="hljs-title">upload</span>.<span class="hljs-title">index</span>')</span>;
    <span class="hljs-attr">Route</span>::post(<span class="hljs-string">'/file-upload'</span>, [FileUploadController::<span class="hljs-class"><span class="hljs-keyword">class</span>, '<span class="hljs-title">store</span>'])-&gt;<span class="hljs-title">name</span>('<span class="hljs-title">file</span>-<span class="hljs-title">upload</span>.<span class="hljs-title">store</span>')</span>;
</code></pre>
<p>Step 6</p>
<p>In step 5 we created a route <strong>file-upload.store</strong> in <strong>web.php</strong> and we know that the route will call <strong>store</strong> method in the <strong>FileUploadController</strong>. So, let's create this method in the controller to upload the file.</p>
<pre><code class="lang-javascript">    public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">store</span>(<span class="hljs-params">Request $request</span>)
    </span>{
        <span class="hljs-keyword">if</span> ($request-&gt;hasFile(<span class="hljs-string">'uploaded_file'</span>)) {
            $uploadedFile = $request-&gt;file(<span class="hljs-string">'uploaded_file'</span>); <span class="hljs-comment">// the file uploaded</span>
            $extension = $request-&gt;file(<span class="hljs-string">'uploaded_file'</span>)-&gt;getClientOriginalExtension(); <span class="hljs-comment">//jpg, jpeg, png</span>
            $fileName = Str::uuid() . <span class="hljs-string">'.'</span> . $extension; <span class="hljs-comment">// de3f31db-85f8-4b9b-a3b9-a4b45b551322.jpg</span>
            Storage::disk(<span class="hljs-string">'public'</span>)-&gt;putFileAs(<span class="hljs-string">'uploaded_files'</span>, $uploadedFile, $fileName);
        }

        <span class="hljs-keyword">return</span> redirect()-&gt;back();
    }
</code></pre>
<p>Let's explore how this method work.</p>
<ul>
<li><p>First of all we check if the request has a file in the <strong>uploaded_file</strong> parameter.</p>
</li>
<li><p>If there is a file then we store it in the <strong>uploadedFile</strong> variable.</p>
</li>
<li><p>Then we get the uploaded file extension using <strong>$request-&gt;file('uploaded_file')-&gt;getClientOriginalExtension();</strong></p>
</li>
<li><p>We need a name to store the file in our file system. So, the <strong>Str::uuid()</strong> helper is used to create a universal unique identifier for the file name and appended the file extension to the end of it.</p>
</li>
<li><p>There are three different disk options on Laravel as default <strong>local, public, and s3</strong>. Since we want to show the uploaded file in our application later we use <strong>public</strong> disk.</p>
</li>
<li><p>In the last part, we upload the file into the <strong>uploaded_files</strong> folder in the public disk (if <strong>uploaded_files</strong> folder does not exist, it will be automatically created) using <strong>Storage::disk</strong> helper in Laravel.</p>
</li>
</ul>
<p>This is how actually we upload a file in the Laravel Framework.</p>
<p>If you like to upload a file but also want to save the path into the database, then basically you just need to save the <strong>fileName</strong> variable as the path and later on, you can use this path to show the file.</p>
<p>Example;</p>
<pre><code class="lang-javascript">&lt;img src=<span class="hljs-string">"{{ asset('storage/uploaded_files/7818704d-088b-4236-b3fb-dcc15bf57cc6.jpeg') }}"</span> alt=<span class="hljs-string">""</span>&gt;
</code></pre>
<p>Note: Since we use the <strong>public</strong> disk of the framework we should run the following artisan command to make sure the <strong>uploaded_files</strong> folder in the <strong>storage</strong> folder of the application is linked to the <strong>public</strong> as a symbolic link. Otherwise, the uploaded files will not be publicly available.</p>
<pre><code class="lang-javascript">php artisan storage:link
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How to upload files using Axios in ReactJS + Laravel.]]></title><description><![CDATA[Today I am going to write about how to upload files using Axios in ReactJS + Laravel Framework.
If you already reading this article that means you know what is Axios and you couldn't figure out how to upload files with it. Don't worry it's so simple ...]]></description><link>https://codewitholgun.com/how-to-upload-files-using-axios-in-reactjs-laravel</link><guid isPermaLink="true">https://codewitholgun.com/how-to-upload-files-using-axios-in-reactjs-laravel</guid><category><![CDATA[Laravel]]></category><category><![CDATA[React]]></category><category><![CDATA[axios]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Sun, 31 Jul 2022 23:23:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/vw3Ahg4x1tY/upload/v1660090321483/s5ZMLzfov.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Today I am going to write about how to upload files using Axios in ReactJS + Laravel Framework.</p>
<p>If you already reading this article that means you know what is Axios and you couldn't figure out how to upload files with it. Don't worry it's so simple and I am going to show you an example as well.</p>
<p>Let's assume we have created a simple <strong>Form</strong> component which contains a simple input element with the type of <strong>file</strong> and a button to submit the form. Of course, we will not directly submit the form instead we are going to use Axios to handle this and the page will not be redirected to some URL.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, {useState} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>;

<span class="hljs-keyword">const</span> Form = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// state to store the selected file.</span>
    <span class="hljs-keyword">const</span> [selectedFile, setSelectedFile] = useState(<span class="hljs-literal">null</span>);

    <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (event) =&gt; {
        event.preventDefault();

        <span class="hljs-comment">// Create a FormData object</span>
        <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData();

        <span class="hljs-comment">// Append file to the formData object here</span>
        formData.append(<span class="hljs-string">"selectedFile"</span>, selectedFile);

        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">// We will send formData object as a data to the API URL here.</span>
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.post(<span class="hljs-string">"/api/upload/file"</span>, formData, {
                <span class="hljs-attr">headers</span>: {<span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"multipart/form-data"</span>}
            }).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
                alert(<span class="hljs-string">"File Uploaded Successfully"</span>);
            }).catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
                alert(<span class="hljs-string">"Error"</span>)
            });
        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.log(error)
        }
    }

    <span class="hljs-keyword">const</span> handleFileSelect = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        <span class="hljs-comment">// we only get the selected file from input element's event</span>
        setSelectedFile(event.target.files[<span class="hljs-number">0</span>])
    }

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleFileSelect}/</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Upload File"</span>/&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
    )
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Form;
</code></pre>
<p>Let's break the above solution into multiple steps</p>
<ul>
<li><p>First, we created a state called <strong>selectedFile</strong> using <strong>useState()</strong> hook and we use this state to store the currently selected file.</p>
</li>
<li><p>Secondly, we set <strong>handleFileSelect</strong> function to the <strong>onChange</strong> handler of the input element, thus whenever we select a file then <strong>handleFileSelect</strong> function will be invoked and it sets the selected file into the <strong>selectedFile</strong> state.</p>
</li>
<li><p>Third, we set <strong>handleSubmit</strong> function as the <strong>onSubmit</strong> handler of the form element, and whenever we press <strong>Upload File</strong> button the code we write inside <strong>handleSubmit</strong> function is executed.</p>
</li>
<li><p>Fourth, in the <strong>handleSubmit</strong> function we created <strong>FormData</strong> object and <strong>append</strong> the file in the <strong>selectedFile</strong> state to this object.</p>
</li>
<li><p>Fifth, as we going to send a file to the server we tell Axios that we need this <strong>FromData</strong> object to be encoded, otherwise the server will not catch the file. In order to do that, we set <strong>headers: { "Content-Type": "multipart/form-data" }</strong> to the config of the Axios object.</p>
</li>
</ul>
<blockquote>
<p>Caution!!! What about if we want to send <strong>PUT</strong> request with Axios, does the file will be uploaded? The answer is no!</p>
<p>If you want to send a <strong>PUT</strong> request then you have to send a <strong>POST</strong> request but specify the actual method you want to send is <strong>PUT</strong> request.</p>
<pre><code class="lang-javascript">formData.append(<span class="hljs-string">"_method"</span>, <span class="hljs-string">"PUT"</span>); <span class="hljs-comment">//this only works in Laravel Framework, didn't tried on other Frameworks.</span>
</code></pre>
</blockquote>
<p>Up to here, we have done with <strong>Client</strong> side and now we will write a simple code to catch the file on the <strong>Back-End</strong> and upload it to the our file storage. I am using <strong>Laravel Framework</strong> on the back-end and I'll show you the example with it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> ($request-&gt;file(<span class="hljs-string">'selectedFile'</span>)) {
$uploadedFile = $request-&gt;file(<span class="hljs-string">'selectedFile'</span>);

  <span class="hljs-keyword">if</span> ($uploadedFile) {
  $filename = Str::uuid() . <span class="hljs-string">'.'</span> . $uploadedFile-&gt;getClientOriginalExtension();
  Storage::disk(<span class="hljs-string">'public'</span>)-&gt;putFileAs(<span class="hljs-string">'uploadedFiles/'</span>, $uploadedFile, $filename);
  }
}
</code></pre>
<p>The above code, checks if the request has a file in the <strong>selectedFile</strong> variable, and if the file exists, it uploads the file into the <strong>uploadedFiles</strong> folder in the public storage of the application.</p>
]]></content:encoded></item><item><title><![CDATA[Laravel Eloquent Tutorial - Get only the fields (aka columns) we need from relation.]]></title><description><![CDATA[Laravel is a great framework to work with, and I use it every day for my 9-5 job. One of the greatest power of Laravel is, it has an ORM (Object Relational Mapping) as default called Eloquent.
I am not going to talk about what is Eloquent ORM, but I ...]]></description><link>https://codewitholgun.com/laravel-eloquent-tutorial-get-only-the-fields-aka-columns-we-need-from-relation</link><guid isPermaLink="true">https://codewitholgun.com/laravel-eloquent-tutorial-get-only-the-fields-aka-columns-we-need-from-relation</guid><category><![CDATA[Laravel]]></category><category><![CDATA[eloquent]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Sun, 20 Feb 2022 00:16:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/npxXWgQ33ZQ/upload/v1645315889266/nrTxLZ1lv.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Laravel is a great framework to work with, and I use it every day for my 9-5 job. One of the greatest power of Laravel is, it has an ORM (Object Relational Mapping) as default called Eloquent.</p>
<p>I am not going to talk about what is Eloquent ORM, but I would like to just indicate that, it makes your life easier to deal with databases.</p>
<p>Below you can find some simple usages of eloquent;</p>
<pre><code class="lang-javascript">$post = Post::find(<span class="hljs-number">1</span>)
<span class="hljs-comment">// That will run the following query in the database</span>
<span class="hljs-comment">// select * from posts where id = 1</span>
<span class="hljs-comment">// You see, it's so easy to use and powerful because we don't need to write a query anymore</span>
</code></pre>
<p>If you are using relational databases such as MySQL, MariaDB, PostgreSQL and etc, it becomes more powerful because you don't need to write complex join queries anymore.</p>
<p>For example, we want to get a specific post from the posts table but also we want to GET the author of the post as well. The following example, clearly explains that.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span> </span>{
 ....
 <span class="hljs-comment">// that will assume that we have author_id column in the posts table</span>
 public <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">author</span>(<span class="hljs-params"></span>): <span class="hljs-title">BelongsTo</span>
</span>{ 
   <span class="hljs-keyword">return</span> $this-&gt;belongsTo(related: Author::<span class="hljs-class"><span class="hljs-keyword">class</span>)
 }
}

 // <span class="hljs-title">Since</span> <span class="hljs-title">the</span> <span class="hljs-title">author</span> <span class="hljs-title">relation</span> <span class="hljs-title">is</span> <span class="hljs-title">defined</span> <span class="hljs-title">in</span> <span class="hljs-title">Post</span> <span class="hljs-title">model</span>, <span class="hljs-title">we</span> <span class="hljs-title">can</span> <span class="hljs-title">load</span> <span class="hljs-title">it</span> <span class="hljs-title">using</span> <span class="hljs-title">following</span> <span class="hljs-title">code</span>
$<span class="hljs-title">post</span> </span>= Post::<span class="hljs-keyword">with</span>(<span class="hljs-string">'author'</span>)-&gt;find(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Now, the post data will have the author data from database</span>
<span class="hljs-comment">// This is called Eager loading and it is very important learn about it.</span>
<span class="hljs-comment">// Link: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading</span>
</code></pre>
<p>Since we used eager loading to get author data with the post, all columns in the author data is loaded. This is not a problem with a small amount of data, but if we get millions of posts, each post will have an author and probably that will run a little bit slower. So, instead of getting all columns in author data, let's get some specific columns.</p>
<pre><code class="lang-javascript">$post = Post::<span class="hljs-keyword">with</span>(<span class="hljs-string">'author:id, name'</span>)-&gt;find(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Now, the post data will have the author data from database but only specific columns id and name</span>
<span class="hljs-comment">// This will make your it more faster to load data</span>
</code></pre>
<p>In the example above, we have used <strong>:id, name</strong>, so, only those columns are going to be loaded from the database.</p>
<p>That's all for this tutorial :)</p>
<p>If you like to get more content similar to that, please follow me on Twitter and on my youtube channel.</p>
<p>Youtube: https://www.youtube.com/channel/UCH-xplaz-cmloIUkYspcEhQ</p>
]]></content:encoded></item><item><title><![CDATA[How to create custom helpers in Laravel?]]></title><description><![CDATA[Laravel is one of the best frameworks out there FOR ME. I use it every day for my 9-5 job and I really love it. 
Whenever I start a new project either for my job or for my side projects, the first thing that I do is to create a new file called helper...]]></description><link>https://codewitholgun.com/how-to-create-custom-helpers-in-laravel</link><guid isPermaLink="true">https://codewitholgun.com/how-to-create-custom-helpers-in-laravel</guid><category><![CDATA[Laravel]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Olgun]]></dc:creator><pubDate>Thu, 10 Feb 2022 00:19:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644452626878/8sUw1uZJW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Laravel is one of the best frameworks out there <strong>FOR ME</strong>. I use it every day for my 9-5 job and I really love it. </p>
<p>Whenever I start a new project either for my job or for my side projects, the first thing that I do is to create a new file called <strong>helpers.php</strong>. I use that file to create the custom helper functions that I will be used for along the project.</p>
<p>For example; I really don't like to find the name of the current route in blade files following a hard way like as below;</p>
<pre><code>{{ <span class="hljs-selector-tag">Illuminate</span>\<span class="hljs-selector-tag">Support</span>\<span class="hljs-selector-tag">Facades</span>\<span class="hljs-selector-tag">Route</span><span class="hljs-selector-pseudo">::currentRouteName()</span> }}
</code></pre><p>Instead, I prefer to create a simple function that I can use anywhere in the project to get the current route name in a shorter syntax like as below;</p>
<pre><code>{{ <span class="hljs-selector-tag">getCurrentRouteName</span>() }} <span class="hljs-comment">// In the blade files,also can be used in .php files as well.</span>
</code></pre><h3 id="heading-how-to-make-sure-that-this-simple-function-can-work-anywhere">How to make sure that this simple function can work anywhere?</h3>
<p>Since Laravel as a default uses <strong>composer</strong> to manage the dependencies, we have a powerful tool under our hands and we can tell the composer to autoload any file we want and it allows us to use it in the entire project.</p>
<p>To do so; first of all, we have to create the file anywhere we want, as a default, I always put it under the <strong>app</strong> folder.</p>
<ul>
<li>app/helpers.php</li>
</ul>
<p>After I am sure that, the file exists, I create my own custom helper functions in the file as shown below; </p>
<pre><code>// function_exists <span class="hljs-keyword">method</span> <span class="hljs-keyword">is</span> initiated <span class="hljs-keyword">to</span> <span class="hljs-keyword">check</span>;
// <span class="hljs-keyword">If</span> there <span class="hljs-keyword">is</span> <span class="hljs-keyword">any</span> <span class="hljs-keyword">function</span> existed <span class="hljs-keyword">with</span> the <span class="hljs-type">name</span> <span class="hljs-keyword">of</span> getCurrentRouteName,
// <span class="hljs-keyword">If</span> <span class="hljs-keyword">not</span>, this <span class="hljs-keyword">function</span> will be added otherwise existed one will be used.
// The aim <span class="hljs-keyword">is</span> <span class="hljs-keyword">to</span> protect existing <span class="hljs-keyword">functions</span> <span class="hljs-keyword">to</span> be overwritten
<span class="hljs-keyword">if</span> (!function_exists(<span class="hljs-string">'getCurrentRouteName'</span>)) {
    <span class="hljs-keyword">function</span> getCurrentRouteName()
    {
        <span class="hljs-keyword">return</span> Illuminate\Support\Facades\Route::currentRouteName();
    }
}
</code></pre><p>At this point, I have to tell the composer to discover and autoload this file by adding it to the <strong>composer.json</strong> file as shown below otherwise my function will not be callable. </p>
<blockquote>
<p>If you don't know, <strong>composer.json</strong> is a file in that you can define the project dependencies and install them using a simple command <strong>composer install</strong> or update them with <strong>composer update</strong>.</p>
</blockquote>
<pre><code>{
    <span class="hljs-string">"require"</span>: { ... },
    <span class="hljs-string">"require-dev"</span>: { ... },
    <span class="hljs-string">"autoload"</span>: {
        <span class="hljs-string">"psr-4"</span>: { ... },
        <span class="hljs-string">"files"</span>: [
            <span class="hljs-string">"app/helpers.php"</span> <span class="hljs-comment">//this is the place I tell composer to autoload file</span>
        ]
    },
    ...
}
</code></pre><p>I created a file, add it to the composer.json file, so is it going to work? <strong>Unfortunately No</strong> 😥</p>
<p>Because I have to run a simple composer command to load all files again in the entire project just for one time.</p>
<pre><code>composer <span class="hljs-keyword">dump</span>-autoload
</code></pre><p>I am afraid to ask, but is it going to work? <strong>Yes! Congratulations, you've made it 😇</strong></p>
<p>So, now I can use <strong>getCurrentRouteName</strong> anywhere I want as I showed in the example above.</p>
<pre><code>{{ <span class="hljs-selector-tag">getCurrentRouteName</span>() }} <span class="hljs-comment">// In the blade files,also can be used in .php files as well.</span>
</code></pre><p>This is how I create custom helper functions in my Laravel projects.</p>
]]></content:encoded></item></channel></rss>