DEV Community

Cover image for Stop Reinventing the Wheel: 5 Hidden Gems in PrestaShop's Tools.php File
Nicolas Dabene
Nicolas Dabene

Posted on • Originally published at nicolas-dabene.fr

Stop Reinventing the Wheel: 5 Hidden Gems in PrestaShop's Tools.php File

Unlock PrestaShop's Power: 5 Essential Functions in Tools.php You're Overlooking

🧠 The Modern Developer's Dilemma

Developers often navigate a challenging duality. We aspire to pristine codebases, perfectly decoupled components, and strict adherence to SOLID principles – the gold standard of software engineering. However, the everyday reality of e-commerce development frequently presents a contrasting picture: demanding clients, often sub-optimal shared hosting, and an unwavering pressure for rapid delivery.

Naturally, our instincts might tell us to steer clear of PrestaShop's Tools class. It’s a classic example of what's often termed a "God Class" – a colossal file, spanning over 4000 lines in the current development branch, that seems to perform every conceivable task: managing files, handling HTTP requests, manipulating strings, and more.

But today, I invite you to consider an unconventional approach: let's cease the redundant effort of reimplementing helper functions that PrestaShop has diligently maintained and perfected over the last fifteen years. I've conducted a thorough review of the latest PrestaShop source code, and I'm ready to unveil five remarkably practical functions (no exaggerations here!) that will undeniably simplify your development workflow and fortify your code.

⚡ Why Delve into this "Legacy" File?

Contemporary software architecture frequently advises against static method heavy classes like Tools::someMethod(), viewing them as promoters of tight coupling. Yet, Tools.php stands as PrestaShop's inherent resilience mechanism. Every seemingly peculiar line of code, every deeply nested conditional within this file, often represents a hard-won victory against a past bug or a workaround for an obscure server compatibility issue you haven't yet encountered.

Consider the trade-off: Would you rather spend three hours crafting a recursive directory deletion function that meticulously accounts for both Windows and Linux permissions, or leverage a single, battle-tested line of code?

In an era defined by AI and automation, the true mark of a skilled developer isn't just knowing how to write a basic loop. It's about discerning which pre-existing building blocks to strategically employ to construct robust and reliable solutions.

🚀 Practical Insights: 5 Verifiable Native Functions

Let's move past theoretical possibilities. Here are five concrete functions residing within the PrestaShop core that deserve a place in your toolkit.

1. Tools::getOctets(): Conversing in Server Language

The Scenario: You need to verify if an uploaded file's size surpasses the upload_max_filesize limit set in php.ini. Retrieving this value with ini_get might yield responses like "128M" or "2G". Attempting a direct mathematical comparison (e.g., if ($file_size > "128M")) will either fail or produce meaningless results.

The PrestaShop Advantage:
Eliminate the need to write your own switch/case logic for unit conversions.

$maxSize = Tools::getOctets(ini_get('upload_max_filesize'));
// For "128M", this returns the integer: 134217728 bytes.
Enter fullscreen mode Exit fullscreen mode

This function is straightforward, dependable, and flawlessly translates K, M, and G suffixes into bytes, saving you tedious manual calculations.

2. Tools::deleteDirectory(): Effortless Deep Cleansing

The Scenario: Deleting a non-empty directory in PHP can be a genuine headache. The native rmdir() function only works on empty folders. This forces developers to implement complex recursive functions to open directories, enumerate and delete files one by one, and then descend into subdirectories – a significant maintenance burden.

The PrestaShop Advantage:
PrestaShop offers a native solution that even handles hidden files (excluding .svn and .git, which is convenient for developers).

if (Tools::deleteDirectory($myTempFolder)) {
    // The folder and all its contents have been successfully removed.
}
Enter fullscreen mode Exit fullscreen mode

I frequently observe this functionality being re-implemented in countless third-party modules. There's no need. Use this proven method instead.

3. Tools::str2url(): The SEO Cornerstone

The Scenario: You need to generate a clean, URL-friendly "slug" from a product title like "Christmas & Wonders: 2025 edition!". This requires careful handling of accents, spaces, punctuation, and capitalization to create a web-friendly string.

The PrestaShop Advantage:
This is the very function PrestaShop's core uses to generate its product URLs.

$slug = Tools::str2url("Christmas & Wonders: 2025 edition!");
// Result: "christmas-wonders-2025-edition"
Enter fullscreen mode Exit fullscreen mode

It intelligently uses iconv or mb_string (depending on server availability) to normalize exotic encodings. Employing this ensures consistency with the rest of your store's URL structure.

4. Tools::getRemoteAddr(): Beyond $_SERVER['REMOTE_ADDR']

