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
| Task | Utility Function |
|---|---|
| Format currency | formatPrice(123.4) โ "$123.40" |
| Generate slug from text | slugify("Hello World") โ "hello-world" |
| Convert bytes to human-readable | bytesToHuman(10240) โ "10 KB" |
| Check if a string is JSON | isJson($str) |
| Pluralize words | pluralize('apple', 2) โ 'apples' |
Example:
function formatPrice($price)
{
return '$' . number_format($price, 2);
}
echo formatPrice(1299); // $1,299.00You can then use it anywhere:
๐ฆ Where to Store Utility Functions in Laravel
- Custom Helpers File
- Create
app/Helpers/helpers.php - Add your functions
- Register in
composer.jsonunderautoload.files
- Create
- 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, parsing | Business rules, DB access |
| Stateless, pure logic | Stateful operations |
| Generic string/date manipulation | App-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?
