Laravel Traits: Reuse Code
February 18, 2024
•
11 min read
Introduction
Traits are a mechanism for code reuse in PHP that allows you to create methods that can be used in multiple classes. Laravel uses traits extensively for functionality like soft deletes, notifications, and more.
Creating Traits
// app/Traits/HasLogger.php
namespace App\Traits;
trait HasLogger
{
protected function logInfo(string $message, array $context = [])
{
logger($message, $context);
}
protected function logError(string $message, array $context = [])
{
logger()->error($message, $context);
}
}
Using Traits
// Using trait in a class
namespace App\Services;
use App\Traits\HasLogger;
class PaymentService
{
use HasLogger;
public function processPayment($amount)
{
$this->logInfo("Processing payment", ['amount' => $amount]);
try {
// Payment logic
$this->logInfo("Payment successful");
} catch (\Exception $e) {
$this->logError("Payment failed", ['error' => $e->getMessage()]);
throw $e;
}
}
}
// Multiple traits
trait CanBeArchived
{
public function archive()
{
$this->archived = true;
$this->save();
}
}
class Order
{
use HasLogger, CanBeArchived;
}
Best Practices
- Single Responsibility - Each trait should do one thing well
- Document Well - Document trait methods and requirements
- Conflict Resolution - Use insteadof to resolve conflicts
- Trait Order - Use AS to change method visibility
- Test Thoroughly - Test traits in all classes that use them
Summary
Traits provide an excellent way to share functionality across unrelated classes. Use them judiciously to avoid tight coupling.
For more Laravel tutorials, see Service Container.