The Scenario: You need the client's IP address, perhaps for security logging. Your initial instinct might be $_SERVER['REMOTE_ADDR'].
The Pitfall: If your store operates behind a service like Cloudflare or a Load Balancer, REMOTE_ADDR will report the proxy's IP, not the actual client's.

The PrestaShop Advantage:
This function is meticulously crafted. It systematically checks a sequence of HTTP headers (such as HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, etc.) to accurately determine the user's true IP address.

// Crucial for robust payment or anti-fraud modules
$userIp = Tools::getRemoteAddr();
Enter fullscreen mode Exit fullscreen mode

Note: This function can also accommodate IP anonymization if your PrestaShop configuration requires it.

5. Tools::file_get_contents(): The Smart Network Handler

The Scenario: You need to interact with an external API (fetching JSON data, currency exchange rates) and your default choice is PHP's native file_get_contents().
The Roadblock: On many shared hosting environments, allow_url_fopen is disabled for security reasons, causing your module to crash.

The PrestaShop Advantage:
This method, sharing a name with the native PHP function (which can sometimes lead to confusion), acts as an intelligent wrapper.

  • It first verifies if cURL is available and prioritizes its use (being generally faster and more secure).
  • If cURL isn't an option, it gracefully falls back to the native file_get_contents().
  • It also incorporates crucial features like timeout management and SSL context handling.
$json = Tools::file_get_contents('https://api.my-service.com/data');
Enter fullscreen mode Exit fullscreen mode

For straightforward HTTP GET requests, it's an incredibly versatile solution. While more complex POST requests might warrant a library like Guzzle (integrated into newer PrestaShop versions), for quick calls, Tools::file_get_contents() remains exceptionally effective.

🧮 Practical Application: Adopting the Senior Developer Mindset

Let's envision a common task: developing a module that exports a product catalog to a CSV file and then transmits it to a remote server.

The "Reinvent Everything" Approach:
You could spend hours writing bespoke functions for cleaning filenames, meticulously checking memory limits, and then integrating a separate cURL library for the transmission.

The "Orchestrator" Approach (Leveraging Tools):

public function exportCatalog($name) {
    // 1. Sanitize the file name (ensure it's SEO-friendly, no problematic characters)
    $safeName = Tools::str2url($name) . '.csv';

    // 2. Proactively check if the server's memory can handle the operation
    $memoryLimit = Tools::getOctets(ini_get('memory_limit'));
    if ($memoryLimit < 128000000) { // Check if less than 128MB
        throw new Exception("Increase your memory_limit to at least 128MB!");
    }

    // 3. If a previous export temp folder exists, ensure a clean slate
    if (is_dir(_PS_TMP_IMG_DIR_ . 'export')) {
        Tools::deleteDirectory(_PS_TMP_IMG_DIR_ . 'export');
    }

    // ... your core export logic proceeds here ...
}
Enter fullscreen mode Exit fullscreen mode

This alternative code is not only more concise and easier to read but, critically, it will perform consistently and reliably across a wide array of PrestaShop hosting environments.

🌍 Vision: AI and the Art of Code Archaeology

Why discuss Tools.php in the modern development landscape of 2025?

Because the very nature of software development is undergoing a profound transformation. With advanced AI assistants like Copilot, ChatGPT, and Claude, generating code snippets has become a trivial exercise. However, the true challenge lies in generating contextually appropriate code – code that deeply understands and leverages the specific framework it operates within.

If you ask an AI, "Write me a function to delete a folder," it will likely provide a generic, often insufficient, snippet from a general programming forum. But if you instruct it, "Utilize PrestaShop's Tools::deleteDirectory," you gain immediate benefits: fewer lines of custom code and a significant reduction in potential technical debt.

The developer of tomorrow acts as an orchestrator. They possess a deep understanding of the inherent tools within their chosen framework – even those considered "legacy" – to seamlessly assemble robust solutions rather than constantly reinventing fundamental functionalities.

🎯 Conclusion

Avoid the temptation to dismiss "legacy" code. PrestaShop empowers hundreds of thousands of online stores globally, a testament to the enduring stability and effectiveness of files like Tools.php.

The next time you encounter a common utility task – whether it's manipulating a URL, cleaning a file path, or accurately identifying an IP address – make it a habit to consult this file. Open it on GitHub or in your IDE and perform a quick CTRL+F.

Embracing existing, proven code is a form of coding wisdom; it allows you to build upon the collective work of others, freeing you to concentrate on the unique, value-adding aspects of your own projects.

Happy coding to all! 🚀


If you found this exploration valuable and want to dive deeper into PrestaShop development insights, consider connecting with me! You can find more of my content and discussions here:

Top comments (0)