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

Iniciado por joomlamz, 28 de Maio de 2026, 20:00

Respostas: 1   |   Visualizações: 20

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Olá a todos os membros do fórum webmastersmz.com! Hoje, vamos analisar o conteúdo da edição de setembro de 2026 da revista c't Magazin für Computertechnik, uma publicação alemã renomada no campo da tecnologia da informação.

A edição em questão aborda vários tópicos relevantes para os profissionais e entusiastas de tecnologia. Um dos pontos principais é a discussão sobre as tendências atuais em segurança cibernética, destacando as ameaças emergentes e as estratégias para proteger sistemas e redes contra ataques maliciosos. Além disso, a revista apresenta uma análise detalhada sobre as últimas inovações em hardware e software, incluindo melhorias nos processadores, memórias e sistemas de armazenamento.

Outro tópico interessante abordado na revista é o futuro da inteligência artificial e como ela está sendo aplicada em diferentes setores, desde a automação industrial até a medicina personalizada. Os autores também exploram as implicações éticas e sociais do uso crescente da inteligência artificial em nosso dia a dia.

É importante notar que a revista c't Magazin für Computertechnik é conhecida por sua abordagem técnica profunda e análises detalhadas, tornando-a uma fonte valiosa de informação para aqueles que buscam entender as complexidades da tecnologia moderna.

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com. Com a AplicHost, vocês podem ter certeza de que seus sites e aplicações estão hospedados em um ambiente seguro, escalável e com suporte técnico especializado, permitindo que vocês se concentrem no que realmente importa: desenvolver e melhorar seus projetos. Então, não hesitem em explorar as opções da AplicHost e descobrir como podem ajudar a elevar seus projetos ao próximo nível!

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



Tópico: Stop Reinventing the Wheel: 5 Hidden Gems in PrestaShop's Tools.php File
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------


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




🧠 Introduction: The Modern Developer's Paradox


There's a tension I often feel when talking with developers coming from the pure Symfony universe.

On one side, the ideal: clean code, decoupled, respecting SOLID principles. On the other, the reality of e-commerce field work: a rushed client, a shared server configured oddly, and the need to move fast.

Intuition pushes us to flee PrestaShop's Tools class. It's what's called a "God Class". A monolithic file of over 4000 lines (in the develop branch) that does everything: file management, HTTP, string manipulation...

Yet today, I'm going to ask you to do something counter-intuitive: stop rewriting helpers that PrestaShop has maintained for 15 years.

I've audited the source code of the latest version for you. Here are 5 very real functions (no hallucination here) that will simplify your code and make it more robust.



⚡ Part 1 – Context: Why Dig Into This File?


In modern software architecture, a class full of static methods like Tools::myMethod() is often considered a bad practice (tight coupling).

But Tools.php is PrestaShop's immune memory. Each somewhat odd line of code, each nested if in this file is often the scar of an old bug or obscure server compatibility you haven't encountered yet.

The stakes: Do you want to spend 3 hours coding a recursive directory deletion that handles Windows and Linux permissions, or use a proven line of code?

In the age of AI and automation, the real skill is no longer knowing how to code a loop, but knowing which building block to use to build solid.



🚀 Part 2 – Analysis: 5 Native Functions (Verified)


Forget imaginary functions. Here's what's actually in the PrestaShop engine that you should use.



1. Tools::getOctets(): Speaking the Server's Language


The problem: You want to check if an uploaded file exceeds the upload_max_filesize limit from php.ini. You retrieve the value with ini_get and PHP proudly responds "128M" or "2G". If you try to compare mathematically (if $file_size > "128M"), it crashes or means nothing.

The PrestaShop solution: Don't write your own switch/case to multiply by 1024.

<span class="nv">$maxSize</span> <span class="o">=</span> <span class="nc">Tools</span><span class="o">::</span><span class="nf">getOctets</span><span class="p">(</span><span class="nb">ini_get</span><span class="p">(</span><span class="s1">'upload_max_filesize'</span><span class="p">));</span>
<span class="c1">// If the config is "128M", returns the integer: 134217728</span>

It's simple, reliable, and handles K, M, G without you having to think about it.



2. Tools::deleteDirectory(): Painless Deep Cleaning


The problem: Deleting a folder in PHP is a pain. The rmdir() function only works if the folder is empty. So you have to code a recursive function that opens the folder, lists files, deletes them one by one, goes into subdirectories... A maintenance horror.

The PrestaShop solution: PrestaShop does it natively, and even handles hidden files (except .svn and .git, handy for devs).

<span class="k">if</span> <span class="p">(</span><span class="nc">Tools</span><span class="o">::</span><span class="nf">deleteDirectory</span><span class="p">(</span><span class="nv">$myTempFolder</span><span class="p">))</span> <span class="p">{</span>
<span class="c1">// Folder and all its contents cleanly deleted.</span>
<span class="p">}</span>

This is a function I see rewritten in 50% of third-party modules. Stop. Use this one.



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


The problem: You need to generate a "slug" (simplified URL) from a product name: "Christmas & Wonders: 2025 edition!". You need to handle accents, spaces, punctuation, capitals...

The PrestaShop solution: This is the function used by the core to generate product URLs.

