The DRY Principle in PHP: Writing Cleaner, More Efficient Code

WhoAmI => notes.sohag.pro/author
Search for a command to run...

WhoAmI => notes.sohag.pro/author
No comments yet. Be the first to comment.
[“KISS” => “Keep It Simple, Stupid”] Introduction: What is the KISS Principle? KISS stands for "Keep It Simple, Stupid" - a principle that is as powerful as it is straightforward. In the world of programming, and especially in PHP, complexity is ofte...
I had a solid list of reasons my life wasn't moving faster, until a grainy old lecture pointed out the one name missing from it

The finale isn't a victory lap. It's the story of the control I shipped that did nothing, the footgun still sitting in my demo, and the handful of things I'd keep exactly as they are.

How do you hold a large payment for a second pair of eyes without ever letting the unapproved money touch a balance, and how do you stream that decision to the outside world without standing up a broker?

How do you show the total under a parent account when the whole system refuses to store a balance? A recursive query, a trigger that refuses to draw a circle, and a rule about what actually has to sum to zero.

Every time I wanted to change an FX rate I had to edit a file on the server and restart the app. So I moved rates and markup into a live admin API, and then audited it hard enough to find the bug that quietly undid the whole thing.

DRY stands for "Don't Repeat Yourself" - a fundamental principle of software development that aims to reduce repetition in code. Think of it like a cooking recipe: if you find yourself doing the same steps over and over, it's time to create a reusable method that does the work for you.
Imagine you're managing a coffee shop. Every time a customer orders a drink, you:
Greet the customer
Take their order
Process the payment
Prepare the drink
Serve the drink
Instead of manually going through these steps each time, you'd create a standard process (or in programming terms, a method) that handles these repeated tasks efficiently.
<?php
// Calculating total price for different order types
function calculatePizzaTotal($pizzaPrice, $quantity) {
$tax = 0.1;
$total = $pizzaPrice * $quantity;
$totalWithTax = $total * (1 + $tax);
return $totalWithTax;
}
function calculateBurgerTotal($burgerPrice, $quantity) {
$tax = 0.1;
$total = $burgerPrice * $quantity;
$totalWithTax = $total * (1 + $tax);
return $totalWithTax;
}
function calculateSaladTotal($saladPrice, $quantity) {
$tax = 0.1;
$total = $saladPrice * $quantity;
$totalWithTax = $total * (1 + $tax);
return $totalWithTax;
}
<?php
class PriceCalculator {
private const TAX_RATE = 0.1;
public function calculateTotal($itemPrice, $quantity) {
$total = $itemPrice * $quantity;
return $total * (1 + self::TAX_RATE);
}
}
// Usage
$calculator = new PriceCalculator();
$pizzaTotal = $calculator->calculateTotal(10, 2);
$burgerTotal = $calculator->calculateTotal(8, 3);
<?php
// Before DRY
function sendEmailToAdmin($message) {
$to = 'admin@example.com';
mail($to, 'System Notification', $message);
}
function sendEmailToSupport($message) {
$to = 'support@example.com';
mail($to, 'System Notification', $message);
}
// After DRY
function sendEmail($to, $message) {
mail($to, 'System Notification', $message);
}
sendEmail('admin@example.com', 'Admin message');
sendEmail('support@example.com', 'Support message');
<?php
trait Loggable {
public function log($message) {
file_put_contents('app.log', $message . PHP_EOL, FILE_APPEND);
}
}
class UserService {
use Loggable;
public function createUser($userData) {
// User creation logic
$this->log('User created: ' . $userData['username']);
}
}
class ProductService {
use Loggable;
public function addProduct($productData) {
// Product addition logic
$this->log('Product added: ' . $productData['name']);
}
}
<?php
class AppConfig {
public const DATABASE_HOST = 'localhost';
public const DATABASE_USER = 'root';
public const DATABASE_PASS = 'password';
public static function getDatabaseConnection() {
return new PDO(
'mysql:host=' . self::DATABASE_HOST,
self::DATABASE_USER,
self::DATABASE_PASS
);
}
}
Over-Abstraction: Don't create complex methods for simple tasks
Premature Optimization: Write readable code first, then optimize
Copy-Paste Coding: Always refactor repeated code
Reduced Maintenance: Less code means fewer places to fix bugs
Improved Readability: Clean, concise code is easier to understand
Faster Development: Reusable components speed up coding
Lower Cognitive Load: Less mental effort to manage code
The DRY principle is like a secret weapon in a programmer's toolkit. It's not about being lazy, but about being smart. By reducing repetition, you create more maintainable, efficient, and elegant code.
Always look for patterns in your code
Refactor regularly
Use PHP's object-oriented features
Embrace code reusability
Happy coding! 🚀👨💻