HomePHPWhat is Utility Functions

What is Utility Functions

Utility functions are simple, reusable functions that perform generic, low-level tasks commonly needed across different parts of an application. They are designed to be stateless, independent, and not tightly tied to the application’s business logic.


๐Ÿ”ง Utility Functions Explained

๐Ÿง  Key Characteristics:

  • Perform single, specific tasks
  • Do not depend on external state (ideally)
  • Are reusable in multiple parts of the application
  • Typically small in size and pure (same input โ†’ same output)

โœ… Examples in Laravel / PHP

TaskUtility Function
Format currencyformatPrice(123.4) โ†’ "$123.40"
Generate slug from textslugify("Hello World") โ†’ "hello-world"
Convert bytes to human-readablebytesToHuman(10240) โ†’ "10 KB"
Check if a string is JSONisJson($str)
Pluralize wordspluralize('apple', 2) โ†’ 'apples'

Example:

function formatPrice($price)
{
    return '$' . number_format($price, 2);
}
echo formatPrice(1299); // $1,299.00

You can then use it anywhere:


๐Ÿ“ฆ Where to Store Utility Functions in Laravel

  1. Custom Helpers File
    • Create app/Helpers/helpers.php
    • Add your functions
    • Register in composer.json under autoload.files
  2. Namespaced Utility Class (Recommended for Larger Apps)
namespace App\Utils; 

class StringHelper {
 public static function slugify($text) {  
 return Str::slug($text);
} 
 } 
 Usage: Helper::slugify("Hello World");

๐Ÿš€ Benefits of Utility Functions

  • Code reuse โ€“ write once, use everywhere
  • Cleaner code โ€“ keeps controllers/models focused
  • Improves consistency โ€“ centralized logic
  • Boosts performance โ€“ no heavy class overhead

โš ๏ธ When to Avoid Utility Functions

  • When logic involves database access
  • When the function needs state or configuration
  • When logic is complex or business-specific โ†’ use services instead

๐Ÿงช Testing Utility Functions

  • Easy to test if pure
  • Example PHPUnit test:
public function test_format_price()
{
    $this->assertEquals('$123.45', formatPrice(123.45));
}

๐Ÿ“ Summary

โœ… Use ForโŒ Avoid For
Formatting, converting, parsingBusiness rules, DB access
Stateless, pure logicStateful operations
Generic string/date manipulationApp-specific flows or decisions

Would you like a starter template or a set of common Laravel utility functions to include in your own helper file or package?

Share:ย 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *