<?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[Gulzaib's blog]]></title><description><![CDATA[Gulzaib's blog]]></description><link>https://blog.gulzaib.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 26 Apr 2026 20:55:56 GMT</lastBuildDate><atom:link href="https://blog.gulzaib.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Bulk Email Sender v2.0: From Simple Tool to Professional Email Marketing Platform]]></title><description><![CDATA[Hey dev community! 👋 
Remember that bulk email sender I built with Laravel a while back? Well, it's gotten a MASSIVE upgrade! What started as a simple tool for sending bulk emails has evolved into a full-fledged email marketing platform. Let me walk...]]></description><link>https://blog.gulzaib.dev/bulk-email-sender-v20-from-simple-tool-to-professional-email-marketing-platform</link><guid isPermaLink="true">https://blog.gulzaib.dev/bulk-email-sender-v20-from-simple-tool-to-professional-email-marketing-platform</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Sat, 26 Jul 2025 08:33:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756779025/d8a04703-f0d6-46c1-bec0-9d8853e44fe4.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey dev community! 👋 </p>
<p>Remember that bulk email sender I built with Laravel a while back? Well, it's gotten a MASSIVE upgrade! What started as a simple tool for sending bulk emails has evolved into a full-fledged email marketing platform. Let me walk you through everything that's new in v2.0!</p>
<h2 id="heading-what-was-missing-in-v10">What Was Missing in v1.0?</h2>
<p>Don't get me wrong - v1.0 did its job. You could send bulk emails, and that was pretty much it. But after using it for a while (and getting feedback from the community), I realized it was missing some crucial features:</p>
<ul>
<li>No proper contact management</li>
<li>Couldn't send individual emails</li>
<li>No way to organize contacts</li>
<li>Basic UI that looked... well, basic</li>
<li>No proper queue system for large campaigns</li>
</ul>
<p>Sound familiar? Yeah, I know. It was more of a "quick hack" than a professional tool.</p>
<h2 id="heading-whats-new-in-v20-spoiler-a-lot">What's New in v2.0? (Spoiler: A LOT!)</h2>
<h3 id="heading-1-complete-contact-management-system">1. Complete Contact Management System</h3>
<p>This was the big one! Now you can:</p>
<ul>
<li>Add contacts individually or in bulk</li>
<li>Import from CSV/Excel files (with proper validation!)</li>
<li>View all contacts in a clean, paginated table</li>
<li>Edit and delete contacts easily</li>
<li>Export your contact lists</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756768325/42e6ec2e-78c4-40a2-b6ad-fe09bfd4e431.png" alt="Contact Management" /></p>
<h3 id="heading-2-smart-tag-system">2. Smart Tag System</h3>
<p>Want to send emails to just your VIP customers? Or maybe only to people from a specific city? Tags got you covered!</p>
<ul>
<li>Create custom tags (VIP, City-NYC, Newsletter-Subscribers, etc.)</li>
<li>Assign multiple tags to contacts</li>
<li>Send targeted campaigns to specific tags</li>
<li>Filter contacts by tags</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756769793/2e44f920-5393-4fd8-a965-52c054a06aa0.png" alt="Tag Management" /></p>
<h3 id="heading-3-individual-email-feature">3. Individual Email Feature</h3>
<p>Sometimes you don't want to send to everyone. Now you can:</p>
<ul>
<li>Send personalized emails to specific contacts</li>
<li>Use the same rich text editor</li>
<li>Perfect for follow-ups or personal messages</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756771639/a8d2896e-d426-4549-a5a4-e10719bf733b.png" alt="Individual Emails" /></p>
<h3 id="heading-4-modern-ui-overhaul">4. Modern UI Overhaul</h3>
<p>Let's be honest - v1.0 looked like it was built in 2010. v2.0 brings:</p>
<ul>
<li>Clean, modern Bootstrap 5 design</li>
<li>Responsive layout that works on mobile</li>
<li>Proper navigation with breadcrumbs</li>
<li>Dark mode support (because why not?)</li>
<li>Professional sidebar navigation</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756773241/82c687a0-9e25-4782-81b3-35817de26802.png" alt="Dashboard" /></p>
<h3 id="heading-5-excel-importexport">5. Excel Import/Export</h3>
<p>This one was a game-changer for productivity:</p>
<ul>
<li>Import contacts from CSV/Excel files</li>
<li>Proper validation and error handling</li>
<li>Export your contacts for backup</li>
<li>Sample CSV template provided</li>
</ul>
<h3 id="heading-6-queue-system-integration">6. 🔧 Queue System Integration</h3>
<p>No more waiting around for large campaigns! Now using Laravel Queues:</p>
<ul>
<li>Background email processing</li>
<li>No timeouts on large campaigns</li>
<li>Better server resource management</li>
<li>Real-time progress tracking</li>
</ul>
<h2 id="heading-technical-improvements">Technical Improvements</h2>
<h3 id="heading-code-quality">Code Quality</h3>
<ul>
<li>Proper MVC architecture</li>
<li>Form validation with Laravel's built-in validators</li>
<li>Database relationships and migrations</li>
<li>Queue jobs for email processing</li>
<li>Error handling and logging</li>
</ul>
<h3 id="heading-performance">Performance</h3>
<ul>
<li>Paginated contact lists</li>
<li>Optimized database queries</li>
<li>Asset optimization with Vite</li>
<li>Proper caching strategies</li>
</ul>
<h3 id="heading-security">Security</h3>
<ul>
<li>CSRF protection on all forms</li>
<li>Input sanitization</li>
<li>SQL injection prevention</li>
<li>Secure file uploads</li>
</ul>
<h2 id="heading-installation-amp-setup-its-still-super-easy">Installation &amp; Setup (It's Still Super Easy!)</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Clone the repository</span>
git <span class="hljs-built_in">clone</span> https://github.com/arafat-web/Bulk-Email-Sender.git
<span class="hljs-built_in">cd</span> Bulk-Email-Sender

<span class="hljs-comment"># Install dependencies</span>
composer install

<span class="hljs-comment"># Setup environment</span>
cp .env.example .env
php artisan key:generate

<span class="hljs-comment"># Setup database</span>
php artisan migrate --seed

<span class="hljs-comment"># Start the application</span>
php artisan serve
php artisan queue:work
</code></pre>
<p><strong>Default login:</strong> <code>admin@email.com</code> / <code>12345678</code></p>
<h2 id="heading-real-world-use-cases">Real-World Use Cases</h2>
<p>Since launching v2.0, I've seen people use it for:</p>
<ol>
<li><strong>Newsletter Management</strong> - Import subscribers, organize by interests with tags</li>
<li><strong>Event Invitations</strong> - Send bulk invites, then individual follow-ups</li>
<li><strong>Customer Support</strong> - Organize customers by product, send targeted updates</li>
<li><strong>Marketing Campaigns</strong> - Segment audiences with tags, track engagement</li>
<li><strong>Community Management</strong> - Organize members, send announcements</li>
</ol>
<h2 id="heading-what-i-learned-building-this">What I Learned Building This</h2>
<h3 id="heading-1-user-feedback-is-gold">1. User Feedback is Gold</h3>
<p>The v1.0 feedback taught me that users needed more than just "send email to everyone." They needed organization, targeting, and flexibility.</p>
<h3 id="heading-2-uiux-matters-more-than-i-thought">2. UI/UX Matters More Than I Thought</h3>
<p>A clean interface isn't just pretty - it actually makes the tool more efficient to use. Who knew? 😅</p>
<h3 id="heading-3-laravel-queues-are-amazing">3. Laravel Queues Are Amazing</h3>
<p>Seriously, if you're not using queues for heavy tasks, you're missing out. Game-changer for user experience.</p>
<h3 id="heading-4-progressive-enhancement-works">4. Progressive Enhancement Works</h3>
<p>Started simple with v1.0, then added features based on actual needs. Much better than trying to build everything upfront.</p>
<h2 id="heading-whats-next">What's Next?</h2>
<p>I'm already thinking about v3.0! Some ideas:</p>
<ul>
<li>Email templates management</li>
<li>A/B testing for campaigns</li>
<li>Analytics and reporting</li>
<li>API for integrations</li>
<li>Multi-user support</li>
</ul>
<h2 id="heading-want-to-contribute">Want to Contribute?</h2>
<p>The project is completely open source! Whether you want to:</p>
<ul>
<li>Report bugs</li>
<li>Suggest features</li>
<li>Submit pull requests</li>
<li>Improve documentation</li>
</ul>
<p>Everything is welcome! Check out the <a target="_blank" href="https://github.com/arafat-web/Bulk-Email-Sender">GitHub repo</a>.</p>
<h2 id="heading-screenshots-gallery">Screenshots Gallery</h2>
<p>Here are some more screenshots showing the features in action:</p>
<h3 id="heading-email-templates">Email Templates</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756774764/8a1a4f14-407a-4512-bd1a-2875b13163cb.png" alt="Email Templates" /></p>
<h3 id="heading-instant-campaign">Instant Campaign</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756776216/54d62c7b-0c1a-40fd-a932-5b4ceb4448cf.png" alt="Instant Campaign" /></p>
<h3 id="heading-email-accounts-settings">Email Accounts Settings</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756777644/c38ee77d-2931-4098-ba48-be1117ec2f02.png" alt="Email Accounts" /></p>
<h2 id="heading-final-thoughts">🎉 Final Thoughts</h2>
<p>Building v2.0 has been an incredible journey. What started as a simple weekend project has become something I'm genuinely proud of. The Laravel community's feedback and support made this possible.</p>
<p>If you're working on email marketing, managing newsletters, or just need to send bulk emails occasionally, give it a try! And if you find it useful, a ⭐ on GitHub would make my day!</p>
<h2 id="heading-links">🔗 Links</h2>
<ul>
<li><strong>GitHub</strong>: <a target="_blank" href="https://github.com/arafat-web/Bulk-Email-Sender">arafat-web/Bulk-Email-Sender</a></li>
<li><strong>Live Demo</strong>: <a target="_blank" href="https://arafat-web.github.io/Bulk-Email-Sender/">GitHub Pages</a></li>
<li><strong>My Website</strong>: <a target="_blank" href="https://arafatdev.com">arafatdev.com</a></li>
</ul>
<hr />
<p><em>What do you think about v2.0? Have you built similar tools? I'd love to hear your thoughts and experiences in the comments below! 👇</em></p>
]]></content:encoded></item><item><title><![CDATA[Design Your Database with dbdiagram.io (Beginner to Pro)]]></title><description><![CDATA[Designing a database schema can either be a quick sketch or a total nightmare, especially if you're working on a big project or collaborating with a team. But what if you could visually plan, share, and even generate your database schema with just a ...]]></description><link>https://blog.gulzaib.dev/design-your-database-with-dbdiagramio-beginner-to-pro</link><guid isPermaLink="true">https://blog.gulzaib.dev/design-your-database-with-dbdiagramio-beginner-to-pro</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Thu, 26 Jun 2025 14:29:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756785688/f4d05d45-7491-4c74-9575-bcdcd17339bc.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Designing a database schema can either be a quick sketch or a total nightmare, especially if you're working on a big project or collaborating with a team. But what if you could <strong>visually plan, share, and even generate your database schema</strong> with just a few lines of easy-to-write code?</p>
<p>That’s exactly what <strong><a target="_blank" href="https://dbdiagram.io">dbdiagram.io</a></strong> helps you do. Whether you're a backend developer, a full-stack dev, or a database enthusiast, this tool will <strong>make your life 10x easier</strong>.</p>
<hr />
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#what-is-dbdiagramio">What is dbdiagram.io?</a></li>
<li><a class="post-section-overview" href="#why-use-dbdiagramio">Why Use dbdiagram.io?</a></li>
<li><a class="post-section-overview" href="#supported-syntax--importing-from-tools">Supported Syntax &amp; Importing From Tools</a></li>
<li><a class="post-section-overview" href="#lets-design-a-real-example--blog-system-schema">Let’s Design a Real Example – Blog System Schema</a></li>
<li><a class="post-section-overview" href="#exporting-sql-scripts">Exporting SQL Scripts</a></li>
<li><a class="post-section-overview" href="#collaboration--sharing">Collaboration &amp; Sharing</a></li>
<li><a class="post-section-overview" href="#tips-for-better-schema-design">Tips for Better Schema Design</a></li>
<li><a class="post-section-overview" href="#final-thoughts">Final Thoughts</a></li>
</ol>
<hr />
<h3 id="heading-what-is-dbdiagramio">What is dbdiagram.io?</h3>
<p><strong>dbdiagram.io</strong> is a free, online database design tool where you can create database diagrams using a simple DSL (domain-specific language) or by importing your schema directly.</p>
<p>No need to install clunky software or memorize ER diagram notations — just focus on <strong>what your data should look like</strong>, and the tool takes care of the visualization.</p>
<hr />
<h3 id="heading-why-use-dbdiagramio">Why Use dbdiagram.io?</h3>
<ul>
<li><strong>Easy to use</strong>: Just write schema like you're writing a config file.</li>
<li><strong>Fast prototyping</strong>: Great for startups, side-projects, or freelance gigs.</li>
<li><strong>Visually shareable</strong>: Auto-generates ER diagrams that you can share via links.</li>
<li><strong>Supports real DBs</strong>: PostgreSQL, MySQL, SQL Server, Oracle, and more.</li>
<li><strong>Free for individuals and small teams</strong>.</li>
</ul>
<hr />
<h3 id="heading-supported-syntax-amp-importing-from-tools">Supported Syntax &amp; Importing From Tools</h3>
<p>You can use either:</p>
<ul>
<li><strong>dbml (Database Markup Language)</strong> – dbdiagram’s native, super readable DSL</li>
<li><strong>SQL (MySQL/PostgreSQL)</strong></li>
<li><strong>Import from tools</strong> like MySQL Workbench, PostgreSQL, Prisma, or Rails.</li>
</ul>
<hr />
<h3 id="heading-lets-design-a-real-example-blog-system-schema">Let’s Design a Real Example – Blog System Schema</h3>
<p>Here's a real-world example of designing a database schema for a blogging platform using <strong>dbml</strong> syntax.</p>
<h4 id="heading-er-diagram-dsl">ER Diagram DSL</h4>
<pre><code class="lang-dbml">Table users {
  id int [pk, increment]
  name varchar
  email varchar
  password varchar
  created_at datetime
  updated_at datetime
}

Table profiles {
  id int [pk, increment]
  user_id int [ref: &gt; users.id]
  bio text
  avatar_url varchar
  created_at datetime
  updated_at datetime
}

Table posts {
  id int [pk, increment]
  user_id int [ref: &gt; users.id]
  title varchar
  content text
  created_at datetime
  updated_at datetime
}

Table comments {
  id int [pk, increment]
  post_id int [ref: &gt; posts.id]
  user_id int [ref: &gt; users.id]
  content text
  created_at datetime
  updated_at datetime
}

Table categories {
  id int [pk, increment]
  name varchar
  created_at datetime
  updated_at datetime
}

Table post_categories {
  post_id int [ref: &gt; posts.id]
  category_id int [ref: &gt; categories.id]
  created_at datetime
  updated_at datetime
  Note: 'Composite Primary Key'
  indexes {
    (post_id, category_id) [pk]
  }
}

Table tags {
  id int [pk, increment]
  name varchar
  created_at datetime
  updated_at datetime
}

Table post_tags {
  post_id int [ref: &gt; posts.id]
  tag_id int [ref: &gt; tags.id]
  created_at datetime
  updated_at datetime
  Note: 'Composite Primary Key'
  indexes {
    (post_id, tag_id) [pk]
  }
}

Table likes {
  id int [pk, increment]
  post_id int [ref: &gt; posts.id]
  user_id int [ref: &gt; users.id]
  created_at datetime
  updated_at datetime
  indexes {
    (post_id, user_id) [unique]
  }
}

Table followers {
  follower_id int [ref: &gt; users.id]
  following_id int [ref: &gt; users.id]
  created_at datetime
  Note: 'User following relationship'
  indexes {
    (follower_id, following_id) [pk]
  }
}
</code></pre>
<p>Paste this into <a target="_blank" href="https://dbdiagram.io/d">https://dbdiagram.io/d</a>, and you’ll instantly see a fully functional, visual representation of a blogging platform’s database (below image). No clicking, dragging, or aligning just clean, readable code.</p>
<h2 id="heading-blog-dbdiagramhttpscdnhashnodecomreshashnodeimageuploadv1753756783800173c2233-7821-4f3e-8af4-b034bb43337epng"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756783800/173c2233-7821-4f3e-8af4-b034bb43337e.png" alt="blog dbdiagram" /></h2>
<h3 id="heading-exporting-sql-scripts">Exporting SQL Scripts</h3>
<p>Once your schema is complete, dbdiagram can generate the equivalent SQL for:</p>
<ul>
<li><strong>PostgreSQL</strong></li>
<li><strong>MySQL</strong></li>
<li><strong>SQL Server</strong></li>
<li><strong>SQLite</strong></li>
</ul>
<p>Just hit <code>Export &gt; SQL</code> and you’re ready to run it in your database setup.</p>
<hr />
<h3 id="heading-collaboration-amp-sharing">Collaboration &amp; Sharing</h3>
<ul>
<li><strong>Version control friendly</strong> – Save your dbml code in <code>.dbml</code> files in GitHub</li>
<li><strong>Share via link</strong> – Collaborators can view your schema without signing up</li>
<li><strong>Teams</strong> – Upgrade to a team plan to collaborate in real-time</li>
</ul>
<hr />
<h3 id="heading-tips-for-better-schema-design">Tips for Better Schema Design</h3>
<ul>
<li>Always use <code>id</code> as primary key unless you <strong>really</strong> need composite keys.</li>
<li>Add <code>created_at</code> and <code>updated_at</code> fields for better tracking.</li>
<li>Use foreign keys to define relationships instead of managing them manually.</li>
<li>Normalize, but don’t over-normalize. Balance is key.</li>
<li>Use <code>ENUM</code> or <code>lookup tables</code> for things like post status, user roles, etc.</li>
</ul>
<hr />
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Whether you're a solo developer working on your next SaaS idea, or part of a big team managing microservices, <strong>dbdiagram.io is a game-changer</strong> for designing and communicating your database architecture.</p>
<p>It saves you from visual mess, enforces good structure, and helps your team stay aligned, all without needing to open MySQL Workbench.</p>
<hr />
<h4 id="heading-useful-links">Useful Links</h4>
<ul>
<li>Try it here: <a target="_blank" href="https://dbdiagram.io">dbdiagram.io</a></li>
<li>Full documentation: <a target="_blank" href="https://dbdocs.io/docs">dbdocs.io/docs</a></li>
<li>GitHub-friendly DBML: <a target="_blank" href="https://github.com/holistics/dbml">https://github.com/holistics/dbml</a></li>
</ul>
<hr />
<p>If you loved this breakdown, let me know! Want me to cover more visual dev tools like this? Drop a comment.</p>
]]></content:encoded></item><item><title><![CDATA[🚀 10 Laravel Eloquent Tricks You Didn’t Know (But Will Love!)]]></title><description><![CDATA[Laravel’s Eloquent ORM is one of the most powerful tools in the PHP ecosystem. But let’s be honest, most developers stick to get(), where(), and find(). Eloquent actually has many hidden features that can help you write cleaner, faster, and more main...]]></description><link>https://blog.gulzaib.dev/10-laravel-eloquent-tricks-you-didnt-know-but-will-love</link><guid isPermaLink="true">https://blog.gulzaib.dev/10-laravel-eloquent-tricks-you-didnt-know-but-will-love</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Mon, 21 Apr 2025 15:06:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756791893/86d14eb9-33cf-49ce-ac80-bf402a31eb84.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Laravel’s Eloquent ORM is one of the most powerful tools in the PHP ecosystem. But let’s be honest, most developers stick to <code>get()</code>, <code>where()</code>, and <code>find()</code>. Eloquent actually has many hidden features that can help you write cleaner, faster, and more maintainable code.</p>
<p>In this blog, you’ll discover 10 lesser-known Eloquent methods and techniques that will level up your Laravel skills.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#1-withwherehas--filter-and-eager-load-in-one-query">withWhereHas() – Filter and Eager Load in One Query</a>  </li>
<li><a class="post-section-overview" href="#2-cursorpaginate--paginate-large-datasets-efficiently">cursorPaginate() – Paginate Large Datasets Efficiently</a>  </li>
<li><a class="post-section-overview" href="#3-sole--ensure-only-one-record-exists">sole() – Ensure Only One Record Exists</a>  </li>
<li><a class="post-section-overview" href="#4-upsert--insert-or-update-multiple-rows-at-once">upsert() – Insert or Update Multiple Rows at Once</a>  </li>
<li><a class="post-section-overview" href="#5-lazy--loop-through-big-data-without-memory-issues">lazy() – Loop Through Big Data Without Memory Issues</a>  </li>
<li><a class="post-section-overview" href="#6-findmany--fetch-multiple-records-easily">findMany() – Fetch Multiple Records Easily</a>  </li>
<li><a class="post-section-overview" href="#7-wherebelongsto--query-using-a-model-instance">whereBelongsTo() – Query Using a Model Instance</a>  </li>
<li><a class="post-section-overview" href="#8-is--compare-models-safely">is() – Compare Models Safely</a>  </li>
<li><a class="post-section-overview" href="#9-firstorcreate-and-updateorcreate--atomic-record-handling">firstOrCreate() and updateOrCreate() – Atomic Record Handling</a>  </li>
<li><a class="post-section-overview" href="#10-tap--inspect-queries-in-the-middle-of-a-chain">tap() – Inspect Queries in the Middle of a Chain</a></li>
</ol>
<h3 id="heading-1-withwherehas-filter-and-eager-load-in-one-query">1. withWhereHas() – Filter and Eager Load in One Query</h3>
<pre><code class="lang-php">$posts = Post::withWhereHas(<span class="hljs-string">'comments'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$query</span>) </span>{
    $query-&gt;where(<span class="hljs-string">'approved'</span>, <span class="hljs-literal">true</span>);
})-&gt;get();
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Avoids multiple queries</li>
<li>Reduces memory usage</li>
<li>Keeps your code concise</li>
</ul>
<h3 id="heading-2-cursorpaginate-paginate-large-datasets-efficiently">2. cursorPaginate() – Paginate Large Datasets Efficiently</h3>
<pre><code class="lang-php">$users = User::orderBy(<span class="hljs-string">'id'</span>)-&gt;cursorPaginate(<span class="hljs-number">50</span>);
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Great for infinite scroll or continuous loading</li>
<li>Handles large datasets without slowing down</li>
</ul>
<h3 id="heading-3-sole-ensure-only-one-record-exists">3. sole() – Ensure Only One Record Exists</h3>
<pre><code class="lang-php">$user = User::where(<span class="hljs-string">'email'</span>, <span class="hljs-string">'admin@example.com'</span>)-&gt;sole();
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Eliminates silent bugs</li>
<li>Ensures data uniqueness and consistency</li>
</ul>
<h3 id="heading-4-upsert-insert-or-update-multiple-rows-at-once">4. upsert() – Insert or Update Multiple Rows at Once</h3>
<pre><code class="lang-php">User::upsert(
    [
        [<span class="hljs-string">'email'</span> =&gt; <span class="hljs-string">'one@test.com'</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'User One'</span>],
        [<span class="hljs-string">'email'</span> =&gt; <span class="hljs-string">'two@test.com'</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'User Two'</span>],
    ],
    [<span class="hljs-string">'email'</span>], <span class="hljs-comment">// Unique column</span>
    [<span class="hljs-string">'name'</span>]   <span class="hljs-comment">// Columns to update</span>
);
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Prevents duplicates</li>
<li>Minimizes database load</li>
</ul>
<h3 id="heading-5-lazy-loop-through-big-data-without-memory-issues">5. lazy() – Loop Through Big Data Without Memory Issues</h3>
<pre><code class="lang-php">User::where(<span class="hljs-string">'active'</span>, <span class="hljs-literal">true</span>)-&gt;lazy()-&gt;each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$user</span>) </span>{
    <span class="hljs-comment">// Process user</span>
});
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Keeps memory usage low</li>
<li>Perfect for batch jobs, exports, and reporting</li>
</ul>
<h3 id="heading-6-findmany-fetch-multiple-records-easily">6. findMany() – Fetch Multiple Records Easily</h3>
<pre><code class="lang-php">$users = User::findMany([<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>]);
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Cleaner syntax</li>
<li>More efficient than multiple queries</li>
</ul>
<h3 id="heading-7-wherebelongsto-query-using-a-model-instance">7. whereBelongsTo() – Query Using a Model Instance</h3>
<pre><code class="lang-php">Post::whereBelongsTo($user)-&gt;get();
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>More readable and expressive</li>
<li>Helps when working directly with models</li>
</ul>
<h3 id="heading-8-is-compare-models-safely">8. is() – Compare Models Safely</h3>
<pre><code class="lang-php"><span class="hljs-keyword">if</span> ($post-&gt;author-&gt;is($currentUser)) {
    <span class="hljs-comment">// Perform action</span>
}
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Safer than manual comparisons</li>
<li>Works with unsaved models too</li>
</ul>
<h3 id="heading-9-firstorcreate-and-updateorcreate-atomic-record-handling">9. firstOrCreate() and updateOrCreate() – Atomic Record Handling</h3>
<pre><code class="lang-php">$user = User::updateOrCreate(
    [<span class="hljs-string">'email'</span> =&gt; <span class="hljs-string">'someone@example.com'</span>],
    [<span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Someone New'</span>]
);
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Avoids duplicate records</li>
<li>Clean and readable</li>
</ul>
<h3 id="heading-10-tap-inspect-queries-in-the-middle-of-a-chain">10. tap() – Inspect Queries in the Middle of a Chain</h3>
<pre><code class="lang-php">User::where(<span class="hljs-string">'active'</span>, <span class="hljs-literal">true</span>)
    -&gt;tap(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$query</span>) </span>{
        logger($query-&gt;toSql());
    })
    -&gt;get();
</code></pre>
<p><strong>Why it’s useful:</strong></p>
<ul>
<li>Great for debugging</li>
<li>Keeps the method chain intact</li>
</ul>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Laravel Eloquent is packed with powerful features that go beyond the basics. By using these lesser-known methods, you can write code that is not only more efficient but also easier to maintain and scale.</p>
<p>Whether you're building APIs, admin panels, or full-blown applications, these tips will give your Laravel skills an extra edge.</p>
<h3 id="heading-useful-links">Useful Links</h3>
<ul>
<li><a target="_blank" href="https://laravel.com/docs/eloquent">Official Eloquent Documentation</a>  </li>
<li><a target="_blank" href="https://dev.to/arafatweb">More Laravel Tips on Dev.to</a>  </li>
<li><a target="_blank" href="https://github.com/arafat-web">Follow Me on GitHub</a> for Laravel projects and tutorials</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Thanks, it's great. I got you from Google News Suggestions]]></title><description><![CDATA[Thanks, it's great. I got you from Google News Suggestions]]></description><link>https://blog.gulzaib.dev/thanks-its-great-i-got-you-from-google-news-suggestions-d0f21deb21fa</link><guid isPermaLink="true">https://blog.gulzaib.dev/thanks-its-great-i-got-you-from-google-news-suggestions-d0f21deb21fa</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Wed, 19 Mar 2025 00:46:43 GMT</pubDate><content:encoded><![CDATA[<p>Thanks, it's great. I got you from Google News Suggestions</p>
]]></content:encoded></item><item><title><![CDATA[Best Practices for Returning API Responses in Express.js Controllers]]></title><description><![CDATA[When building APIs with Express.js , it's crucial to follow best practices for structuring and returning API responses. A well-designed API not only improves developer experience but also ensures consistency, scalability, and maintainability of your ...]]></description><link>https://blog.gulzaib.dev/best-practices-for-returning-api-responses-in-expressjs-controllers</link><guid isPermaLink="true">https://blog.gulzaib.dev/best-practices-for-returning-api-responses-in-expressjs-controllers</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Sat, 15 Feb 2025 18:56:16 GMT</pubDate><content:encoded><![CDATA[<p>When building APIs with Express.js , it's crucial to follow best practices for structuring and returning API responses. A well-designed API not only improves developer experience but also ensures consistency, scalability, and maintainability of your codebase. In this article, we’ll explore some key principles and patterns for returning API responses in Express.js controllers.</p>
<hr />
<h2 id="heading-1-use-consistent-response-structures">1. Use Consistent Response Structures</h2>
<p>Consistency is key when designing APIs. Every response should follow a predictable structure so that clients know what to expect. A common pattern is to include three main components in every response:</p>
<ul>
<li>Status : Indicates whether the request was successful or not.</li>
<li>Message : Provides a human-readable description of the result.</li>
<li>Data : Contains the payload or result of the operation (if applicable).</li>
</ul>
<p>Here’s an example of a consistent response structure:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"status"</span>: <span class="hljs-string">"success"</span>,
  <span class="hljs-attr">"message"</span>: <span class="hljs-string">"User retrieved successfully"</span>,
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"john.doe@example.com"</span>
  }
}
</code></pre>
<p>For error responses, you can use a similar structure but with an <code>error</code> field instead of <code>data</code>:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"status"</span>: <span class="hljs-string">"error"</span>,
  <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Invalid credentials"</span>,
  <span class="hljs-attr">"error"</span>: {
    <span class="hljs-attr">"code"</span>: <span class="hljs-number">401</span>,
    <span class="hljs-attr">"details"</span>: <span class="hljs-string">"The provided email or password is incorrect."</span>
  }
}
</code></pre>
<h2 id="heading-2-leverage-middleware-for-error-handling">2. Leverage Middleware for Error Handling</h2>
<p>In Express.js, middleware functions are a powerful way to handle errors consistently across your application. Instead of handling errors inline within each route, you can create a centralized error-handling middleware.</p>
<p>Here’s an example of an error-handling middleware:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Error-handling middleware</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">errorHandler</span>(<span class="hljs-params">err, req, res, next</span>) </span>{
  <span class="hljs-built_in">console</span>.error(err.stack);

  <span class="hljs-keyword">const</span> statusCode = err.statusCode || <span class="hljs-number">500</span>;
  <span class="hljs-keyword">const</span> message = err.message || <span class="hljs-string">'Internal Server Error'</span>;

  res.status(statusCode).json({
    <span class="hljs-attr">status</span>: <span class="hljs-string">'error'</span>,
    <span class="hljs-attr">message</span>: message,
    <span class="hljs-attr">error</span>: {
      <span class="hljs-attr">code</span>: statusCode,
      <span class="hljs-attr">details</span>: err.details || <span class="hljs-string">'Something went wrong on the server.'</span>
    }
  });
}

<span class="hljs-comment">// Use the middleware in your app</span>
app.use(errorHandler);
</code></pre>
<p>Now, whenever an error occurs in your routes, you can pass it to the next() function, and the middleware will handle it:</p>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">'/user/:id'</span>, <span class="hljs-keyword">async</span> (req, res, next) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> User.findById(req.params.id);
    <span class="hljs-keyword">if</span> (!user) {
      <span class="hljs-keyword">throw</span> { <span class="hljs-attr">statusCode</span>: <span class="hljs-number">404</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">'User not found'</span> };
    }
    res.json({
      <span class="hljs-attr">status</span>: <span class="hljs-string">'success'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'User retrieved successfully'</span>,
      <span class="hljs-attr">data</span>: user
    });
  } <span class="hljs-keyword">catch</span> (err) {
    next(err); <span class="hljs-comment">// Pass the error to the error-handling middleware</span>
  }
});
</code></pre>
<h2 id="heading-3-use-http-status-codes-appropriately">3. Use HTTP Status Codes Appropriately</h2>
<p>HTTP status codes provide a standardized way to indicate the result of an API request. Always use the appropriate status code to reflect the outcome of the operation. Here are some common status codes and their use cases:</p>
<ul>
<li>200 OK : The request was successful.</li>
<li>201 Created : A new resource was successfully created.</li>
<li>400 Bad Request : The request was invalid or malformed.</li>
<li>401 Unauthorized : Authentication is required or has failed.</li>
<li>403 Forbidden : The client does not have permission to access the resource.</li>
<li>404 Not Found : The requested resource could not be found.</li>
<li>500 Internal Server Error : An unexpected error occurred on the server.
For example, when creating a new user, you might return a <code>201 Created</code> status code:<pre><code class="lang-javascript">app.post(<span class="hljs-string">'/users'</span>, <span class="hljs-keyword">async</span> (req, res, next) =&gt; {
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> newUser = <span class="hljs-keyword">await</span> User.create(req.body);
  res.status(<span class="hljs-number">201</span>).json({
    <span class="hljs-attr">status</span>: <span class="hljs-string">'success'</span>,
    <span class="hljs-attr">message</span>: <span class="hljs-string">'User created successfully'</span>,
    <span class="hljs-attr">data</span>: newUser
  });
} <span class="hljs-keyword">catch</span> (err) {
  next(err);
}
});
</code></pre>
</li>
</ul>
<h2 id="heading-4-validate-input-data">4. Validate Input Data</h2>
<p>Validating input data is essential to ensure that your API receives the correct information and prevents malicious or malformed requests. You can use libraries like Joi or express-validator to validate request data.</p>
<p>Here’s an example using express-validator :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { body, validationResult } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-validator'</span>);

app.post(
  <span class="hljs-string">'/users'</span>,
  [
    body(<span class="hljs-string">'name'</span>).notEmpty().withMessage(<span class="hljs-string">'Name is required'</span>),
    body(<span class="hljs-string">'email'</span>).isEmail().withMessage(<span class="hljs-string">'Invalid email address'</span>),
    body(<span class="hljs-string">'password'</span>).isLength({ <span class="hljs-attr">min</span>: <span class="hljs-number">6</span> }).withMessage(<span class="hljs-string">'Password must be at least 6 characters'</span>)
  ],
  <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> errors = validationResult(req);
    <span class="hljs-keyword">if</span> (!errors.isEmpty()) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({
        <span class="hljs-attr">status</span>: <span class="hljs-string">'error'</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'Validation failed'</span>,
        <span class="hljs-attr">error</span>: {
          <span class="hljs-attr">code</span>: <span class="hljs-number">400</span>,
          <span class="hljs-attr">details</span>: errors.array()
        }
      });
    }

    <span class="hljs-comment">// Proceed with creating the user</span>
    next();
  }
);
</code></pre>
<h2 id="heading-5-paginate-large-datasets">5. Paginate Large Datasets</h2>
<p>When dealing with large datasets, it’s important to paginate your responses to improve performance and reduce the load on both the server and the client. Include pagination metadata in your response to help clients navigate through the data.</p>
<p>Here’s an example of a paginated response:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"status"</span>: <span class="hljs-string">"success"</span>,
  <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Users retrieved successfully"</span>,
  <span class="hljs-attr">"data"</span>: [
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span> },
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Jane Smith"</span> }
  ],
  <span class="hljs-attr">"pagination"</span>: {
    <span class="hljs-attr">"total"</span>: <span class="hljs-number">100</span>,
    <span class="hljs-attr">"page"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"limit"</span>: <span class="hljs-number">10</span>,
    <span class="hljs-attr">"pages"</span>: <span class="hljs-number">10</span>
  }
}
</code></pre>
<p>You can implement pagination in Express.js like this:</p>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">'/users'</span>, <span class="hljs-keyword">async</span> (req, res, next) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> page = <span class="hljs-built_in">parseInt</span>(req.query.page) || <span class="hljs-number">1</span>;
    <span class="hljs-keyword">const</span> limit = <span class="hljs-built_in">parseInt</span>(req.query.limit) || <span class="hljs-number">10</span>;

    <span class="hljs-keyword">const</span> users = <span class="hljs-keyword">await</span> User.find()
      .skip((page - <span class="hljs-number">1</span>) * limit)
      .limit(limit);

    <span class="hljs-keyword">const</span> total = <span class="hljs-keyword">await</span> User.countDocuments();

    res.json({
      <span class="hljs-attr">status</span>: <span class="hljs-string">'success'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'Users retrieved successfully'</span>,
      <span class="hljs-attr">data</span>: users,
      <span class="hljs-attr">pagination</span>: {
        total,
        page,
        limit,
        <span class="hljs-attr">pages</span>: <span class="hljs-built_in">Math</span>.ceil(total / limit)
      }
    });
  } <span class="hljs-keyword">catch</span> (err) {
    next(err);
  }
});
</code></pre>
<h2 id="heading-6-secure-your-api-responses">6. Secure Your API Responses</h2>
<p>Always sanitize and filter sensitive data before sending it in API responses. For example, avoid exposing sensitive fields like passwords or tokens in your responses.</p>
<p>Here’s an example of how to exclude sensitive fields:</p>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">'/user/:id'</span>, <span class="hljs-keyword">async</span> (req, res, next) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> User.findById(req.params.id).select(<span class="hljs-string">'-password'</span>);
    <span class="hljs-keyword">if</span> (!user) {
      <span class="hljs-keyword">throw</span> { <span class="hljs-attr">statusCode</span>: <span class="hljs-number">404</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">'User not found'</span> };
    }
    res.json({
      <span class="hljs-attr">status</span>: <span class="hljs-string">'success'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'User retrieved successfully'</span>,
      <span class="hljs-attr">data</span>: user
    });
  } <span class="hljs-keyword">catch</span> (err) {
    next(err);
  }
});
</code></pre>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>By following these best practices, you can build robust, scalable, and maintainable APIs with Express.js. Consistent response structures, proper error handling, appropriate HTTP status codes, input validation, pagination, and security measures are all critical components of a well-designed API.</p>
<p>Remember, the goal is to make your API intuitive and easy to use for developers, while ensuring that it remains secure and performant. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Optimizing PHP Applications: Why Separate Read and Write Models Matter]]></title><description><![CDATA[Models are a great tool to communicate with a data storage. We can define how the data looks like, and that makes sure that it’s compatible with the data storage, typically a database. Once we have a model that validates our input and helps us write ...]]></description><link>https://blog.gulzaib.dev/optimizing-php-applications-why-separate-read-and-write-models-matter</link><guid isPermaLink="true">https://blog.gulzaib.dev/optimizing-php-applications-why-separate-read-and-write-models-matter</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Sat, 15 Feb 2025 18:42:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753755603218/c6a705cb-553d-4587-909b-ccca7de8f7bb.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Models are a great tool to communicate with a data storage. We can define how the data looks like, and that makes sure that it’s compatible with the data storage, typically a database. Once we have a model that validates our input and helps us write that data we could be tempted to use it also for retrieving data. Except for some basic CRUD applications, that is not usually such a good idea. Let’s see why.</p>
<h2 id="heading-set-up-a-model-to-work-with">Set up a model to work with</h2>
<p>Let’s use a simple User model and the interface of a repository, we don’t really need the details here. But let’s assume we have some assertion library that we use to validate that every model created is valid.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $password,
    </span>) </span>{
        Assert::email($email);
        Assert::notEmpty($name);
        Assert::password($password, strength: <span class="hljs-number">3</span>);
    }
}
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
}
</code></pre>
<p>So main use case, we get data for a new user, it validates that the name is not empty, the email is a valid email and that the password complies with whatever we defined as strength level 3. Then we send it to the repository and save it. Job done.</p>
<pre><code class="lang-php">$user = <span class="hljs-keyword">new</span> User(
    $request-&gt;get(<span class="hljs-string">'email'</span>),
    $request-&gt;get(<span class="hljs-string">'name'</span>),
    $request-&gt;get(<span class="hljs-string">'password'</span>),
);
$repository-&gt;save($user);
</code></pre>
<h2 id="heading-problem-model-properties-that-should-not-be-read">Problem: Model properties that should not be read</h2>
<p>So now we want to read a user by email from the database to return a json representation of it for a client to present some user profile. What happens if we add a read method to our repository reusing the same model?</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $email</span>): <span class="hljs-title">User</span></span>;
}
<span class="hljs-comment">// Inside some controller class</span>
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
    json_encode(
        $repository-&gt;get($request-&gt;get(<span class="hljs-string">'email'</span>))
    ),
);
</code></pre>
<p>So what are we getting here?</p>
<pre><code class="lang-php">{
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"peter@dailybugle.com"</span>,
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Peter Parker"</span>,
  <span class="hljs-string">"password"</span>: <span class="hljs-string">"<span class="hljs-subst">$2y</span><span class="hljs-subst">$10</span><span class="hljs-subst">$OEaTphGkW0HQv4QNxtptQOE</span>.BSQDnpwrB.\/VGqIgjMEhvIr22jnFK"</span>
}
</code></pre>
<p>The first thing that should cross our minds when we watch this is that passwords, even encrypted, should never, ever be sent in any kind of communication from the server. So this is an important security concern.</p>
<p>Even if this is probably the worst possible case of an information leak caused by using a write model as a read model, it’s not the only one. Another common issue is just sending irrelevant information to the client. For example, we could have an active boolean we can use for enabling or disabling users that would be useless for the client, because if the user is not active the request will respond with a 404 Not Found. Irrelevant data means that we are sending bytes that will never be consumed, hurting performance. It may be little, but everything adds and this has an easy solution.</p>
<p>So what do we do? Provide a return with a restricted list of data? This could solve these problems.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-comment">// ...</span>

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">read</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'email'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;email,
            <span class="hljs-string">'name'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;name,
        ];
    }
}
</code></pre>
<p>But there are more issues to solve, let’s see.</p>
<h2 id="heading-problem-unnecessary-validations">Problem: Unnecessary validations</h2>
<p>Talking about performance, we have validations in the model constructor, but are those needed when we fetch data that is already in the database? They must have been valid the moment they were stored, so it can be argued that running those validations again is a waste.</p>
<p>But not only a waste, it can be a real problem. Validations might evolve and that can impact the ability to fetch results if we use a write model which makes use of validations. Suppose an application that validates that emails for users have a valid email format, but at some point another rule is added to blacklist some domains in email addresses. The validation is updated, but the existing users can’t really be updated, because they still expect communications via that email address.</p>
<p>Now we get a request for a list of 100 users in which one of them has a blacklisted domain, what happens? The whole request is considered an error. And what do we send the user? A 400 Bad Request response like if some user input was wrong? This is not the client’s fault but the server’s. In this case it should be some kind of 500 error.</p>
<p>To avoid this, I’ve seen some complex solutions involving Reflection and an instance without constructor. If we really had to use the write model in cases we don’t want to validate I would move the assertions to a static constructor though, like this.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $password,
    </span>) </span>{}

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">create</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $email, <span class="hljs-keyword">string</span> $name, <span class="hljs-keyword">string</span> $password</span>): <span class="hljs-title">self</span>
    </span>{
        Assert::email($email);
        Assert::notEmpty($name);
        Assert::password($password, strength: <span class="hljs-number">3</span>);

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">self</span>($email, $name, $password);
    }
}
</code></pre>
<p>This way, when creating a new model that requires validation I can do <code>User::new()</code>, and use the constructor when fetching data from the database. Solves some issues, but there are more.</p>
<h2 id="heading-problem-adding-extra-data-to-the-model">Problem: Adding extra data to the model</h2>
<p>Another common situation is the client requiring some more data for the view. In our example, the view might need to show the number of comments that a user has created in the system. That’s not part of the model, but it looks wasteful not to add that in the same HTTP response and keep the client waiting for a second one just because the data does not match the write model.</p>
<p>Even if we try to add the data in the same request, sticking to this write model means that we can’t use a single database request to get the whole set of data, though in many cases that could be solved with a simple SQL join. Instead we get the write model and then do another database request to fetch the missing data, and compose it before sending it to the client.</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
    json_encode(
        array_merge(
            $repository-&gt;get($request-&gt;get(<span class="hljs-string">'email'</span>)),
            [<span class="hljs-string">'comments'</span> =&gt; $commentRepository-&gt;count($request-&gt;get(<span class="hljs-string">'email'</span>))]
        )

    ),
);
</code></pre>
<p>It works, but it means an extra database query with it’s impact in the performance. And it also hurts re-usability, as you can’t just call the repository somewhere else, you also need to copy and paste the comments part.</p>
<h2 id="heading-problem-are-inserts-and-updates-really-the-same">Problem: Are inserts and updates really the same?</h2>
<p>For a last problem, this is not really a write vs read model, but when we are updating a model, can we really use the same class that we use when creating it?</p>
<p>So if we create a new user with this model, we expect name, email and password. For creating a user that’s ok, but in our example our security expert requires that passwords are updated in a specific way, which involves the user requesting a password change, an email being sent to the user with a limited time token and then validating that token to accept the new password.</p>
<p>The password should never be updated in any other way, so what do we do if we use the same model we already have for updating the user? We will have two different places in the code where we update the user, one for password, another for anything else.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">update</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
}
<span class="hljs-comment">// Updating name</span>
$user = <span class="hljs-keyword">new</span> User(
    $request-&gt;get(<span class="hljs-string">'email'</span>),
    $request-&gt;get(<span class="hljs-string">'name'</span>),
    <span class="hljs-string">'WHAT DO WE DO WITH PASSWORD HERE?'</span>,
);

$repository-&gt;update($user);
<span class="hljs-comment">// Updating password</span>
$user = <span class="hljs-keyword">new</span> User(
    $request-&gt;get(<span class="hljs-string">'email'</span>),
    <span class="hljs-string">'WHAT DO WE DO WITH NAME HERE?'</span>,
    $request-&gt;get(<span class="hljs-string">'password'</span>),
);

$repository-&gt;update($user);
</code></pre>
<p>Now we have to deal with data in the model that must not be processed, which will make our repository implementation unnecessarily more complex. It will also force the model creation to provide data that will not be available and will not be used, making code much harder to understand. And finally, we introduce a fragile implementation that, if used incorrectly, can cause the update of something that should not be updated, just because it is in the model. If we process the user name change in a way that triggers a password update, that’s a serious problem.</p>
<h2 id="heading-solution-individual-model-for-each-case">Solution: Individual model for each case</h2>
<p>How can we solve all the problems when reading a user? A dedicated model will do.</p>
<pre><code class="lang-php"><span class="hljs-keyword">final</span> readonly <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRead</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> $commentCount,
    </span>) </span>{}
}
</code></pre>
<p>We can have another repository to fetch it.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserReadRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $email</span>): <span class="hljs-title">UserRead</span></span>;
}
</code></pre>
<p>This implementation, assuming a relational SQL database, would not select the password form the table which is not in the read model, solving problem number 1. This read model does not include validations solving problem number 2. And this model has a place for the comments count that can be implemented in the new repository by using a join in a single query, solving problem number 3.</p>
<p>Even more, if we have more representations of a user, we should have a different read model to cover each one. We could have a UserWithLastCommentsRead for example.</p>
<p>And for the update problems? You probably guessed. Individual models for each update.</p>
<pre><code class="lang-php"><span class="hljs-keyword">final</span> readonly <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserDataUpdate</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
    </span>) </span>{
        Assert::notEmpty($name);
    }
}
<span class="hljs-keyword">final</span> readonly <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserPasswordUpdate</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $password,
    </span>) </span>{
        Assert::password($password, strength: <span class="hljs-number">3</span>);
    }
}
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateData</span>(<span class="hljs-params">UserDataUpdate $userDataUpdate</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updatePassword</span>(<span class="hljs-params">UserPasswordUpdate $userPasswordUpdate</span>): <span class="hljs-title">void</span></span>;
}
</code></pre>
<p>Now there are no mistakes or unnecessary data. Each update is isolated and it is much more protected from bugs.</p>
<p>Note that in the update models I didn’t add the email validation. That is intentional because it is going to be used to find the user, and if we have an evolved validation, as commented before, we would not be able to find older users with emails that are not valid anymore, but still in the database anyways.</p>
<h2 id="heading-last-words">Last words</h2>
<p>This is really not that different as we model objects in the real world. We never consider everything about a real life object in a particular context. For example a car.</p>
<p>If a car is modeled by a driver, we can expect the positioning of the seat and the rear mirrors to be really important, while at the same time it is irrelevant for a mechanic doing some maintenance. The mechanic will probably be more concerned about metrics on the engine that are not important to the driver. And a kid at the school learning about transport methods will probably just care about it being a land transport with 4 wheels.</p>
<p>If we use different models for the same real life objects we can definitely do the same for our code models.</p>
]]></content:encoded></item><item><title><![CDATA[Tencent Cloud Integrates DeepSeek R1 to Revolutionize AI Deployment in Just 3 Minutes]]></title><description><![CDATA[Tencent Cloud, the cloud computing division of Chinese tech giant Tencent, has announced the integration of DeepSeek's R1 model into its Hyper Application Inventor service. This collaboration enables developers to access advanced artificial intellige...]]></description><link>https://blog.gulzaib.dev/tencent-cloud-integrates-deepseek-r1-to-revolutionize-ai-deployment-in-just-3-minutes</link><guid isPermaLink="true">https://blog.gulzaib.dev/tencent-cloud-integrates-deepseek-r1-to-revolutionize-ai-deployment-in-just-3-minutes</guid><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[AI]]></category><category><![CDATA[Deepseek]]></category><category><![CDATA[Tencent]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Cloud Computing]]></category><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Mon, 03 Feb 2025 06:57:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738565598876/013e95b4-eb94-4098-98c9-42d852e0cbd5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Tencent Cloud, the cloud computing division of Chinese tech giant Tencent, has announced the integration of DeepSeek's R1 model into its Hyper Application Inventor service. This collaboration enables developers to access advanced artificial intelligence (AI) capabilities swiftly, reducing deployment time to just three minutes.</p>
<p>Traditionally, setting up AI models involves a series of complex steps, including purchasing GPUs, installing drivers, configuring networks and storage, setting up environments, and downloading models. With this integration, developers can bypass these hurdles, streamlining the process significantly.</p>
<p>Industry expert Liu Dingding highlighted the significance of this development for startups, noting that it provides a seamless, ready-to-use AI solution. "Since users no longer need technical expertise or deal with hardware procurement, they can concentrate on leveraging AI for their business applications," Liu stated. He also emphasized that this move reflects a growing trend of collaboration among Chinese tech firms, fostering a cooperative environment in the competitive tech landscape.</p>
<p>This announcement follows closely on the heels of Huawei's recent launch of the DeepSeek R1/V3 inference service on its cloud platform. Huawei claims that models deployed on its platform can achieve performance comparable to global high-end graphics processing unit (GPU) models.</p>
<p>DeepSeek has been gaining global recognition for its groundbreaking AI capabilities. Many international tech companies, including U.S.-based GPU maker Nvidia, are integrating DeepSeek into their platforms, acknowledging its technological prowess. Notably, DeepSeek's AI assistant recently became the most downloaded mobile AI app across 140 markets, with India leading in new user adoption.</p>
<p>However, it's worth noting that some countries have recently moved to block the Chinese AI platform, citing "security concerns."</p>
<p>The collaboration between Tencent Cloud and DeepSeek marks a significant step in making advanced AI solutions more accessible to developers, particularly benefiting startups and small enterprises. This partnership not only streamlines the deployment process but also exemplifies the increasing cooperation among Chinese tech companies in the global AI arena.</p>
]]></content:encoded></item><item><title><![CDATA[Why Avoid Using the Same PHP Models for Writing and Reading]]></title><description><![CDATA[Models are a great tool to communicate with a data storage. We can define how the data looks like, and that makes sure that it’s compatible with the data storage, typically a database. Once we have a model that validates our input and helps us write ...]]></description><link>https://blog.gulzaib.dev/why-avoid-using-the-same-php-models-for-writing-and-reading</link><guid isPermaLink="true">https://blog.gulzaib.dev/why-avoid-using-the-same-php-models-for-writing-and-reading</guid><category><![CDATA[PHP]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[best practices]]></category><category><![CDATA[architecture]]></category><category><![CDATA[optimization]]></category><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Sun, 02 Feb 2025 18:34:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738520223377/3922948d-8b8c-4448-96a8-2656e7f410b9.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Models are a great tool to communicate with a data storage. We can define how the data looks like, and that makes sure that it’s compatible with the data storage, typically a database. Once we have a model that validates our input and helps us write that data we could be tempted to use it also for retrieving data. Except for some basic CRUD applications, that is not usually such a good idea. Let’s see why.</p>
<h2 id="heading-set-up-a-model-to-work-with"><strong>Set up a model to work with</strong></h2>
<p>Let’s use a simple User model and the interface of a repository, we don’t really need the details here. But let’s assume we have some assertion library that we use to validate that every model created is valid.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $password,
    </span>) </span>{
        Assert::email($email);
        Assert::notEmpty($name);
        Assert::password($password, strength: <span class="hljs-number">3</span>);
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
}
</code></pre>
<p>So main use case, we get data for a new user, it validates that the name is not empty, the email is a valid email and that the password complies with whatever we defined as strength level 3. Then we send it to the repository and save it. Job done.</p>
<pre><code class="lang-php">$user = <span class="hljs-keyword">new</span> User(
    $request-&gt;get(<span class="hljs-string">'email'</span>),
    $request-&gt;get(<span class="hljs-string">'name'</span>),
    $request-&gt;get(<span class="hljs-string">'password'</span>),
);

$repository-&gt;save($user);
</code></pre>
<h2 id="heading-problem-model-properties-that-should-not-be-read"><strong>Problem: Model properties that should not be read</strong></h2>
<p>So now we want to read a user by email from the database to return a json representation of it for a client to present some user profile. What happens if we add a read method to our repository reusing the same model?</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $email</span>): <span class="hljs-title">User</span></span>;
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-comment">// Inside some controller class</span>
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
    json_encode(
        $repository-&gt;get($request-&gt;get(<span class="hljs-string">'email'</span>))
    ),
);
</code></pre>
<p>So what are we getting here?</p>
<pre><code class="lang-php">{
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"gulzaib@test-email.com"</span>,
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Gulzaib"</span>,
  <span class="hljs-string">"password"</span>: <span class="hljs-string">"<span class="hljs-subst">$2y</span><span class="hljs-subst">$10</span><span class="hljs-subst">$OEaTphGkW0HQv4QNxtptQOE</span>.BSQDnpwrB.\/VGqIgjMEhvIr22jnFK"</span>
}
</code></pre>
<p>The first thing that should cross our minds when we watch this is that <strong>passwords, even encrypted, should never, ever be sent</strong> in any kind of communication from the server. So this is an important security concern.</p>
<p>Even if this is probably the worst possible case of an information leak caused by using a write model as a read model, it’s not the only one. Another common issue is just sending irrelevant information to the client. For example, we could have an <code>active</code> boolean we can use for enabling or disabling users that would be useless for the client, because if the user is not active the request will respond with a <code>404 Not Found</code>. Irrelevant data means that we are sending bytes that will never be consumed, hurting performance. It may be little, but everything adds and this has an easy solution.</p>
<p>So what do we do? Provide a return with a restricted list of data? This could solve these problems.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-comment">// ...</span>

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">read</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'email'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;email,
            <span class="hljs-string">'name'</span> =&gt; <span class="hljs-keyword">$this</span>-&gt;name,
        ];
    }
}
</code></pre>
<p>But there are more issues to solve, let’s see.</p>
<h2 id="heading-problem-unnecessary-validations"><strong>Problem: Unnecessary validations</strong></h2>
<p>Talking about performance, we have validations in the model constructor, but are those needed when we fetch data that is already in the database? They must have been valid the moment they were stored, so it can be argued that running those validations again is a waste.</p>
<p>But not only a waste, it can be a real problem. Validations might evolve and that can impact the ability to fetch results if we use a write model which makes use of validations. Suppose an application that validates that emails for users have a valid email format, but at some point another rule is added to blacklist some domains in email addresses. The validation is updated, but the existing users can’t really be updated, because they still expect communications via that email address.</p>
<p>Now we get a request for a list of 100 users in which one of them has a blacklisted domain, what happens? The whole request is considered an error. And what do we send the user? A <code>400 Bad Request</code> response like if some user input was wrong? This is not the client’s fault but the server’s. In this case it should be some kind of <code>500</code> error.</p>
<p>To avoid this, I’ve seen some complex solutions involving <a target="_blank" href="https://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php">Reflection and an instance without constructor</a>. If we really had to use the write model in cases we don’t want to validate I would move the assertions to a static constructor though, like this.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $password,
    </span>) </span>{}

    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">create</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $email, <span class="hljs-keyword">string</span> $name, <span class="hljs-keyword">string</span> $password</span>): <span class="hljs-title">self</span>
    </span>{
        Assert::email($email);
        Assert::notEmpty($name);
        Assert::password($password, strength: <span class="hljs-number">3</span>);

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">self</span>($email, $name, $password);
    }
}
</code></pre>
<p>This way, when creating a new model that requires validation I can do <code>User::new()</code>, and use the constructor when fetching data from the database. Solves some issues, but there are more.</p>
<h2 id="heading-problem-adding-extra-data-to-the-model"><strong>Problem: Adding extra data to the model</strong></h2>
<p>Another common situation is the client requiring some more data for the view. In our example, the view might need to show the number of comments that a user has created in the system. That’s not part of the model, but it looks wasteful not to add that in the same HTTP response and keep the client waiting for a second one just because the data does not match the write model.</p>
<p>Even if we try to add the data in the same request, sticking to this write model means that we can’t use a single database request to get the whole set of data, though in many cases that could be solved with a simple SQL join. Instead we get the write model and then do another database request to fetch the missing data, and compose it before sending it to the client.</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
    json_encode(
        array_merge(
            $repository-&gt;get($request-&gt;get(<span class="hljs-string">'email'</span>)),
            [<span class="hljs-string">'comments'</span> =&gt; $commentRepository-&gt;count($request-&gt;get(<span class="hljs-string">'email'</span>))]
        )

    ),
);
</code></pre>
<p>It works, but it means an extra database query with it’s impact in the performance. And it also hurts re-usability, as you can’t just call the repository somewhere else, you also need to copy and paste the comments part.</p>
<h2 id="heading-problem-are-inserts-and-updates-really-the-same"><strong>Problem: Are inserts and updates really the same?</strong></h2>
<p>For a last problem, this is not really a write vs read model, but when we are updating a model, can we really use the same class that we use when creating it?</p>
<p>So if we create a new user with this model, we expect name, email and password. For creating a user that’s ok, but in our example our security expert requires that passwords are updated in a specific way, which involves the user requesting a password change, an email being sent to the user with a limited time token and then validating that token to accept the new password.</p>
<p>The password should never be updated in any other way, so what do we do if we use the same model we already have for updating the user? We will have two different places in the code where we update the user, one for password, another for anything else.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">update</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-comment">// Updating name</span>
$user = <span class="hljs-keyword">new</span> User(
    $request-&gt;get(<span class="hljs-string">'email'</span>),
    $request-&gt;get(<span class="hljs-string">'name'</span>),
    <span class="hljs-string">'WHAT DO WE DO WITH PASSWORD HERE?'</span>,
);

$repository-&gt;update($user);
</code></pre>
<pre><code class="lang-php"><span class="hljs-comment">// Updating password</span>
$user = <span class="hljs-keyword">new</span> User(
    $request-&gt;get(<span class="hljs-string">'email'</span>),
    <span class="hljs-string">'WHAT DO WE DO WITH NAME HERE?'</span>,
    $request-&gt;get(<span class="hljs-string">'password'</span>),
);

$repository-&gt;update($user);
</code></pre>
<p>Now we have to deal with data in the model that must not be processed, which will make our repository implementation unnecessarily more complex. It will also force the model creation to provide data that will not be available and will not be used, making code much harder to understand. And finally, we introduce a fragile implementation that, if used incorrectly, can cause the update of something that should not be updated, just because it is in the model. If we process the user name change in a way that triggers a password update, that’s a serious problem.</p>
<h2 id="heading-solution-individual-model-for-each-case"><strong>Solution: Individual model for each case</strong></h2>
<p>How can we solve all the problems when reading a user? A dedicated model will do.</p>
<pre><code class="lang-php"><span class="hljs-keyword">final</span> readonly <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRead</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> $commentCount,
    </span>) </span>{}
}
</code></pre>
<p>We can have another repository to fetch it.</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserReadRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $email</span>): <span class="hljs-title">UserRead</span></span>;
}
</code></pre>
<p>This implementation, assuming a relational SQL database, would not select the password form the table which is not in the read model, solving problem number 1. This read model does not include validations solving problem number 2. And this model has a place for the comments count that can be implemented in the new repository by using a join in a single query, solving problem number 3.</p>
<p>Even more, if we have more representations of a user, we should have a different read model to cover each one. We could have a <code>UserWithLastCommentsRead</code> for example.</p>
<p>And for the update problems? You probably guessed. Individual models for each update.</p>
<pre><code class="lang-php"><span class="hljs-keyword">final</span> readonly <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserDataUpdate</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name,
    </span>) </span>{
        Assert::notEmpty($name);
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-keyword">final</span> readonly <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserPasswordUpdate</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $email,
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $password,
    </span>) </span>{
        Assert::password($password, strength: <span class="hljs-number">3</span>);
    }
}
</code></pre>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">save</span>(<span class="hljs-params">User $user</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateData</span>(<span class="hljs-params">UserDataUpdate $userDataUpdate</span>): <span class="hljs-title">void</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updatePassword</span>(<span class="hljs-params">UserPasswordUpdate $userPasswordUpdate</span>): <span class="hljs-title">void</span></span>;
}
</code></pre>
<p>Now there are no mistakes or unnecessary data. Each update is isolated and it is much more protected from bugs.</p>
<p>Note that in the update models I didn’t add the email validation. That is intentional because it is going to be used to find the user, and if we have an evolved validation, as commented before, we would not be able to find older users with emails that are not valid anymore, but still in the database anyways.</p>
<h2 id="heading-last-words"><strong>Last words</strong></h2>
<p>This is really not that different as we model objects in the real world. We never consider everything about a real life object in a particular context. For example a car.</p>
<p>If a car is modeled by a driver, we can expect the positioning of the seat and the rear mirrors to be really important, while at the same time it is irrelevant for a mechanic doing some maintenance. The mechanic will probably be more concerned about metrics on the engine that are not important to the driver. And a kid at the school learning about transport methods will probably just care about it being a land transport with 4 wheels.</p>
<p>If we use different models for the same real life objects we can definitely do the same for our code models.</p>
]]></content:encoded></item><item><title><![CDATA[Building a PHP CRUD Application with OOP and MySQL: A Best Practice Guide]]></title><description><![CDATA[When developing PHP applications, managing database operations effectively is crucial. One of the most common operations you’ll perform is CRUD (Create, Read, Update, Delete). Adopting Object-Oriented Programming (OOP) principles helps make your code...]]></description><link>https://blog.gulzaib.dev/building-a-php-crud-application-with-oop-and-mysql-a-best-practice-guide</link><guid isPermaLink="true">https://blog.gulzaib.dev/building-a-php-crud-application-with-oop-and-mysql-a-best-practice-guide</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Fri, 10 Jan 2025 15:58:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756795014/6abf7dc3-6f78-4fa6-8eb3-0bcebfff83b4.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When developing PHP applications, managing database operations effectively is crucial. One of the most common operations you’ll perform is CRUD (Create, Read, Update, Delete). Adopting Object-Oriented Programming (OOP) principles helps make your code cleaner, reusable, and scalable. Using MySQL with PHP also ensures that your application can handle data storage efficiently.</p>
<p>In this blog, we’ll go through building a <strong>PHP CRUD application</strong> with <strong>OOP</strong> and <strong>MySQL</strong>. We’ll organize the code using best practices and design patterns that are beginner-friendly yet robust enough for larger projects.</p>
<p>By the end of this guide, you will have a solid foundation for working with databases using OOP principles in PHP.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#the-importance-of-oop-in-php">The Importance of OOP in PHP</a></li>
<li><a class="post-section-overview" href="#setting-up-the-project">Setting Up the Project</a></li>
<li><a class="post-section-overview" href="#creating-the-database">Creating the Database</a></li>
<li><a class="post-section-overview" href="#folder-structure">Folder Structure</a></li>
<li><a class="post-section-overview" href="#connecting-to-the-database">Connecting to the Database</a></li>
<li><a class="post-section-overview" href="#creating-crud-operations">Creating CRUD Operations</a><ul>
<li><a class="post-section-overview" href="#create">Create</a></li>
<li><a class="post-section-overview" href="#read">Read</a></li>
<li><a class="post-section-overview" href="#update">Update</a></li>
<li><a class="post-section-overview" href="#delete">Delete</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#final-thoughts">Final Thoughts</a></li>
</ol>
<h3 id="heading-1-the-importance-of-oop-in-php">1. The Importance of OOP in PHP</h3>
<p><strong>Object-Oriented Programming (OOP)</strong> is a programming paradigm that uses "objects" to organize code. In PHP, OOP allows you to create classes that represent real-world entities, making your code more modular, reusable, and easier to manage.</p>
<p>When working with databases, applying OOP principles means:</p>
<ul>
<li><strong>Separation of Concerns</strong>: Database logic is encapsulated in a class, separate from the rest of your application logic.</li>
<li><strong>Reusability</strong>: You can reuse the database class in multiple parts of the application.</li>
<li><strong>Maintainability</strong>: Your code is easier to update and extend as your application grows.</li>
</ul>
<h3 id="heading-2-setting-up-the-project">2. Setting Up the Project</h3>
<p>Before diving into coding, let’s set up a folder structure that’s easy to maintain. Here’s how your project should be organized:</p>
<pre><code>php-crud/
├── config/
│   └── Database.php
├── controllers/
│   └── UserController.php
├── models/
│   └── User.php
├── views/
│   └── user_list.php
├── public/
│   └── index.php
└── .gitignore
</code></pre><ul>
<li><strong>config/Database.php</strong>: Contains the database connection logic.</li>
<li><strong>controllers/UserController.php</strong>: Handles CRUD operations and communicates with the model.</li>
<li><strong>models/User.php</strong>: Contains the logic to interact with the <code>users</code> table in MySQL.</li>
<li><strong>views/user_list.php</strong>: Displays user data in a table.</li>
<li><strong>public/index.php</strong>: The entry point for the application.</li>
</ul>
<h3 id="heading-3-creating-the-database">3. Creating the Database</h3>
<p>Let’s start by creating the database and a <code>users</code> table in MySQL. You can execute the following SQL queries to set up the database:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> php_crud;

<span class="hljs-keyword">USE</span> php_crud;

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-keyword">users</span> (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    email <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>
);
</code></pre>
<p>This table will store basic user information such as <code>name</code>, <code>email</code>, and <code>created_at</code>.</p>
<h3 id="heading-4-folder-structure">4. Folder Structure</h3>
<p>We’ve already set up the basic folder structure. Here’s a breakdown of each folder’s purpose:</p>
<ul>
<li><strong>config/</strong>: Contains the database configuration and connection logic.</li>
<li><strong>controllers/</strong>: Handles requests and calls the appropriate methods from the model.</li>
<li><strong>models/</strong>: Represents the business logic and database interactions.</li>
<li><strong>views/</strong>: Displays the data to the user.</li>
<li><strong>public/</strong>: The public folder contains the <code>index.php</code> file, which will be the entry point for the application.</li>
</ul>
<h3 id="heading-5-connecting-to-the-database">5. Connecting to the Database</h3>
<p>Let’s start by creating a database connection class in <code>config/Database.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Config</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">PDO</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Database</span>
</span>{
    <span class="hljs-keyword">private</span> $host = <span class="hljs-string">'127.0.0.1'</span>;
    <span class="hljs-keyword">private</span> $dbName = <span class="hljs-string">'php_crud'</span>;
    <span class="hljs-keyword">private</span> $username = <span class="hljs-string">'root'</span>;
    <span class="hljs-keyword">private</span> $password = <span class="hljs-string">''</span>;
    <span class="hljs-keyword">private</span> $connection;

    <span class="hljs-keyword">public</span> <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-keyword">try</span> {
            <span class="hljs-keyword">$this</span>-&gt;connection = <span class="hljs-keyword">new</span> PDO(
                <span class="hljs-string">"mysql:host=<span class="hljs-subst">{$this-&gt;host}</span>;dbname=<span class="hljs-subst">{$this-&gt;dbName}</span>"</span>,
                <span class="hljs-keyword">$this</span>-&gt;username,
                <span class="hljs-keyword">$this</span>-&gt;password
            );
            <span class="hljs-keyword">$this</span>-&gt;connection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;connection;
        } <span class="hljs-keyword">catch</span> (PDOException $e) {
            <span class="hljs-keyword">die</span>(<span class="hljs-string">"Database connection failed: "</span> . $e-&gt;getMessage());
        }
    }
}
</code></pre>
<p>This class creates a PDO connection to MySQL and is reusable across your project.</p>
<h3 id="heading-6-creating-crud-operations">6. Creating CRUD Operations</h3>
<p>Let’s create a model for handling user data. This class will interact with the <code>users</code> table and perform CRUD operations.</p>
<h4 id="heading-create-model-userphp"><strong>Create Model (User.php)</strong></h4>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Models</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Config</span>\<span class="hljs-title">Database</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-keyword">private</span> $conn;

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

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">create</span>(<span class="hljs-params">$name, $email</span>)
    </span>{
        $sql = <span class="hljs-string">"INSERT INTO users (name, email) VALUES (:name, :email)"</span>;
        $stmt = <span class="hljs-keyword">$this</span>-&gt;conn-&gt;prepare($sql);
        $stmt-&gt;bindParam(<span class="hljs-string">':name'</span>, $name);
        $stmt-&gt;bindParam(<span class="hljs-string">':email'</span>, $email);
        <span class="hljs-keyword">return</span> $stmt-&gt;execute();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">read</span>(<span class="hljs-params"></span>)
    </span>{
        $sql = <span class="hljs-string">"SELECT * FROM users"</span>;
        $stmt = <span class="hljs-keyword">$this</span>-&gt;conn-&gt;prepare($sql);
        $stmt-&gt;execute();
        <span class="hljs-keyword">return</span> $stmt-&gt;fetchAll(\PDO::FETCH_ASSOC);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">update</span>(<span class="hljs-params">$id, $name, $email</span>)
    </span>{
        $sql = <span class="hljs-string">"UPDATE users SET name = :name, email = :email WHERE id = :id"</span>;
        $stmt = <span class="hljs-keyword">$this</span>-&gt;conn-&gt;prepare($sql);
        $stmt-&gt;bindParam(<span class="hljs-string">':name'</span>, $name);
        $stmt-&gt;bindParam(<span class="hljs-string">':email'</span>, $email);
        $stmt-&gt;bindParam(<span class="hljs-string">':id'</span>, $id);
        <span class="hljs-keyword">return</span> $stmt-&gt;execute();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delete</span>(<span class="hljs-params">$id</span>)
    </span>{
        $sql = <span class="hljs-string">"DELETE FROM users WHERE id = :id"</span>;
        $stmt = <span class="hljs-keyword">$this</span>-&gt;conn-&gt;prepare($sql);
        $stmt-&gt;bindParam(<span class="hljs-string">':id'</span>, $id);
        <span class="hljs-keyword">return</span> $stmt-&gt;execute();
    }
}
</code></pre>
<h4 id="heading-create-controller-usercontrollerphp"><strong>Create Controller (UserController.php)</strong></h4>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Models</span>\<span class="hljs-title">User</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params">$name, $email</span>)
    </span>{
        $user = <span class="hljs-keyword">new</span> User();
        <span class="hljs-keyword">return</span> $user-&gt;create($name, $email);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUsers</span>(<span class="hljs-params"></span>)
    </span>{
        $user = <span class="hljs-keyword">new</span> User();
        <span class="hljs-keyword">return</span> $user-&gt;read();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateUser</span>(<span class="hljs-params">$id, $name, $email</span>)
    </span>{
        $user = <span class="hljs-keyword">new</span> User();
        <span class="hljs-keyword">return</span> $user-&gt;update($id, $name, $email);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deleteUser</span>(<span class="hljs-params">$id</span>)
    </span>{
        $user = <span class="hljs-keyword">new</span> User();
        <span class="hljs-keyword">return</span> $user-&gt;delete($id);
    }
}
</code></pre>
<h4 id="heading-create-view-userlistphp"><strong>Create View (user_list.php)</strong></h4>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-comment">// This file is responsible for displaying the list of users.</span>

<span class="hljs-keyword">require_once</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../controllers/UserController.php'</span>;

$userController = <span class="hljs-keyword">new</span> \Controllers\UserController();
$users = $userController-&gt;getUsers();

<span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;h1&gt;User List&lt;/h1&gt;"</span>;
<span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;table&gt;&lt;tr&gt;&lt;th&gt;ID&lt;/th&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Email&lt;/th&gt;&lt;th&gt;Actions&lt;/th&gt;&lt;/tr&gt;"</span>;
<span class="hljs-keyword">foreach</span> ($users <span class="hljs-keyword">as</span> $user) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;tr&gt;&lt;td&gt;<span class="hljs-subst">{$user['id']}</span>&lt;/td&gt;&lt;td&gt;<span class="hljs-subst">{$user['name']}</span>&lt;/td&gt;&lt;td&gt;<span class="hljs-subst">{$user['email']}</span>&lt;/td&gt;&lt;td&gt;&lt;a href='update.php?id=<span class="hljs-subst">{$user['id']}</span>'&gt;Edit&lt;/a&gt; | &lt;a href='delete.php?id=<span class="hljs-subst">{$user['id']}</span>'&gt;Delete&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;"</span>;
}
<span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;/table&gt;"</span>;
<span class="hljs-meta">?&gt;</span>
</code></pre>
<h4 id="heading-create-the-entry-point-indexphp"><strong>Create the Entry Point (index.php)</strong></h4>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">require_once</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../models/User.php'</span>;
<span class="hljs-keyword">require_once</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../controllers/UserController.php'</span>;

$userController = <span class="hljs-keyword">new</span> \Controllers\UserController();

<span class="hljs-comment">// Example: Create a user</span>
$userController-&gt;createUser(<span class="hljs-string">'John Doe'</span>, <span class="hljs-string">'john@example.com'</span>);

<span class="hljs-comment">// Example: Read users</span>
$userController-&gt;getUsers();
</code></pre>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>By following OOP principles and applying best practices in PHP, we’ve built a simple and scalable CRUD application. This approach makes it easy to expand your project with new features or improve database interactions.</p>
<p>In this guide, we’ve covered:</p>
<ul>
<li>A simple and maintainable folder structure.</li>
<li>A reusable <code>Database</code> class for MySQL connections.</li>
<li>A <code>User</code> model that encapsulates all CRUD operations.</li>
<li>A <code>UserController</code> to handle business logic.</li>
</ul>
<p>This structure makes your PHP applications cleaner, more modular, and easier to extend. You can now take this approach and build larger, more complex applications using OOP and MySQL.</p>
<p>Happy coding! 🎉</p>
]]></content:encoded></item><item><title><![CDATA[Unit Testing in Laravel: A Practical Approach for Developers]]></title><description><![CDATA[Testing is a critical part of software development, but it often feels like a chore. Fortunately, Laravel makes testing a breeze with its built-in tools, helping developers ensure their applications work as expected without spending endless hours deb...]]></description><link>https://blog.gulzaib.dev/unit-testing-in-laravel-a-practical-approach-for-developers</link><guid isPermaLink="true">https://blog.gulzaib.dev/unit-testing-in-laravel-a-practical-approach-for-developers</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Wed, 20 Nov 2024 19:08:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756799161/08e33c02-d5fd-4a98-b93a-e750b4d99972.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Testing is a critical part of software development, but it often feels like a chore. Fortunately, Laravel makes testing a breeze with its built-in tools, helping developers ensure their applications work as expected without spending endless hours debugging. Whether you’re building a small project or a large-scale application, unit testing can save you from potential headaches by catching issues early.</p>
<p>In this blog, we’ll explore <strong>unit testing in Laravel</strong>—what it is, why it’s important, and how to get started with writing tests. By the end, you’ll understand how to create and execute tests in Laravel with real-world examples.</p>
<hr />
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#what-is-unit-testing">What is Unit Testing?</a></li>
<li><a class="post-section-overview" href="#why-unit-testing-is-important">Why Unit Testing is Important</a></li>
<li><a class="post-section-overview" href="#setting-up-unit-testing-in-laravel">Setting Up Unit Testing in Laravel</a></li>
<li><a class="post-section-overview" href="#writing-your-first-unit-test">Writing Your First Unit Test</a></li>
<li><a class="post-section-overview" href="#testing-models-controllers-and-services">Testing Models, Controllers, and Services</a></li>
<li><a class="post-section-overview" href="#running-and-interpreting-tests">Running and Interpreting Tests</a></li>
<li><a class="post-section-overview" href="#best-practices-for-laravel-unit-testing">Best Practices for Laravel Unit Testing</a></li>
<li><a class="post-section-overview" href="#final-thoughts">Final Thoughts</a></li>
</ol>
<hr />
<h3 id="heading-what-is-unit-testing">What is Unit Testing?</h3>
<p><strong>Unit testing</strong> is a type of testing where you write code to test individual units of your application, like functions, methods, or classes. These tests are small, fast, and focus on ensuring a specific piece of code works as expected. </p>
<p>In Laravel, unit tests are typically written using <strong>PHPUnit</strong>, which comes pre-installed with Laravel.</p>
<hr />
<h3 id="heading-why-unit-testing-is-important">Why Unit Testing is Important</h3>
<p>Unit testing might feel like extra work at first, but the benefits far outweigh the initial effort. Here’s why it’s worth your time:</p>
<ul>
<li><strong>Catch Bugs Early</strong>: Tests help identify bugs before your application goes live, saving you from costly fixes later.</li>
<li><strong>Refactor with Confidence</strong>: Knowing your tests will catch any issues makes refactoring safer and more efficient.</li>
<li><strong>Improve Code Quality</strong>: Writing tests forces you to think through your code’s logic and edge cases, leading to cleaner, more robust code.</li>
<li><strong>Ensure Consistency</strong>: Tests ensure that updates or new features don’t break existing functionality.</li>
</ul>
<hr />
<h3 id="heading-setting-up-unit-testing-in-laravel">Setting Up Unit Testing in Laravel</h3>
<p>Laravel is pre-configured for unit testing, so you don’t need to install any additional tools. Here’s how to get started:</p>
<h4 id="heading-step-1-check-phpunit-installation">Step 1: Check PHPUnit Installation</h4>
<p>Laravel includes PHPUnit out of the box. You can check the version by running:</p>
<pre><code class="lang-bash">vendor/bin/phpunit --version
</code></pre>
<h4 id="heading-step-2-create-a-test-class">Step 2: Create a Test Class</h4>
<p>Laravel provides a handy Artisan command to generate a new test class:</p>
<pre><code class="lang-bash">php artisan make:<span class="hljs-built_in">test</span> ExampleTest --unit
</code></pre>
<p>This creates a test file in the <code>tests/Unit</code> directory:</p>
<pre><code>tests/
├── Unit/
│   └── ExampleTest.php
</code></pre><h4 id="heading-step-3-configure-the-testing-environment">Step 3: Configure the Testing Environment</h4>
<p>Laravel uses the <code>.env.testing</code> file for testing. Copy your <code>.env</code> file and rename it to <code>.env.testing</code>. Update the database configuration to use a separate testing database, ensuring your tests don’t affect your development database.</p>
<pre><code class="lang-dotenv">DB_CONNECTION=sqlite
DB_DATABASE=:memory:
</code></pre>
<hr />
<h3 id="heading-writing-your-first-unit-test">Writing Your First Unit Test</h3>
<p>Let’s write a simple test to check if a method in a class returns the expected value.</p>
<h4 id="heading-example-testing-a-math-helper-function">Example: Testing a Math Helper Function</h4>
<p>Create a helper class in <code>app/Helpers/MathHelper.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Helpers</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MathHelper</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">$a, $b</span>)
    </span>{
        <span class="hljs-keyword">return</span> $a + $b;
    }
}
</code></pre>
<p>Write a test for this function in <code>tests/Unit/MathHelperTest.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Tests</span>\<span class="hljs-title">Unit</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">PHPUnit</span>\<span class="hljs-title">Framework</span>\<span class="hljs-title">TestCase</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Helpers</span>\<span class="hljs-title">MathHelper</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MathHelperTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TestCase</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testAddition</span>(<span class="hljs-params"></span>)
    </span>{
        $result = MathHelper::add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
        <span class="hljs-keyword">$this</span>-&gt;assertEquals(<span class="hljs-number">5</span>, $result);
    }
}
</code></pre>
<p>Run the test:</p>
<pre><code class="lang-bash">vendor/bin/phpunit
</code></pre>
<p>If everything is correct, PHPUnit will output:</p>
<pre><code>OK (<span class="hljs-number">1</span> test, <span class="hljs-number">1</span> assertion)
</code></pre><hr />
<h3 id="heading-testing-models-controllers-and-services">Testing Models, Controllers, and Services</h3>
<h4 id="heading-testing-models">Testing Models</h4>
<p>Models are central to any Laravel application. Let’s test a simple model method.</p>
<p>Add a <code>User</code> model with a custom method in <code>app/Models/User.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Eloquent</span>\<span class="hljs-title">Factories</span>\<span class="hljs-title">HasFactory</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Database</span>\<span class="hljs-title">Eloquent</span>\<span class="hljs-title">Model</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Model</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">HasFactory</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isAdmin</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;role === <span class="hljs-string">'admin'</span>;
    }
}
</code></pre>
<p>Write a test in <code>tests/Unit/UserTest.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Tests</span>\<span class="hljs-title">Unit</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">PHPUnit</span>\<span class="hljs-title">Framework</span>\<span class="hljs-title">TestCase</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">User</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TestCase</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testIsAdmin</span>(<span class="hljs-params"></span>)
    </span>{
        $user = <span class="hljs-keyword">new</span> User();
        $user-&gt;role = <span class="hljs-string">'admin'</span>;

        <span class="hljs-keyword">$this</span>-&gt;assertTrue($user-&gt;isAdmin());
    }
}
</code></pre>
<h4 id="heading-testing-controllers">Testing Controllers</h4>
<p>For controllers, you’ll typically use <strong>feature tests</strong>, but you can still test individual methods.</p>
<h4 id="heading-testing-services">Testing Services</h4>
<p>Create a service in <code>app/Services/ExampleService.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Services</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleService</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">$name</span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, <span class="hljs-subst">$name</span>!"</span>;
    }
}
</code></pre>
<p>Write a test for it:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">Tests</span>\<span class="hljs-title">Unit</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">PHPUnit</span>\<span class="hljs-title">Framework</span>\<span class="hljs-title">TestCase</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">ExampleService</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleServiceTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TestCase</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testGreeting</span>(<span class="hljs-params"></span>)
    </span>{
        $service = <span class="hljs-keyword">new</span> ExampleService();
        <span class="hljs-keyword">$this</span>-&gt;assertEquals(<span class="hljs-string">'Hello, John!'</span>, $service-&gt;greet(<span class="hljs-string">'John'</span>));
    }
}
</code></pre>
<hr />
<h3 id="heading-running-and-interpreting-tests">Running and Interpreting Tests</h3>
<p>To run all tests in your project:</p>
<pre><code class="lang-bash">vendor/bin/phpunit
</code></pre>
<p>To run a specific test file:</p>
<pre><code class="lang-bash">vendor/bin/phpunit tests/Unit/ExampleTest.php
</code></pre>
<p>The output will show:</p>
<ul>
<li>Tests that passed.</li>
<li>Tests that failed (with details on what went wrong).</li>
</ul>
<hr />
<h3 id="heading-best-practices-for-laravel-unit-testing">Best Practices for Laravel Unit Testing</h3>
<ol>
<li><strong>Test Small Units</strong>: Focus on small, isolated units of code, like a single method or function.</li>
<li><strong>Use Assertions Wisely</strong>: Laravel provides many assertion methods, such as <code>assertEquals</code>, <code>assertTrue</code>, and <code>assertCount</code>. Use them to verify expected outcomes.</li>
<li><strong>Mock External Dependencies</strong>: Use Laravel’s mocking capabilities to simulate database queries or API calls, ensuring tests are independent of external factors.</li>
<li><strong>Run Tests Regularly</strong>: Integrate testing into your development workflow to catch issues early.</li>
</ol>
<hr />
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Unit testing in Laravel doesn’t have to be intimidating. With its built-in tools and seamless integration with PHPUnit, Laravel makes it easy to write and manage tests. By adopting a testing-first mindset, you’ll ensure your application is robust, reliable, and ready for production.</p>
<p>Start small—write a test for a single function or class. As you get comfortable, you’ll see how unit testing can transform your development process. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Machine Learning in PHP: Build a News Classifier Using Rubix ML]]></title><description><![CDATA[Introduction
Machine learning is everywhere—recommending movies, tagging images, and now even classifying news articles. Imagine if you could do that within PHP! With Rubix ML, you can bring the power of machine learning to PHP in a way that’s straig...]]></description><link>https://blog.gulzaib.dev/machine-learning-in-php-build-a-news-classifier-using-rubix-ml</link><guid isPermaLink="true">https://blog.gulzaib.dev/machine-learning-in-php-build-a-news-classifier-using-rubix-ml</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Fri, 01 Nov 2024 16:51:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756803975/46f833e4-1649-4a63-b1c7-bbe8a1b98131.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>Machine learning is everywhere—recommending movies, tagging images, and now even classifying news articles. Imagine if you could do that within PHP! With <a target="_blank" href="https://rubixml.com"><strong>Rubix ML</strong></a>, you can bring the power of machine learning to PHP in a way that’s straightforward and accessible. This guide will walk you through building a simple <strong>news classifier</strong> that sorts articles into categories like “Sports” or “Technology.” By the end, you’ll have a working classifier that can predict categories for new articles based on their content.</p>
<p>This project is perfect for beginners who want to dip their toes into machine learning using PHP, and you can follow along with the complete code on <a target="_blank" href="https://github.com/arafat-web/NewsClassifier">GitHub</a>.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#what-is-rubix-ml">What is Rubix ML?</a></li>
<li><a class="post-section-overview" href="#setting-up-the-project">Setting Up the Project</a></li>
<li><a class="post-section-overview" href="#creating-the-news-classification-class">Creating the News Classification Class</a></li>
<li><a class="post-section-overview" href="#training-the-model">Training the Model</a></li>
<li><a class="post-section-overview" href="#predicting-new-samples">Predicting New Samples</a></li>
<li><a class="post-section-overview" href="#final-thoughts">Final Thoughts</a></li>
</ol>
<h3 id="heading-what-is-rubix-ml">What is Rubix ML?</h3>
<p><a target="_blank" href="https://rubixml.com/"><strong>Rubix ML</strong></a> is a machine learning library for PHP that brings ML tools and algorithms into a PHP-friendly environment. Whether you’re working on classification, regression, clustering, or even natural language processing, Rubix ML has you covered. It allows you to load and preprocess data, train models, and evaluate performance—all in PHP.</p>
<p>Rubix ML supports a wide range of machine learning tasks, such as:</p>
<ul>
<li><strong>Classification</strong>: Categorizing data, like labeling emails as spam or not spam.</li>
<li><strong>Regression</strong>: Predicting continuous values, like housing prices.</li>
<li><strong>Clustering</strong>: Grouping data without labels, like finding customer segments.</li>
<li><strong>Natural Language Processing (NLP)</strong>: Working with text data, such as tokenizing and transforming it into usable formats for ML.</li>
</ul>
<p>Let’s dive into how you can use Rubix ML to build a simple news classifier in PHP!</p>
<h3 id="heading-setting-up-the-project">Setting Up the Project</h3>
<p>We’ll start by setting up a new PHP project with Rubix ML and configuring autoloading.</p>
<h4 id="heading-step-1-initialize-the-project-directory">Step 1: Initialize the Project Directory</h4>
<p>Create a new project directory and navigate into it:</p>
<pre><code class="lang-bash">mkdir NewsClassifier
<span class="hljs-built_in">cd</span> NewsClassifier
</code></pre>
<h4 id="heading-step-2-install-rubix-ml-with-composer">Step 2: Install Rubix ML with Composer</h4>
<p>Make sure you have Composer installed, then add Rubix ML to your project by running:</p>
<pre><code class="lang-bash">composer require rubix/ml
</code></pre>
<h4 id="heading-step-3-configure-autoloading-in-composerjson">Step 3: Configure Autoloading in <code>composer.json</code></h4>
<p>To autoload classes from our project’s <code>src</code> directory, open or create a <code>composer.json</code> file and add the following configuration:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"autoload"</span>: {
        <span class="hljs-attr">"psr-4"</span>: {
            <span class="hljs-attr">"NewsClassifier\\"</span>: <span class="hljs-string">"src/"</span>
        }
    },
    <span class="hljs-attr">"require"</span>: {
        <span class="hljs-attr">"rubix/ml"</span>: <span class="hljs-string">"^2.5"</span>
    }
}
</code></pre>
<p>This tells Composer to autoload any classes within the <code>src</code> folder under the <code>NewsClassifier</code> namespace.</p>
<h4 id="heading-step-4-run-composer-autoload-dump">Step 4: Run Composer Autoload Dump</h4>
<p>After adding the autoload configuration, run the following command to regenerate Composer’s autoloader:</p>
<pre><code class="lang-bash">composer dump-autoload
</code></pre>
<h4 id="heading-step-5-directory-structure">Step 5: Directory Structure</h4>
<p>Your project directory should look like this:</p>
<pre><code>NewsClassifier/
├── src/
│   ├── Classification.php
│   └── train.php
├── storage/
├── vendor/
├── composer.json
└── composer.lock
</code></pre><ul>
<li><strong>src/</strong>: Contains your PHP scripts.</li>
<li><strong>storage/</strong>: Where the trained model will be saved.</li>
<li><strong>vendor/</strong>: Contains dependencies installed by Composer.</li>
</ul>
<h3 id="heading-creating-the-news-classification-class">Creating the News Classification Class</h3>
<p>In <code>src/</code>, create a file called <code>Classification.php</code>. This file will contain the methods for training the model and predicting news categories.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">NewsClassifier</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Classifiers</span>\<span class="hljs-title">KNearestNeighbors</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Datasets</span>\<span class="hljs-title">Labeled</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Datasets</span>\<span class="hljs-title">Unlabeled</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">PersistentModel</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Pipeline</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Tokenizers</span>\<span class="hljs-title">Word</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Transformers</span>\<span class="hljs-title">TfIdfTransformer</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Transformers</span>\<span class="hljs-title">WordCountVectorizer</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Rubix</span>\<span class="hljs-title">ML</span>\<span class="hljs-title">Persisters</span>\<span class="hljs-title">Filesystem</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Classification</span>
</span>{
    <span class="hljs-keyword">private</span> $modelPath;

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

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">train</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-comment">// Sample data and corresponding labels</span>
        $samples = [
            [<span class="hljs-string">'The team played an amazing game of soccer'</span>],
            [<span class="hljs-string">'The new programming language has been released'</span>],
            [<span class="hljs-string">'The match between the two teams was incredible'</span>],
            [<span class="hljs-string">'The new tech gadget has been launched'</span>],
        ];

        $labels = [
            <span class="hljs-string">'sports'</span>,
            <span class="hljs-string">'technology'</span>,
            <span class="hljs-string">'sports'</span>,
            <span class="hljs-string">'technology'</span>,
        ];

        <span class="hljs-comment">// Create a labeled dataset</span>
        $dataset = <span class="hljs-keyword">new</span> Labeled($samples, $labels);

        <span class="hljs-comment">// Set up the pipeline with a text transformer and K-Nearest Neighbors classifier</span>
        $estimator = <span class="hljs-keyword">new</span> Pipeline([
            <span class="hljs-keyword">new</span> WordCountVectorizer(<span class="hljs-number">10000</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-keyword">new</span> Word()),
            <span class="hljs-keyword">new</span> TfIdfTransformer(),
        ], <span class="hljs-keyword">new</span> KNearestNeighbors(<span class="hljs-number">4</span>));

        <span class="hljs-comment">// Train the model</span>
        $estimator-&gt;train($dataset);

        <span class="hljs-comment">// Save the model</span>
        <span class="hljs-keyword">$this</span>-&gt;saveModel($estimator);

        <span class="hljs-keyword">echo</span> <span class="hljs-string">"Training completed and model saved.\n"</span>;
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saveModel</span>(<span class="hljs-params">$estimator</span>)
    </span>{
        $persister = <span class="hljs-keyword">new</span> Filesystem(<span class="hljs-keyword">$this</span>-&gt;modelPath);
        $model = <span class="hljs-keyword">new</span> PersistentModel($estimator, $persister);
        $model-&gt;save();
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">predict</span>(<span class="hljs-params"><span class="hljs-keyword">array</span> $samples</span>)
    </span>{
        <span class="hljs-comment">// Load the saved model</span>
        $persister = <span class="hljs-keyword">new</span> Filesystem(<span class="hljs-keyword">$this</span>-&gt;modelPath);
        $model = PersistentModel::load($persister);

        <span class="hljs-comment">// Predict categories for new samples</span>
        $dataset = <span class="hljs-keyword">new</span> Unlabeled($samples);
        <span class="hljs-keyword">return</span> $model-&gt;predict($dataset);
    }
}
</code></pre>
<p>This <code>Classification</code> class contains methods to:</p>
<ul>
<li><strong>Train</strong>: Create and train a pipeline-based model.</li>
<li><strong>Save the Model</strong>: Save the trained model to the specified path.</li>
<li><strong>Predict</strong>: Load the saved model and predict the category for new samples.</li>
</ul>
<h3 id="heading-training-the-model">Training the Model</h3>
<p>Create a script called <code>train.php</code> in <code>src/</code> to train the model.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../vendor/autoload.php'</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">NewsClassifier</span>\<span class="hljs-title">Classification</span>;

<span class="hljs-comment">// Define the model path</span>
$modelPath = <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../storage/model.rbx'</span>;

<span class="hljs-comment">// Initialize the Classification object</span>
$classifier = <span class="hljs-keyword">new</span> Classification($modelPath);

<span class="hljs-comment">// Train the model and save it</span>
$classifier-&gt;train();
</code></pre>
<p>Run this script to train the model:</p>
<pre><code class="lang-bash">php src/train.php
</code></pre>
<p>If successful, you’ll see:</p>
<pre><code>Training completed and model saved.
</code></pre><h3 id="heading-predicting-new-samples">Predicting New Samples</h3>
<p>Create another script, <code>predict.php</code>, in <code>src/</code> to classify new articles based on the trained model.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../vendor/autoload.php'</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">NewsClassifier</span>\<span class="hljs-title">Classification</span>;

<span class="hljs-comment">// Define the path to the saved model</span>
$modelPath = <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../storage/model.rbx'</span>;

<span class="hljs-comment">// Initialize the Classification object</span>
$classifier = <span class="hljs-keyword">new</span> Classification($modelPath);

<span class="hljs-comment">// Define new samples for classification</span>
$samples = [
    [<span class="hljs-string">'The team played an amazing game of soccer, showing excellent teamwork and strategy.'</span>],
    [<span class="hljs-string">'The latest programming language release introduces features that enhance coding efficiency.'</span>],
    [<span class="hljs-string">'An incredible match between two top teams ended in a thrilling draw last night.'</span>],
    [<span class="hljs-string">'This new tech gadget includes features never before seen, setting a new standard in the industry.'</span>],
];

<span class="hljs-comment">// Predict categories</span>
$predictions = $classifier-&gt;predict($samples);

<span class="hljs-comment">// Display predictions</span>
<span class="hljs-keyword">foreach</span> ($predictions <span class="hljs-keyword">as</span> $index =&gt; $prediction) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Sample: "</span> . $samples[$index][<span class="hljs-number">0</span>] . <span class="hljs-string">"\n"</span>;
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Prediction: "</span> . $prediction . <span class="hljs-string">"\n\n"</span>;
}
</code></pre>
<p>Run the prediction script to classify the samples:</p>
<pre><code class="lang-bash">php src/predict.php
</code></pre>
<p>The output should show each sample text with its predicted category.</p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>With this guide, you’ve successfully built a simple news classifier in PHP using Rubix ML! This demonstrates how PHP can be more versatile than you might think, bringing in machine learning capabilities for tasks like text classification, recommendation systems, and more. The full code for this project is available on <a target="_blank" href="https://github.com/arafat-web/NewsClassifier">GitHub</a>.</p>
<p>Experiment with different algorithms or data to expand the classifier. Who knew PHP could do machine learning? Now you do.
Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Understanding PSR-12: The PHP Coding Style Guide]]></title><description><![CDATA[If you’ve been developing with PHP for a while, you've likely encountered the term PSR-12. It’s one of the most widely accepted coding standards in the PHP community and is aimed at ensuring consistency in PHP codebases across different projects. Whe...]]></description><link>https://blog.gulzaib.dev/understanding-psr-12-the-php-coding-style-guide</link><guid isPermaLink="true">https://blog.gulzaib.dev/understanding-psr-12-the-php-coding-style-guide</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Mon, 21 Oct 2024 17:34:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756808938/48bb9492-ef79-4604-b37e-2d416552154c.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you’ve been developing with PHP for a while, you've likely encountered the term <strong>PSR-12</strong>. It’s one of the most widely accepted coding standards in the PHP community and is aimed at ensuring consistency in PHP codebases across different projects. Whether you're working solo or as part of a team, following PSR-12 can make your code cleaner, more readable, and easier to maintain. In this blog, we'll break down what PSR-12 is, why it's important, and how you can apply it in your projects.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#what-is-psr-12">What is PSR-12?</a></li>
<li><a class="post-section-overview" href="#why-is-psr-12-important">Why is PSR-12 Important?</a></li>
<li><a class="post-section-overview" href="#key-rules-of-psr-12">Key Rules of PSR-12</a><ul>
<li><a class="post-section-overview" href="#file-structure">File Structure</a></li>
<li><a class="post-section-overview" href="#namespaces-and-use-declarations">Namespaces and Use Declarations</a></li>
<li><a class="post-section-overview" href="#classes-and-methods">Classes and Methods</a></li>
<li><a class="post-section-overview" href="#control-structures">Control Structures</a></li>
<li><a class="post-section-overview" href="#comments-and-documentation">Comments and Documentation</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#how-to-apply-psr-12-in-your-php-projects">How to Apply PSR-12 in Your PHP Projects</a></li>
<li><a class="post-section-overview" href="#tools-to-help-you-follow-psr-12">Tools to Help You Follow PSR-12</a></li>
<li><a class="post-section-overview" href="#final-thoughts">Final Thoughts</a></li>
</ol>
<h3 id="heading-what-is-psr-12">What is PSR-12?</h3>
<p>PSR-12 is a <strong>coding style guide</strong> for PHP, developed by the PHP-FIG (Framework Interoperability Group). It builds upon the previous PSR-2 standard, providing an updated set of rules that reflect modern PHP practices and improve consistency across codebases.</p>
<p>Think of PSR-12 as the blueprint for writing clean, readable, and maintainable PHP code. By following PSR-12, developers can ensure that their code adheres to a standardized structure, making it easier to collaborate with others and to work on open-source projects.</p>
<h3 id="heading-why-is-psr-12-important">Why is PSR-12 Important?</h3>
<p>Coding standards like PSR-12 aren't just about nitpicking over spaces and tabs. Here’s why they matter:</p>
<ul>
<li><strong>Readability</strong>: Code that follows a standard style is easier to read, especially for developers new to a project.</li>
<li><strong>Collaboration</strong>: If everyone follows the same rules, working together becomes smoother and more efficient.</li>
<li><strong>Maintainability</strong>: Clean, consistent code is easier to debug, test, and extend over time.</li>
<li><strong>Interoperability</strong>: In open-source projects or when integrating third-party libraries, following a common standard ensures compatibility across different codebases.</li>
</ul>
<h3 id="heading-key-rules-of-psr-12">Key Rules of PSR-12</h3>
<p>Let’s dive into some of the key rules that PSR-12 lays out. While there are many smaller guidelines, here are the ones that stand out the most.</p>
<h4 id="heading-1-file-structure">1. File Structure</h4>
<ul>
<li><strong>Opening Tag</strong>: PHP files must use the <code>&lt;?php</code> tag and should not use short tags.</li>
<li><strong>Encoding</strong>: Files must be encoded in UTF-8 without a BOM (Byte Order Mark).</li>
<li><strong>Line Length</strong>: Lines should not be longer than 120 characters, but lines up to 80 characters are preferred.</li>
<li><strong>Blank Lines</strong>: There should be no blank lines after the opening PHP tag or before the closing tag. Additionally, there must be a single blank line before <code>return</code> statements, and between method definitions.</li>
</ul>
<h4 id="heading-2-namespaces-and-use-declarations">2. Namespaces and Use Declarations</h4>
<p>PSR-12 requires that namespaces and use declarations follow a specific order to improve clarity:</p>
<ul>
<li><strong>Namespace Declaration</strong>: The namespace declaration must be the first line after the opening PHP tag. There must be one blank line after the namespace.</li>
<li><strong>Use Declarations</strong>: All use declarations must be grouped together after the namespace declaration and separated by a blank line. Additionally, there must be one blank line after the last use statement.</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Models</span>\<span class="hljs-title">User</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Repositories</span>\<span class="hljs-title">UserRepository</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> </span>{
    <span class="hljs-comment">// Class implementation</span>
}
</code></pre>
<h4 id="heading-3-classes-and-methods">3. Classes and Methods</h4>
<p>PSR-12 enforces some strict rules on how classes, properties, and methods should be declared:</p>
<ul>
<li><strong>Class Declaration</strong>: The <code>class</code> keyword must be followed by a space, then the class name. Open curly braces <code>{</code> must be placed on the same line as the class declaration, with closing braces <code>}</code> on their own line.</li>
<li><strong>Properties</strong>: Visibility (<code>public</code>, <code>protected</code>, <code>private</code>) must be declared for all properties.</li>
<li><strong>Methods</strong>: Similar to class declarations, the <code>function</code> keyword must be followed by a space, then the method name. Visibility must be declared for all methods.</li>
</ul>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> </span>{
    <span class="hljs-keyword">private</span> $userRepository;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">UserRepository $userRepository</span>) </span>{
        <span class="hljs-keyword">$this</span>-&gt;userRepository = $userRepository;
    }
}
</code></pre>
<h4 id="heading-4-control-structures">4. Control Structures</h4>
<p>Control structures like <code>if</code>, <code>for</code>, and <code>switch</code> must follow certain rules:</p>
<ul>
<li><strong>Structure</strong>: There must be one space between the control keyword and the opening parenthesis. Curly braces <code>{}</code> must always be used, even for single-line statements.</li>
<li><strong>Indentation</strong>: All blocks inside control structures must be indented by one level (typically four spaces).</li>
</ul>
<pre><code class="lang-php"><span class="hljs-keyword">if</span> ($user-&gt;isAdmin()) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"User is an admin"</span>;
} <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"User is not an admin"</span>;
}
</code></pre>
<h4 id="heading-5-comments-and-documentation">5. Comments and Documentation</h4>
<p>Comments are crucial for explaining why certain parts of the code exist. PSR-12 emphasizes the need for proper, clear comments.</p>
<ul>
<li><strong>Block Comments</strong>: Use <code>/* */</code> for multi-line comments, and place a blank line before the comment.</li>
<li><strong>Single-line Comments</strong>: Use <code>//</code> for inline comments, and ensure that comments are meaningful.</li>
</ul>
<pre><code class="lang-php"><span class="hljs-comment">// Fetch user from the repository</span>
$user = $userRepository-&gt;find($id);