<span class="nv">$slug</span> <span class="o">=</span> <span class="nc">Tools</span><span class="o">::</span><span class="nf">str2url</span><span class="p">(</span><span class="s2">"Christmas & Wonders: 2025 edition!"</span><span class="p">);</span>
<span class="c1">// Result: "christmas-wonders-2025-edition"</span>

It uses iconv or mb_string depending on what's available on the server to clean exotic encodings. It's the de facto standard to stay consistent with the rest of the store.



4. Tools::getRemoteAddr(): Smarter Than $_SERVER


The problem: You want the client's IP for a security log. The reflex: $_SERVER['REMOTE_ADDR']. The trap: If the store uses Cloudflare or a Load Balancer, REMOTE_ADDR will give you Cloudflare's IP, not the client's.

The PrestaShop solution: This function is paranoid. It checks a cascade of headers (HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, etc.) to find the user's real IP.

<span class="c1">// Essential for payment or anti-fraud modules</span>
<span class="nv">$userIp</span> <span class="o">=</span> <span class="nc">Tools</span><span class="o">::</span><span class="nf">getRemoteAddr</span><span class="p">();</span>

Note: It even handles anonymization if necessary according to configuration.



5. Tools::file_get_contents(): The Network Diplomat


The problem: You need to call an external API (fetch JSON, exchange rate). You use PHP's native file_get_contents() function. The crash: On your client's shared hosting, allow_url_fopen is disabled for security. Your module crashes.

The PrestaShop solution: This method (which has the same name as the native one, hence the confusion sometimes) is an intelligent wrapper.

• It checks if cURL is available and uses it as priority (faster, more secure).

• Otherwise, it tries the native method.

• It handles timeouts and SSL contexts.

<span class="nv">$json</span> <span class="o">=</span> <span class="nc">Tools</span><span class="o">::</span><span class="nb">file_get_contents</span><span class="p">(</span><span class="s1">'https://api.my-service.com/data'</span><span class="p">);</span>

It's the 4x4 of simple HTTP requests (GET). For complex POST, we'd prefer Guzzle (integrated in recent versions), but for a quick call, Tools remains unbeatable.



🧮 Part 3 – Practical Application: The Senior Reflex


Imagine a common scenario: You're creating a module that generates a catalog export CSV file and sends it to a remote server.

"I recode everything" approach: You spend 2 hours writing a function to clean file names, another to check memory limit, and a Curl library for sending.

"Orchestrator" approach (with Tools):

<span class="k">public</span> <span class="k">function</span> <span class="n">exportCatalog</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// 1. Clean the file name (SEO friendly, no spaces)</span>
<span class="nv">$safeName</span> <span class="o">=</span> <span class="nc">Tools</span><span class="o">::</span><span class="nf">str2url</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span> <span class="mf">.</span> <span class="s1">'.csv'</span><span class="p">;</span>

<span class="c1">// 2. Check we won't blow up the server's memory</span>
<span class="nv">$memoryLimit</span> <span class="o">=</span> <span class="nc">Tools</span><span class="o">::</span><span class="nf">getOctets</span><span class="p">(</span><span class="nb">ini_get</span><span class="p">(</span><span class="s1">'memory_limit'</span><span class="p">));</span>
<span class="k">if</span> <span class="p">(</span><span class="nv">$memoryLimit</span> <span class="o"><</span> <span class="mi">128000000</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// < 128MB</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nc">Exception</span><span class="p">(</span><span class="s2">"Increase your memory_limit!"</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">// 3. If export already exists, delete previous temp folder</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">is_dir</span><span class="p">(</span><span class="n">_PS_TMP_IMG_DIR_</span> <span class="mf">.</span> <span class="s1">'export'</span><span class="p">))</span> <span class="p">{</span>
<span class="nc">Tools</span><span class="o">::</span><span class="nf">deleteDirectory</span><span class="p">(</span><span class="n">_PS_TMP_IMG_DIR_</span> <span class="mf">.</span> <span class="s1">'export'</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">// ... export logic ...</span>
<span class="p">}</span>

This code is shorter, more readable, and above all, will behave predictably on any PrestaShop hosting.



🌍 Part 4 – Vision: AI and Code Archaeology


Why am I talking about Tools.php in 2025?

Because the developer's job is changing. With the arrival of AI assistants (Copilot, ChatGPT, Claude), generating code has become trivial. But generating context-appropriate code is rare.

If you ask an AI "Make me a function to delete a folder", it will give you a generic snippet from StackOverflow. If you tell it "Use PrestaShop's Tools::deleteDirectory", you save lines of code and technical debt.

The developer of the future is an orchestrator. They know the tools available in the framework (even old "legacy" tools) to assemble robust solutions without reinventing the wheel.



🎯 Conclusion


Don't be snobbish with "Legacy" code. PrestaShop runs on hundreds of thousands of stores thanks to the resilience of files like Tools.php.

Next time you have a utility task to do (manipulate a URL, clean a file, check an IP), have the reflex to open this file on GitHub or in your IDE. Do a CTRL+F.

Kindness in code means building on others' work to focus on your project's added value.

Happy coding to all! 🚀


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: