Posted on: June 05, 2025 07:50 PM
Posted by: Renato
Categories: Laravel
Views: 324
𝕌𝕤𝕚𝕟𝕘 𝕋𝕣𝕒𝕚𝕥𝕤 𝕚𝕟 ℍ𝕖𝕝𝕡𝕖𝕣𝕤 𝔼𝕗𝕗𝕚𝕔𝕚𝕖𝕟𝕥𝕝𝕪
Você já precisou de formatação numérica reutilizável ou operações
matemáticas personalizadas no Laravel?
Quer combinar o poder de Traits e Helpers para melhor reutilização de código?
Esta é uma maneira limpa e eficiente de usar Traits em funções auxiliares do Laravel!
➤ Etapa 1: Crie uma característica para formatação de números
➤ Etapa 2: Crie uma classe auxiliar que use o traço
➤ Etapa 3: Criar uma função auxiliar Singleton
➤ Etapa 4: Definir funções auxiliares globais Vantagens desta abordagem:
➤ Lógica encapsulada: mantém a formatação numérica e as operações em uma característica reutilizável.
➤ Padrão Singleton: garante que o BcMath seja inicializado apenas uma vez.
➤ Funções do Global Helper: fáceis de usar em qualquer lugar do aplicativo Laravel.
𝗔𝗿𝗲 𝘆𝗼𝘂 𝘂𝘀𝗶𝗻𝗴 𝗧𝗿𝗮𝗶𝘁𝘀 𝗶𝗻 𝘆𝗼𝘂𝗿 𝗛𝗲𝗹𝗽𝗲𝗿𝘀 ? 𝗟𝗲𝘁 𝗺𝗲 𝗸𝗻𝗼𝘄 𝗶𝗻 𝘁𝗵𝗲 𝗰𝗼𝗺𝗺𝗲𝗻𝘁𝘀 !
// 🍓 Step 1:
namespace App\Traits;
trait NumberFormatTrait
{
public function truncateNum($num, int $scale = 8)
{
return bcadd($num, '0', $scale); // Ensures proper decimal precision
}
}
// 🍓 Step 2:
use App\Traits\NumberFormatTrait;
class BcMath
{
use NumberFormatTrait;
function bcOperation(string $operation, $num1, $num2, int $scale = 8)
{
$num1 = $this->truncateNum($num1, $scale);
$num2 = $this->truncateNum($num2, $scale);
return $operation($num1, $num2, $scale);
}
}
// 🍓 Step 3:
function getBcMathInstance(): BcMath
{
static $bcMath = null;
if ($bcMath === null) {
$bcMath = new BcMath();
}
return $bcMath;
}
// 🍓 Step 4:
function bcaddx($num1, $num2, int $scale = 8)
{
return getBcMathInstance()->bcOperation('bcadd', $num1, $num2, $scale);
}
function bcsubx($num1, $num2, int $scale = 8)
{
return getBcMathInstance()->bcOperation('bcsub', $num1, $num2, $scale);
}
echo bcaddx(1.123456789, 2.987654321); // Output: "4.11111111"
echo bcsubx(10, 3.5); // Output: "6.50000000"
Fonte: https://x.com/SabowaRyan/status/1930530327052595595
In Laravel (and generally in PHP), traits offer a mechanism to reuse code effectively across multiple classes, enhancing efficiency and code organization, while helpers are collections of functions for common tasks, providing a convenient way to simplify development without requiring object instantiation. Traits are typically used for shared functionality, while helpers are for general-purpose functions.
Elaboration:
Traits:
-
Code Reusability:
Traits allow you to include specific functionalities (methods, properties) into multiple classes without extending them or using inheritance. This reduces code duplication and promotes consistency.
-
Organization:
Traits help organize your codebase by grouping related functionalities, making it easier to maintain and read.
-
Flexibility:
Traits can be included in any class, offering flexibility in sharing common methods and enhancing development efficiency.
-
Example:
A trait could handle logging or authentication logic that is needed by several classes.
Helpers:
-
Convenient Functions:
Laravel helpers are pre-defined functions (or user-defined functions in custom helper files) that provide common utility functions.
-
Global Availability:
Helpers are globally available and can be used anywhere in your application without object instantiation.
-
Simplified Development:
They streamline the development process by providing shortcuts for frequently used tasks like formatting dates, working with numbers, or generating HTML.
-
Example:
str_slug(),url(),dd()(debug data) are examples of Laravel helpers.
When to use which:
-
Traits:
Use traits when you need to share functionality across multiple classes, particularly when dealing with complex or specific behaviors that are not easily implemented as global functions.
-
Helpers:
Use helpers for general-purpose tasks that don't require a class context and are used globally throughout your application.
In essence: Traits are used for code reusability and organization, while helpers are used for simplifying common tasks and providing global utility functions. They are different tools that serve different purposes in the overall development process.
Donate to Site
Renato
Developer
-
Renato Lucena - há 11 meses
=> https://x.com/SabowaRyan/status/1930530327052595595