<span class="hljs-comment">/*
 * If user is not found, throw an exception.
 * This helps in handling invalid user IDs.
 */</span>
<span class="hljs-keyword">if</span> (!$user) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundException();
}
</code></pre>
<h3 id="heading-how-to-apply-psr-12-in-your-php-projects">How to Apply PSR-12 in Your PHP Projects</h3>
<p>To follow PSR-12 in your projects, you can manually adhere to the guidelines when writing code, but the best way to ensure compliance is by using automated tools.</p>
<p>First, get familiar with these general practices:</p>
<ul>
<li><strong>Use consistent indentation</strong>: Four spaces are required for indentation.</li>
<li><strong>Limit line length</strong>: Try to keep your lines under 120 characters, although 80 characters are preferred for better readability.</li>
<li><strong>Organize code structure</strong>: Follow the rules for class declarations, visibility, and control structures.</li>
</ul>
<h3 id="heading-tools-to-help-you-follow-psr-12">Tools to Help You Follow PSR-12</h3>
<p>Manually ensuring that your code follows PSR-12 can be time-consuming, but there are tools that can help you automate this process.</p>
<h4 id="heading-1-phpcodesniffer">1. <strong>PHP_CodeSniffer</strong></h4>
<p>One of the most popular tools for ensuring your PHP code follows PSR-12 is PHP_CodeSniffer. It analyzes your code and points out where you're deviating from the standard.</p>
<p>To install and use it:</p>
<pre><code class="lang-bash">composer require <span class="hljs-string">"squizlabs/php_codesniffer=*"</span>
</code></pre>
<p>Then, run it against your code:</p>
<pre><code class="lang-bash">./vendor/bin/phpcs --standard=PSR12 src/
</code></pre>
<h4 id="heading-2-php-cs-fixer">2. <strong>PHP CS Fixer</strong></h4>
<p>Another useful tool is PHP CS Fixer. It not only detects issues but can also fix your code to comply with PSR-12 automatically.</p>
<pre><code class="lang-bash">composer require friendsofphp/php-cs-fixer
</code></pre>
<p>Run the fixer with:</p>
<pre><code class="lang-bash">./vendor/bin/php-cs-fixer fix src/
</code></pre>
<h4 id="heading-3-phpstorm">3. <strong>PHPStorm</strong></h4>
<p>If you use PHPStorm, you can configure it to follow PSR-12. Go to <strong>Settings</strong> -&gt; <strong>Editor</strong> -&gt; <strong>Code Style</strong> -&gt; <strong>PHP</strong> and set the standard to PSR-12.</p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Following PSR-12 in your PHP projects is about more than just adhering to arbitrary rules. It’s about making your code cleaner, more readable, and easier to maintain—whether you're working alone or with a team. By following PSR-12, you're not just writing code for yourself but for the entire PHP community.</p>
<p>Adopting this standard is a step towards writing professional, consistent, and maintainable PHP code. Use the tools mentioned to make the process easier, and watch how clean and organized your projects become!</p>
<p>Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Highlights from Laracon US 2024 Keynote]]></title><description><![CDATA[Key Announcements from Laracon US 2024 Keynote
The Laracon US 2024 keynote delivered by Taylor Otwell brought thrilling updates to the Laravel community. Here are the major highlights:
1. Laravel VS Code Extension
One of the most exciting announcemen...]]></description><link>https://blog.gulzaib.dev/highlights-from-laracon-us-2024-keynote</link><guid isPermaLink="true">https://blog.gulzaib.dev/highlights-from-laracon-us-2024-keynote</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Mon, 02 Sep 2024 04:08:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756820384/fc535fbf-253c-485f-bd4c-1b913fd5c8fd.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-key-announcements-from-laracon-us-2024-keynote">Key Announcements from Laracon US 2024 Keynote</h2>
<p>The Laracon US 2024 keynote delivered by Taylor Otwell brought thrilling updates to the Laravel community. Here are the major highlights:</p>
<h3 id="heading-1-laravel-vs-code-extension">1. <strong>Laravel VS Code Extension</strong></h3>
<p>One of the most exciting announcements was the introduction of a <strong>dedicated Laravel extension for Visual Studio Code</strong>. This tool provides built-in features like enhanced <strong>autocomplete</strong>, inline <strong>diagnostics</strong>, and <strong>intelligent suggestions</strong> to speed up development and improve coding accuracy.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756812539/fe6cddf9-a28a-4552-b20c-a6da44e2cc24.png" alt="Laravel VS Code Extension" /></p>
<h3 id="heading-2-concurrency-facade-amp-defer-helper">2. <strong>Concurrency Facade &amp; defer() Helper</strong></h3>
<p>A powerful new <strong>Concurrency Facade</strong> was introduced, allowing developers to handle parallel task execution more efficiently. Alongside this, the new <code>defer()</code> helper will help offload time-consuming tasks to the background, making the app more responsive without complicated setups.</p>
<h4 id="heading-new-defer-helper">New Defer Helper</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756814037/689a3a31-bc2c-4528-97ce-8fc620f74adb.png" alt="Differ" /></p>
<h4 id="heading-new-concurrency-facade">New Concurrency Facade</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756815570/8c497b41-c5f8-4d2b-92cb-79ede7854ba9.png" alt="Concurrency" /></p>
<h3 id="heading-3-inertia-v20">3. <strong>Inertia v2.0</strong></h3>
<p>Otwell also announced <strong>Inertia v2.0</strong>, bringing new features like <strong>asynchronous requests</strong> and <strong>prefetching</strong>, resulting in faster and more dynamic applications. This version helps developers build modern single-page applications (SPAs) without compromising speed and performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756816995/f9ed12a5-e1bd-463c-8973-b80fa0e2b58c.png" alt="Inertia" /></p>
<h3 id="heading-4-laravel-cloud">4. <strong>Laravel Cloud</strong></h3>
<p>Perhaps the most groundbreaking announcement was <strong>Laravel Cloud</strong>, a new platform designed to make app deployment effortless. This platform allows developers to deploy their Laravel applications with minimal configuration while offering built-in scalability and performance optimizations. Laravel Cloud promises to make the deployment process as simple as pushing code to a Git repository.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756818383/77669160-df1d-4649-8ff6-79d50092b7e5.png" alt="Laravel Cloud" /></p>
<h3 id="heading-5-laravel-echo-amp-websockets-updates">5. <strong>Laravel Echo &amp; WebSockets Updates</strong></h3>
<p>The updates also included improvements to <strong>Laravel Echo</strong>, enhancing real-time communication in applications. This brings better integration with WebSockets and makes it easier to develop applications with real-time features like notifications and live updates.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Laracon US 2024 highlighted Laravel’s continuing evolution, focusing on boosting developer productivity and improving application performance. The new <strong>VS Code extension</strong>, <strong>Concurrency tools</strong>, and <strong>Inertia v2.0</strong> offer solutions for common development challenges, while <strong>Laravel Cloud</strong> provides a robust, easy-to-use deployment platform. These updates ensure that Laravel continues to empower developers to build faster, more scalable applications with less complexity.</p>
<p>For a detailed look at the announcements, visit the <a target="_blank" href="https://laravel-news.com/laracon-us-keynote-2024">full article</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Project Management with Task Manager: An Open-Source Laravel Application]]></title><description><![CDATA[Task Manager
In today's fast-paced development world, managing projects and tasks efficiently is crucial for every developer. I'm excited to introduce Task Manager, an open-source project management tool built with Laravel. This tool is inspired by t...]]></description><link>https://blog.gulzaib.dev/project-management-with-task-manager-an-open-source-laravel-application</link><guid isPermaLink="true">https://blog.gulzaib.dev/project-management-with-task-manager-an-open-source-laravel-application</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Thu, 04 Jul 2024 11:01:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756829663/11f930c5-1513-48b6-88d5-2df1eaf5f132.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-task-manager">Task Manager</h3>
<p>In today's fast-paced development world, managing projects and tasks efficiently is crucial for every developer. I'm excited to introduce <strong>Task Manager</strong>, an open-source project management tool built with Laravel. This tool is inspired by the functionalities of popular platforms like ClickUp and Trello, offering a flexible and user-friendly interface to streamline your project management tasks.</p>
<h3 id="heading-key-features">Key Features</h3>
<p>Task Manager is designed to enhance your productivity with several key features:</p>
<ul>
<li><strong>Project Organization</strong>: Easily create and manage multiple projects, and maintain your projects.</li>
<li><strong>Task Management</strong>: Add, edit, delete, and move tasks across different statuses with drag-and-drop functionality.</li>
<li><strong>Notes and Files</strong>: Attach detailed notes and files to your tasks or projects, ensuring you have all the necessary information at your fingertips.</li>
<li><strong>Reminders and Routines</strong>: Set reminders for deadlines and define routine tasks that recur at specified intervals.</li>
</ul>
<h3 id="heading-getting-started-with-task-manager">Getting Started with Task Manager</h3>
<p>Getting started with Task Manager is straightforward. Here’s a quick setup guide:</p>
<ol>
<li><p><strong>Clone the Repository</strong>:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/arafat-web/Task-Manager.git
<span class="hljs-built_in">cd</span> Task-Manager
</code></pre>
</li>
<li><p><strong>Install Dependencies</strong>:</p>
<pre><code class="lang-bash">composer install
</code></pre>
</li>
<li><p><strong>Environment Setup</strong>:
Duplicate <code>.env.example</code> to <code>.env</code> and fill in your database and mail settings.</p>
</li>
<li><p><strong>Generate Application Key</strong>:</p>
<pre><code class="lang-bash">php artisan key:generate
</code></pre>
</li>
<li><p><strong>Database Migrations</strong>:</p>
<pre><code class="lang-bash">php artisan migrate --seed
</code></pre>
</li>
<li><p><strong>Serve the Application</strong>:</p>
<pre><code class="lang-bash">php artisan serve
</code></pre>
<p>Access the application at http://localhost:8000.</p>
</li>
</ol>
<h4 id="heading-credentials">Credentials</h4>
<p>Email: <code>admin@example.com</code>
Password: <code>secret</code></p>
<h3 id="heading-demo-and-screenshots">Demo and Screenshots</h3>
<p>Explore how Task Manager looks and functions through these screenshots and imagine how it can transform your project management experience.</p>
<h4 id="heading-dashboard">Dashboard</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756825416/7f4b336f-38a0-42bb-863f-ae9a436ae994.png" alt="Dashboard" /></p>
<h4 id="heading-projects">Projects</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756826762/d72170bc-2434-498f-aead-81a10f7e87c5.png" alt="Projects" /></p>
<h4 id="heading-tasks">Tasks</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756827921/24554d9f-149e-45c2-8339-ecfe09cf6f20.png" alt="Tasks" /></p>
<h3 id="heading-how-to-contribute">How to Contribute</h3>
<p>Contributions are welcome! If you have improvements or bug fixes, please feel free to fork the repository, make changes, and submit a pull request. For any issues, queries, or suggestions, open an issue on GitHub.</p>
<h3 id="heading-stay-connected">Stay Connected</h3>
<p>For more insights and updates, follow me on [LinkedIn] (https://www.linkedin.com/in/arafat-hossain-ar-a174b51a6/), <a target="_blank" href="https://www.github.com/arafat-web">Github</a>, <a target="_blank" href="https://www.facebook.com/arafathossain000">Facebook</a>, and my <a target="_blank" href="https://arafatdev.com">website</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Top 3 PHP Frameworks: Speed, Response Time, and Efficiency Compared]]></title><description><![CDATA[In the bustling world of web development, PHP frameworks play a crucial role in shaping robust, efficient, and scalable web applications. Whether you're a seasoned developer or a newcomer, picking the right framework can significantly impact your pro...]]></description><link>https://blog.gulzaib.dev/top-3-php-frameworks-speed-response-time-and-efficiency-compared</link><guid isPermaLink="true">https://blog.gulzaib.dev/top-3-php-frameworks-speed-response-time-and-efficiency-compared</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Mon, 01 Jul 2024 17:33:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756835150/18eec908-7c27-438a-b7da-342a3cbcdfa1.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the bustling world of web development, PHP frameworks play a crucial role in shaping robust, efficient, and scalable web applications. Whether you're a seasoned developer or a newcomer, picking the right framework can significantly impact your project's success. Today, we're diving into the top 3 PHP frameworks: Laravel, Symfony, and CodeIgniter. We'll explore why these frameworks stand out, examine their execution speeds, response times, and more to determine which one is best suited for your needs.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#laravel-the-artisans-choice">Laravel: The Artisan's Choice</a><ul>
<li><a class="post-section-overview" href="#why-laravel">Why Laravel?</a></li>
<li><a class="post-section-overview" href="#key-features">Key Features</a></li>
<li><a class="post-section-overview" href="#performance-metrics">Performance Metrics</a></li>
<li><a class="post-section-overview" href="#use-case">Use Case</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#symfony-the-enterprise-powerhouse">Symfony: The Enterprise Powerhouse</a><ul>
<li><a class="post-section-overview" href="#why-symfony">Why Symfony?</a></li>
<li><a class="post-section-overview" href="#key-features-1">Key Features</a></li>
<li><a class="post-section-overview" href="#performance-metrics-1">Performance Metrics</a></li>
<li><a class="post-section-overview" href="#use-case-1">Use Case</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#codeigniter-the-lightweight-contender">CodeIgniter: The Lightweight Contender</a><ul>
<li><a class="post-section-overview" href="#why-codeigniter">Why CodeIgniter?</a></li>
<li><a class="post-section-overview" href="#key-features-2">Key Features</a></li>
<li><a class="post-section-overview" href="#performance-metrics-2">Performance Metrics</a></li>
<li><a class="post-section-overview" href="#use-case-2">Use Case</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#performance-comparison-table">Performance Comparison Table</a></li>
<li><a class="post-section-overview" href="#which-php-framework-reigns-supreme">Which PHP Framework Reigns Supreme?</a></li>
<li><a class="post-section-overview" href="#faqs">FAQs</a></li>
</ol>
<hr />
<h3 id="heading-laravel-the-artisans-choice">Laravel: The Artisan's Choice</h3>
<h4 id="heading-why-laravel">Why Laravel?</h4>
<p>Laravel has emerged as one of the most popular PHP frameworks, thanks to its elegant syntax, extensive ecosystem, and vibrant community. It simplifies tasks like routing, authentication, and caching, making development a breeze.</p>
<h4 id="heading-key-features">Key Features:</h4>
<ul>
<li><strong>Eloquent ORM:</strong> Laravel's built-in ORM makes database interactions intuitive and efficient.</li>
<li><strong>Blade Templating Engine:</strong> A powerful yet simple templating engine that enhances performance.</li>
<li><strong>Artisan CLI:</strong> Command-line interface for automating repetitive tasks.</li>
<li><strong>Robust Security:</strong> Out-of-the-box protection against common security threats like SQL injection and XSS.</li>
</ul>
<h4 id="heading-performance-metrics">Performance Metrics:</h4>
<ul>
<li><strong>Execution Speed:</strong> Laravel 11 boasts an impressive execution speed, often clocking in at around 50-60 milliseconds per request.</li>
<li><strong>Response Time:</strong> On average, response times hover around 100 milliseconds, making it a responsive choice for dynamic web applications.</li>
</ul>
<h4 id="heading-use-case">Use Case:</h4>
<p>Laravel is perfect for applications that require rich features and extensive customization, such as e-commerce platforms and content management systems.</p>
<hr />
<h3 id="heading-symfony-the-enterprise-powerhouse">Symfony: The Enterprise Powerhouse</h3>
<h4 id="heading-why-symfony">Why Symfony?</h4>
<p>Symfony is renowned for its flexibility, scalability, and reusable components, making it a favorite among enterprises and large-scale applications. Its modularity allows developers to pick and choose the components they need, ensuring a tailored solution.</p>
<h4 id="heading-key-features-1">Key Features:</h4>
<ul>
<li><strong>Modular Architecture:</strong> Highly customizable and reusable components.</li>
<li><strong>Twig Templating Engine:</strong> Fast and secure templating system.</li>
<li><strong>Strong Community:</strong> Backed by a large, supportive community and excellent documentation.</li>
<li><strong>Advanced Security:</strong> Comprehensive security features for enterprise-level applications.</li>
</ul>
<h4 id="heading-performance-metrics-1">Performance Metrics:</h4>
<ul>
<li><strong>Execution Speed:</strong> Symfony 7 shows strong performance with execution speeds around 40-50 milliseconds per request.</li>
<li><strong>Response Time:</strong> Typically, response times are around 90 milliseconds, providing quick interactions for users.</li>
</ul>
<h4 id="heading-use-case-1">Use Case:</h4>
<p>Symfony shines in enterprise environments where robustness and scalability are paramount, such as corporate intranets, large-scale web services, and high-traffic websites.</p>
<hr />
<h3 id="heading-codeigniter-the-lightweight-contender">CodeIgniter: The Lightweight Contender</h3>
<h4 id="heading-why-codeigniter">Why CodeIgniter?</h4>
<p>CodeIgniter is celebrated for its simplicity, small footprint, and ease of use. It's an excellent choice for developers seeking a framework with minimal configuration and a lightweight approach.</p>
<h4 id="heading-key-features-2">Key Features:</h4>
<ul>
<li><strong>Lightweight:</strong> Minimal setup with a small footprint.</li>
<li><strong>Exceptional Performance:</strong> Known for its blazing-fast performance.</li>
<li><strong>Easy Learning Curve:</strong> Perfect for beginners due to its straightforward approach.</li>
<li><strong>Flexibility:</strong> Allows developers to use only what they need without heavy dependencies.</li>
</ul>
<h4 id="heading-performance-metrics-2">Performance Metrics:</h4>
<ul>
<li><strong>Execution Speed:</strong> CodeIgniter 4.5 leads with execution speeds often around 30-40 milliseconds per request.</li>
<li><strong>Response Time:</strong> With response times averaging 70 milliseconds, it offers one of the quickest interactions among PHP frameworks.</li>
</ul>
<h4 id="heading-use-case-2">Use Case:</h4>
<p>Ideal for small to medium-sized applications where performance is crucial, such as lightweight websites and simple APIs.</p>
<hr />
<h3 id="heading-performance-comparison-table">Performance Comparison Table</h3>
<p>To give you a clearer picture, here's a comparative table showcasing the execution speeds and response times of these top PHP frameworks:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Framework</td><td>Latest Version</td><td>Execution Speed (ms)</td><td>Response Time (ms)</td></tr>
</thead>
<tbody>
<tr>
<td>Laravel</td><td>11</td><td>50-60</td><td>100</td></tr>
<tr>
<td>Symfony</td><td>7</td><td>40-50</td><td>90</td></tr>
<tr>
<td>CodeIgniter</td><td>4.5</td><td>30-40</td><td>70</td></tr>
</tbody>
</table>
</div><hr />
<h3 id="heading-which-php-framework-reigns-supreme">Which PHP Framework Reigns Supreme?</h3>
<p>Choosing the best PHP framework ultimately depends on your specific needs and project requirements:</p>
<ul>
<li><strong>For feature-rich, customizable applications:</strong> Laravel is your go-to with its elegant syntax and extensive features.</li>
<li><strong>For enterprise-level, scalable applications:</strong> Symfony's flexibility and robust components make it the top choice.</li>
<li><strong>For lightweight, high-performance applications:</strong> CodeIgniter stands out with its simplicity and speed.</li>
</ul>
<p>Each framework has its strengths, and understanding these can guide you to the best choice for your next web development project.</p>
<hr />
<h3 id="heading-faqs">FAQs</h3>
<ol>
<li><p><strong>Which PHP framework is the fastest?</strong></p>
<ul>
<li>CodeIgniter typically offers the fastest execution and response times among the top frameworks.</li>
</ul>
</li>
<li><p><strong>Is Laravel suitable for beginners?</strong></p>
<ul>
<li>Yes, Laravel’s intuitive syntax and extensive documentation make it accessible for beginners.</li>
</ul>
</li>
<li><p><strong>Can Symfony handle high-traffic applications?</strong></p>
<ul>
<li>Absolutely, Symfony is designed for scalability and can efficiently manage high-traffic environments.</li>
</ul>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Simplifying Email Communication: Introducing Bulk Email Sender]]></title><description><![CDATA[Hey Dev community!
I'm excited to introduce my latest project, Bulk Email Sender! Managing email communication for your business, events, or personal contacts can be a daunting task. That's why I created Bulk Email Sender, a simple and powerful tool ...]]></description><link>https://blog.gulzaib.dev/simplifying-email-communication-introducing-bulk-email-sender</link><guid isPermaLink="true">https://blog.gulzaib.dev/simplifying-email-communication-introducing-bulk-email-sender</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Mon, 09 Oct 2023 05:08:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756839034/ca64c937-a5a3-49a5-817f-62b7365ea4e7.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey Dev community!</p>
<p>I'm excited to introduce my latest project, <strong>Bulk Email Sender</strong>! Managing email communication for your business, events, or personal contacts can be a daunting task. That's why I created Bulk Email Sender, a simple and powerful tool designed to streamline your email outreach efforts.</p>
<p><strong>What is Bulk Email Sender?</strong></p>
<p>Bulk Email Sender is a user-friendly application that enables you to effortlessly send emails to a large audience. Whether you're managing a business, organizing events, or just want to connect with many people, this project simplifies the process of sending bulk emails. Say goodbye to the hassle of managing multiple recipients individually – with Bulk Email Sender, you can import your contacts from an Excel file, design your email template, and send your messages in a matter of clicks.</p>
<p><strong>Technologies Used:</strong></p>
<ul>
<li><strong>Laravel 10</strong>: Utilizing the latest features and improvements from Laravel for a robust backend.</li>
<li><strong>PHP 8</strong>: Harnessing the power of PHP's latest version for efficient and secure server-side processing.</li>
</ul>
<p><strong>Key Features:</strong></p>
<ul>
<li><strong>Effortless Import</strong>: Import email addresses seamlessly from Excel files.</li>
<li><strong>HTML Email Support</strong>: Craft visually appealing emails using HTML templates.</li>
<li><strong>One-Time Sender</strong>: Send your emails with a single click.</li>
<li><strong>Contribution Friendly</strong>: Open-source project on GitHub, welcoming issues and pull requests.</li>
</ul>
<p><strong>How to Use Bulk Email Sender:</strong></p>
<ol>
<li>Select 'One Time Sender'.</li>
<li>Import your contacts from an Excel file.</li>
<li>Design your email template using the HTML editor.</li>
<li>Click send, and your emails are on their way!</li>
</ol>
<p><strong>Get Involved:</strong></p>
<p>I invite you to get involved with the Bulk Email Sender project! Whether you find a bug, have a feature request, or want to contribute, your input is valuable. Feel free to create issues or contribute code through pull requests on our <a target="_blank" href="https://github.com/arafat-web/Bulk-Email-Sender">GitHub repository</a>.</p>
<p><strong>Conclusion:</strong></p>
<p>Simplify your email communication and enhance your outreach efforts with Bulk Email Sender. It's designed with ease of use in mind, making it accessible for businesses, event organizers, and anyone looking to streamline their email campaigns.</p>
<p>Ready to simplify your email communication? <a target="_blank" href="https://github.com/arafat-web/Bulk-Email-Sender">Check out Bulk Email Sender on GitHub</a> and start sending emails effortlessly today!</p>
<p>Happy emailing! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Mastering PHP Foreach Loops: The Power of '&' for References ⚡🚀]]></title><description><![CDATA[Introduction
PHP, a versatile scripting language, offers a range of features to make developers' lives easier. Among these, the foreach loop stands out as a convenient tool for iterating over arrays and objects. However, there's a hidden gem within P...]]></description><link>https://blog.gulzaib.dev/mastering-php-foreach-loops-the-power-of-for-references</link><guid isPermaLink="true">https://blog.gulzaib.dev/mastering-php-foreach-loops-the-power-of-for-references</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Thu, 05 Oct 2023 11:55:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753755606452/46730ae3-f96c-49ff-b768-a3e262d79f72.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>PHP, a versatile scripting language, offers a range of features to make developers' lives easier. Among these, the <code>foreach</code> loop stands out as a convenient tool for iterating over arrays and objects. However, there's a hidden gem within PHP's <code>foreach</code> loops – the use of the <code>&amp;</code> symbol. In this comprehensive guide, we'll delve into the world of PHP foreach loops and explore how leveraging the <code>&amp;</code> symbol can take your coding skills to the next level.</p>
<h2 id="heading-understanding-php-foreach-loops">Understanding PHP Foreach Loops</h2>
<p>Before we dive into the specifics of the <code>&amp;</code> symbol, let's revisit the basics of PHP <code>foreach</code> loops. These loops are designed for iterating over arrays and objects, providing a clean and concise way to access and manipulate their elements.</p>
<pre><code class="lang-php">$fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'cherry'</span>];

<span class="hljs-keyword">foreach</span> ($fruits <span class="hljs-keyword">as</span> $fruit) {
    <span class="hljs-keyword">echo</span> $fruit . <span class="hljs-string">' '</span>;
}
<span class="hljs-comment">// Output: apple banana cherry</span>
</code></pre>
<h2 id="heading-the-power-of-amp-creating-references">The Power of '&amp;' – Creating References</h2>
<p>The <code>&amp;</code> symbol in PHP <code>foreach</code> loops allows us to create references to array elements or object properties rather than working with copies. This distinction can have a profound impact on how you manipulate data within the loop.</p>
<pre><code class="lang-php">$fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'cherry'</span>];

<span class="hljs-keyword">foreach</span> ($fruits <span class="hljs-keyword">as</span> &amp;$fruit) {
    $fruit = strtoupper($fruit);
}

<span class="hljs-comment">// $fruits now contains ['APPLE', 'BANANA', 'CHERRY']</span>
</code></pre>
<p>Here, we've transformed the original array's elements to uppercase using the reference created with <code>&amp;</code>.</p>
<h2 id="heading-common-use-cases-for-amp-in-foreach-loops">Common Use Cases for '&amp;' in Foreach Loops</h2>
<p>While not every loop requires the use of <code>&amp;</code>, there are situations where it can be incredibly useful:</p>
<h3 id="heading-modifying-array-elements-by-reference">Modifying Array Elements by Reference</h3>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">foreach</span> ($numbers <span class="hljs-keyword">as</span> &amp;$number) {
    $number *= <span class="hljs-number">2</span>;
}
<span class="hljs-comment">// $numbers becomes [2, 4, 6, 8]</span>
</code></pre>
<h3 id="heading-creating-dynamic-references">Creating Dynamic References</h3>
<pre><code class="lang-php">$variables = [<span class="hljs-string">'var1'</span>, <span class="hljs-string">'var2'</span>, <span class="hljs-string">'var3'</span>];
<span class="hljs-keyword">foreach</span> ($variables <span class="hljs-keyword">as</span> $varName) {
    $$varName = <span class="hljs-string">'initialized'</span>;
}
<span class="hljs-comment">// $var1, $var2, and $var3 are now initialized variables</span>
</code></pre>
<h3 id="heading-efficiently-handling-large-datasets">Efficiently Handling Large Datasets</h3>
<pre><code class="lang-php"><span class="hljs-comment">// Process large dataset efficiently using references</span>
$largeData = fetchData();
<span class="hljs-keyword">foreach</span> ($largeData <span class="hljs-keyword">as</span> &amp;$dataItem) {
    processData($dataItem);
}
</code></pre>
<h2 id="heading-pitfalls-and-best-practices">Pitfalls and Best Practices</h2>
<p>While using <code>&amp;</code> in <code>foreach</code> loops can be powerful, it comes with potential pitfalls. Here are some best practices to keep in mind:</p>
<h3 id="heading-unset-references">Unset References</h3>
<pre><code class="lang-php">$fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'cherry'</span>];
<span class="hljs-keyword">foreach</span> ($fruits <span class="hljs-keyword">as</span> &amp;$fruit) {
    <span class="hljs-comment">// Some logic here</span>
}
<span class="hljs-keyword">unset</span>($fruit); <span class="hljs-comment">// Important to unset the reference</span>
</code></pre>
<h3 id="heading-avoid-nesting-references">Avoid Nesting References</h3>
<pre><code class="lang-php">$matrix = [[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]];
<span class="hljs-keyword">foreach</span> ($matrix <span class="hljs-keyword">as</span> &amp;$row) {
    <span class="hljs-keyword">foreach</span> ($row <span class="hljs-keyword">as</span> &amp;$value) {
        <span class="hljs-comment">// Avoid nesting references – can lead to unexpected behavior</span>
    }
}
</code></pre>
<h2 id="heading-alternatives-to-amp-in-foreach-loops">Alternatives to '&amp;' in Foreach Loops</h2>
<p>In some cases, you can achieve similar results without using references:</p>
<h3 id="heading-using-arraymap">Using array_map</h3>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
$numbers = array_map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$number</span>) </span>{
    <span class="hljs-keyword">return</span> $number * <span class="hljs-number">2</span>;
}, $numbers);
<span class="hljs-comment">// $numbers becomes [2, 4, 6, 8]</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Mastering PHP foreach loops and understanding the power of &amp; for references can significantly improve your coding efficiency. While this feature should be used judiciously to avoid unintended consequences, it offers a valuable tool for working with arrays and objects. By following best practices and considering alternatives, you can confidently navigate the world of PHP loops and elevate your programming skills.</p>
]]></content:encoded></item><item><title><![CDATA[20 Useful ChatGPT Prompts for Web Developers: Boosting Your Development Journey]]></title><description><![CDATA[In the vast realm of web development, having access to valuable resources and insights can significantly enhance your skills and creativity. ChatGPT, powered by OpenAI, is a powerful tool that can be harnessed by web developers to gain knowledge, sol...]]></description><link>https://blog.gulzaib.dev/20-useful-chatgpt-prompts-for-web-developers-boosting-your-development-journey</link><guid isPermaLink="true">https://blog.gulzaib.dev/20-useful-chatgpt-prompts-for-web-developers-boosting-your-development-journey</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Thu, 05 Oct 2023 09:39:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756843484/0c1086b9-5375-4f62-aa5d-af4a35999079.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the vast realm of web development, having access to valuable resources and insights can significantly enhance your skills and creativity. ChatGPT, powered by OpenAI, is a powerful tool that can be harnessed by web developers to gain knowledge, solve problems, and spark inspiration. In this blog post, we’ll explore 20 useful ChatGPT prompts tailored specifically for web developers.</p>
<h3 id="heading-1-debugging-assistance">1. <strong>Debugging Assistance:</strong></h3>
<p>   <em>"Help me debug my code: I'm facing an issue with [specific problem] in [programming language/framework]. Can you guide me through the debugging process?"</em></p>
<h3 id="heading-2-learning-pathways">2. <strong>Learning Pathways:</strong></h3>
<p>   <em>"Suggest the best online courses and tutorials for mastering frontend technologies like HTML, CSS, and JavaScript."</em></p>
<h3 id="heading-3-framework-comparisons">3. <strong>Framework Comparisons:</strong></h3>
<p>   <em>"Compare and contrast popular JavaScript frameworks like React, Angular, and Vue.js. What are their strengths and ideal use cases?"</em></p>
<h3 id="heading-4-design-tips">4. <strong>Design Tips:</strong></h3>
<p>   <em>"Provide tips for creating intuitive user interfaces. What are the best practices for UI/UX design in web development?"</em></p>
<h3 id="heading-5-performance-optimization">5. <strong>Performance Optimization:</strong></h3>
<p>   <em>"Share techniques for optimizing website performance. How can I reduce page load times and improve overall responsiveness?"</em></p>
<h3 id="heading-6-security-measures">6. <strong>Security Measures:</strong></h3>
<p>   <em>"What are the essential security practices for web applications? How can I safeguard against common vulnerabilities like XSS and CSRF attacks?"</em></p>
<h3 id="heading-7-responsive-design-guidelines">7. <strong>Responsive Design Guidelines:</strong></h3>
<p>   <em>"Explain the principles of responsive web design. What CSS techniques can I use to create mobile-friendly layouts?"</em></p>
<h3 id="heading-8-database-integration">8. <strong>Database Integration:</strong></h3>
<p>   <em>"Guide me on integrating a database into my web application. What are the steps for connecting and querying a database using [specific technology]?"</em></p>
<h3 id="heading-9-seo-best-practices">9. <strong>SEO Best Practices:</strong></h3>
<p>   <em>"What are the SEO strategies for improving a website's visibility on search engines? How can I optimize my website's content and structure for better rankings?"</em></p>
<h3 id="heading-10-version-control-help">10. <strong>Version Control Help:</strong></h3>
<p>   <em>"Explain the basics of Git version control. How can I create repositories, commit changes, and manage branches effectively?"</em></p>
<h3 id="heading-11-progressive-web-apps-pwas">11. <strong>Progressive Web Apps (PWAs):</strong></h3>
<p>   <em>"Share insights on Progressive Web Apps. What are the key features, and how can I convert my website into a PWA for enhanced user experience?"</em></p>
<h3 id="heading-12-web-accessibility">12. <strong>Web Accessibility:</strong></h3>
<p>   <em>"Explain the importance of web accessibility. What are the guidelines and techniques for making web applications accessible to users with disabilities?"</em></p>
<h3 id="heading-13-api-integration">13. <strong>API Integration:</strong></h3>
<p>   <em>"Guide me on integrating third-party APIs into my web project. What are the best practices for authentication and error handling?"</em></p>
<h3 id="heading-14-code-review-assistance">14. <strong>Code Review Assistance:</strong></h3>
<p>   <em>"Review my code for [specific feature/section] in my web application. Are there any improvements or optimizations I could make?"</em></p>
<h3 id="heading-15-security-headers">15. <strong>Security Headers:</strong></h3>
<p>   <em>"What are security headers, and how can I implement them in my web application to enhance security?"</em></p>
<h3 id="heading-16-testing-strategies">16. <strong>Testing Strategies:</strong></h3>
<p>   <em>"What are the different types of testing (unit, integration, end-to-end) in web development? How can I implement effective testing strategies in my projects?"</em></p>
<h3 id="heading-17-deployment-best-practices">17. <strong>Deployment Best Practices:</strong></h3>
<p>   <em>"Share best practices for deploying web applications. What services can I use for hosting, and what steps are involved in the deployment process?"</em></p>
<h3 id="heading-18-cross-browser-compatibility">18. <strong>Cross-Browser Compatibility:</strong></h3>
<p>   <em>"How can I ensure my web application works seamlessly across different web browsers? What are the common challenges and solutions for cross-browser compatibility?"</em></p>
<h3 id="heading-19-content-management-systems-cms">19. <strong>Content Management Systems (CMS):</strong></h3>
<p>   <em>"Compare popular CMS platforms like WordPress, Joomla, and Drupal. What are their strengths, and how can I choose the right CMS for my project?"</em></p>
<h3 id="heading-20-continuous-learning-resources">20. <strong>Continuous Learning Resources:</strong></h3>
<p>   <em>"Recommend online communities, forums, and newsletters where web developers can stay updated with the latest trends, tools, and best practices."</em></p>
<p>By utilizing these ChatGPT prompts, web developers can tap into a wealth of knowledge and expertise, making their development journey more informed and efficient. Remember, the key to success in web development lies not only in solving problems but also in the continuous pursuit of knowledge and the willingness to explore new ideas and technologies. Happy coding! 🚀✨</p>
]]></content:encoded></item><item><title><![CDATA[Responsive Web Design with Flexbox: A Quick Guide with Examples]]></title><description><![CDATA[Responsive web design is no longer an option; it's a standard. In this digital era where users access websites on a plethora of devices, crafting layouts that seamlessly adapt has become a fundamental skill for developers. Flexbox, a layout model in ...]]></description><link>https://blog.gulzaib.dev/responsive-web-design-with-flexbox-a-quick-guide-with-examples</link><guid isPermaLink="true">https://blog.gulzaib.dev/responsive-web-design-with-flexbox-a-quick-guide-with-examples</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Thu, 05 Oct 2023 04:50:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753756847105/92308c7f-0483-4db0-862b-ad268e6a372b.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Responsive web design is no longer an option; it's a standard. In this digital era where users access websites on a plethora of devices, crafting layouts that seamlessly adapt has become a fundamental skill for developers. Flexbox, a layout model in CSS, has emerged as a powerful tool, simplifying the creation of responsive and flexible designs. In this comprehensive guide, we will delve deep into Flexbox, exploring its properties in detail and providing practical examples to help you master the art of responsive web design.</p>
<h3 id="heading-understanding-the-basics-of-flexbox"><strong>Understanding the Basics of Flexbox</strong></h3>
<p>At its core, Flexbox is designed to provide a more efficient way to layout, align, and distribute space among items in a container, even when their size is unknown or dynamic. Before we dive into the properties, let's understand the fundamental concepts of Flexbox:</p>
<ol>
<li><p><strong>Flex Container:</strong> Any container set to <code>display: flex;</code> becomes a Flex Container. It enables a flex context for all its direct children.</p>
</li>
<li><p><strong>Flex Items:</strong> Direct children of a Flex Container automatically become Flex Items and are laid out using the Flexbox model.</p>
</li>
</ol>
<h3 id="heading-exploring-flexbox-properties"><strong>Exploring Flexbox Properties</strong></h3>
<h4 id="heading-1-justify-content-aligning-along-the-main-axis"><strong>1. <code>justify-content</code>: Aligning Along the Main Axis</strong></h4>
<p>This property aligns Flex Items along the main axis of the Flex Container.</p>
<ul>
<li><strong><code>flex-start</code> (default):</strong> Items are packed toward the start of the main axis.</li>
<li><strong><code>flex-end</code>:</strong> Items are packed toward the end of the main axis.</li>
<li><strong><code>center</code>:</strong> Items are centered along the main axis.</li>
<li><strong><code>space-between</code>:</strong> Items are evenly distributed with the first item at the start and the last item at the end.</li>
<li><strong><code>space-around</code>:</strong> Items are evenly distributed with equal space around them.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: space-around; <span class="hljs-comment">/* Items distributed with space around them */</span>
}
</code></pre>
<h4 id="heading-2-align-items-aligning-along-the-cross-axis"><strong>2. <code>align-items</code>: Aligning Along the Cross Axis</strong></h4>
<p>This property aligns Flex Items along the cross axis of the Flex Container.</p>
<ul>
<li><strong><code>flex-start</code>:</strong> Items are aligned at the start of the cross axis.</li>
<li><strong><code>flex-end</code>:</strong> Items are aligned at the end of the cross axis.</li>
<li><strong><code>center</code>:</strong> Items are centered along the cross axis.</li>
<li><strong><code>baseline</code>:</strong> Items are aligned such that their baselines align.</li>
<li><strong><code>stretch</code> (default):</strong> Items are stretched to fill the container.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">align-items</span>: center; <span class="hljs-comment">/* Items centered along the cross axis */</span>
}
</code></pre>
<h4 id="heading-3-flex-direction-specifying-the-main-axis"><strong>3. <code>flex-direction</code>: Specifying the Main Axis</strong></h4>
<p>This property defines the direction in which the main axis of the Flex Container points.</p>
<ul>
<li><strong><code>row</code> (default):</strong> Main axis runs from left to right.</li>
<li><strong><code>row-reverse</code>:</strong> Main axis runs from right to left.</li>
<li><strong><code>column</code>:</strong> Main axis runs from top to bottom.</li>
<li><strong><code>column-reverse</code>:</strong> Main axis runs from bottom to top.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">flex-direction</span>: column; <span class="hljs-comment">/* Main axis runs from top to bottom */</span>
}
</code></pre>
<h4 id="heading-4-flex-wrap-controlling-wrapping-of-flex-items"><strong>4. <code>flex-wrap</code>: Controlling Wrapping of Flex Items</strong></h4>
<p>This property controls whether the Flex Items should wrap to the next line if they exceed the container's width.</p>
<ul>
<li><strong><code>nowrap</code> (default):</strong> Items are not wrapped.</li>
<li><strong><code>wrap</code>:</strong> Items wrap to the next line if necessary.</li>
<li><strong><code>wrap-reverse</code>:</strong> Items wrap to the previous line if necessary.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">flex-wrap</span>: wrap; <span class="hljs-comment">/* Items wrap to the next line if necessary */</span>
}
</code></pre>
<h4 id="heading-5-align-self-aligning-individual-flex-items"><strong>5. <code>align-self</code>: Aligning Individual Flex Items</strong></h4>
<p>This property allows the default alignment set by <code>align-items</code> to be overridden for individual Flex Items.</p>
<ul>
<li><strong><code>auto</code> (default):</strong> Inherits the value from its parent <code>align-items</code> property.</li>
<li><strong><code>flex-start</code>:</strong> Item is aligned at the start of the cross axis.</li>
<li><strong><code>flex-end</code>:</strong> Item is aligned at the end of the cross axis.</li>
<li><strong><code>center</code>:</strong> Item is centered along the cross axis.</li>
<li><strong><code>baseline</code>:</strong> Item is aligned such that its baseline aligns.</li>
<li><strong><code>stretch</code>:</strong> Item is stretched to fill the container.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-class">.item</span> {
    <span class="hljs-attribute">align-self</span>: flex-start; <span class="hljs-comment">/* Item is aligned at the start of the cross axis */</span>
}
</code></pre>
<h3 id="heading-practical-examples-applying-flexbox-properties"><strong>Practical Examples: Applying Flexbox Properties</strong></h3>
<h4 id="heading-example-1-creating-a-horizontal-navigation-bar"><strong>Example 1: Creating a Horizontal Navigation Bar</strong></h4>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-bar"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>Home<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">class</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>About<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">class</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>Services<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">class</span>=<span class="hljs-string">"nav-item"</span>&gt;</span>Contact<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>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.nav-bar</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: space-around;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">color</span>:

 white;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.nav-item</span> {
    <span class="hljs-attribute">flex</span>: <span class="hljs-number">1</span>;
    <span class="hljs-attribute">text-align</span>: center;
}
</code></pre>
<p>In this example, the navigation items are evenly distributed within the <code>.nav-bar</code> container, creating a responsive horizontal navigation bar.</p>
<h4 id="heading-example-2-building-a-flexible-card-layout"><strong>Example 2: Building a Flexible Card Layout</strong></h4>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>Card 1<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">class</span>=<span class="hljs-string">"card"</span>&gt;</span>Card 2<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">class</span>=<span class="hljs-string">"card"</span>&gt;</span>Card 3<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>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.card-container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">flex-wrap</span>: wrap;
    <span class="hljs-attribute">justify-content</span>: space-around;
}

<span class="hljs-selector-class">.card</span> {
    <span class="hljs-attribute">flex</span>: <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">30%</span>; <span class="hljs-comment">/* Each card takes up 30% of the container width */</span>
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
    <span class="hljs-attribute">text-align</span>: center;
}
</code></pre>
<p>Here, the <code>.card-container</code> uses Flexbox properties to create a responsive card layout that adjusts its width based on the screen size.</p>
<h3 id="heading-conclusion-empowering-web-design-with-flexbox"><strong>Conclusion: Empowering Web Design with Flexbox</strong></h3>
<p>Flexbox provides a powerful and intuitive way to create responsive layouts in CSS. By understanding and mastering its properties, you can craft visually appealing and user-friendly designs that adapt seamlessly across various devices. With Flexbox, the complexities of layout design are simplified, allowing developers to focus on creating engaging user interfaces. So, experiment with these properties, explore their capabilities, and elevate your web design skills to new heights. Happy coding! 🚀✨</p>
]]></content:encoded></item><item><title><![CDATA[Concurrency Management: How Web Servers Keep the Show Running Smoothly ⚡🚀]]></title><description><![CDATA[In the realm of web development, the ability to efficiently handle multiple client requests concurrently is a fundamental aspect of ensuring a responsive and scalable web application. PHP, a popular server-side scripting language, plays a crucial rol...]]></description><link>https://blog.gulzaib.dev/concurrency-management-how-web-servers-keep-the-show-running-smoothly</link><guid isPermaLink="true">https://blog.gulzaib.dev/concurrency-management-how-web-servers-keep-the-show-running-smoothly</guid><dc:creator><![CDATA[Gul Zaib]]></dc:creator><pubDate>Wed, 04 Oct 2023 20:22:05 GMT</pubDate><content:encoded><![CDATA[<p>In the realm of web development, the ability to efficiently handle multiple client requests concurrently is a fundamental aspect of ensuring a responsive and scalable web application. PHP, a popular server-side scripting language, plays a crucial role in this process. In this blog post, we will delve into how PHP and the PHP server achieve this by isolating and managing variables and data separately for each request.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Concurrency, in the context of web development, refers to the ability of a web server to process multiple incoming client requests simultaneously. It's vital for ensuring that a web application can serve many users without slowing down or crashing.</p>
<h2 id="heading-web-server-setup">Web Server Setup</h2>
<p>To understand how PHP manages concurrent requests, let's start with the setup. Most web servers (e.g., Apache or Nginx) use a multi-process or multi-threaded model to handle incoming HTTP requests. This means that the web server can spawn multiple PHP processes or threads to execute scripts in parallel.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753755610477/cc41afeb-374d-4456-a819-94bf37cae2d4.png" alt="Multi-tasking in humans" /></p>
<h2 id="heading-concurrency-models">Concurrency Models</h2>
<h3 id="heading-multi-process-model">Multi-Process Model</h3>
<p>In the multi-process model, the web server creates a separate process for each incoming request. Each process runs independently, allowing multiple requests to be processed simultaneously. This model is advantageous for stability because if one process crashes, it doesn't affect others.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753755611830/443a7a4a-61a7-40e3-b1f3-8c0e9a79d727.png" alt="Multi processing" /></p>
<h3 id="heading-multi-threaded-model">Multi-Threaded Model</h3>
<p>Some web servers use multiple threads instead of processes. Each thread can handle one request at a time, but multiple threads can run concurrently. This model is more memory-efficient but can be less robust since a problem in one thread can affect the entire server.</p>
<p><strong>Example:</strong> Imagine you're running a popular e-commerce website, and it's Black Friday. This means a massive influx of users trying to snag the best deals simultaneously. To handle this surge in traffic, your web server uses multiple PHP processes, each responsible for a client's request.</p>
<h2 id="heading-isolation-of-variables">Isolation of Variables</h2>
<p>One key aspect of handling concurrent requests is the isolation of variables and data. When a client makes an HTTP request, a new PHP process or thread is spawned to handle that specific request. Variables declared within a PHP script are local to that process or thread, ensuring that they do not interfere with variables in other concurrent requests.</p>
<h2 id="heading-data-storage-and-retrieval">Data Storage and Retrieval</h2>
<p>Data retrieval during the execution of a PHP script is also isolated for each request. For example, if a script connects to a database, each request has its own database connection or resource handle. This ensures that data retrieved during one request does not conflict with data retrieval for other requests.</p>
<h2 id="heading-response-generation-and-sending">Response Generation and Sending</h2>
<p>After processing a request, the PHP script generates an HTTP response, typically in the form of HTML or other content. This response is sent back to the requesting client. Importantly, the response generated for one request does not mix with the response for another request because each response is sent separately.</p>
<h2 id="heading-concurrency-management">Concurrency Management</h2>
<p>Web servers are responsible for managing concurrent requests efficiently. They queue incoming requests and allocate resources (processes or threads) as needed to ensure that multiple requests are processed in parallel without conflicts.</p>
<h2 id="heading-benefits-of-concurrency-handling">Benefits of Concurrency Handling</h2>
<p>Efficient concurrent request handling offers several benefits, including improved application responsiveness, scalability, and the ability to serve many users simultaneously. It's essential for modern web applications.</p>
<h2 id="heading-real-world-scenarios">Real-World Scenarios</h2>
<p>Explore real-world scenarios where PHP's concurrent request handling shines. This could include e-commerce platforms handling simultaneous user orders, social media sites serving multiple users' feeds, or content delivery networks (CDNs) distributing content efficiently.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, PHP's ability to handle multiple client requests concurrently by isolating and managing variables and data separately for each request is a crucial aspect of web development. It ensures that web applications can provide a smooth and responsive user experience even under heavy load.</p>
]]></content:encoded></item></channel></rss>