spatie/weight-conversions
Lightweight PHP package for converting between common weight units (e.g., grams, kilograms, pounds, ounces). Handy for apps needing consistent unit handling in calculations, forms, and APIs, with a simple, dependency-free API.
The spatie/weight-conversions package is a lightweight, utility-focused library designed for simple, isolated weight unit conversions (e.g., kg ↔️ lbs, grams ↔️ ounces). It aligns well with Laravel’s modular architecture, as it:
Misalignment Risks:
composer require spatie/weight-conversions.Key Dependencies:
ServiceProvider or Facade required).| Risk Area | Assessment |
|---|---|
| Stability | Last release in 2021 (3+ years stale). No active maintenance signals. |
| Functional Scope | Limited to basic conversions; lacks extensibility (e.g., no hooks for custom units). |
| Performance | Minimal overhead (pure PHP calculations); negligible impact on scaling. |
| Security | MIT license + no known vulnerabilities. Safe for internal use. |
Mitigation:
composer vendor:publish)?POST /orders accepts lbs, stores kg).{{ $product->weight->inKilograms() }}).composer require spatie/weight-conversions
use Spatie\WeightConversions\Weight;
$weight = Weight::fromKilograms(1.5);
echo $weight->inPounds(); // Output: ~3.3069
WeightConversionService to abstract usage.
namespace App\Services;
use Spatie\WeightConversions\Weight;
class WeightConversionService {
public function convertToKg(float $value, string $fromUnit): float {
return Weight::from($fromUnit, $value)->inKilograms();
}
}
class Product extends Model {
public function getWeightInLbsAttribute(): float {
return Weight::fromKilograms($this->weight)->inPounds();
}
}
Feature\WeightConversionsTest.Weight::fromPounds(0)).| Component | Compatibility Notes |
|---|---|
| PHP Version | Requires PHP ≥8.0 (check Laravel project’s PHP version). |
| Laravel Version | No Laravel-specific code; works with Laravel 8+ (tested via CI). |
| Database | No schema changes; conversions are runtime logic. |
| Third-Party | None; pure PHP dependency. |
OrderService).App\Services\WeightService).spatie:weight Artisan commands).Recommendation:
composer vendor:publish) to avoid dependency bloat."abc").inPounds() may return floating-point quirks).Weight objects in a static map).| Scenario | Impact | Mitigation |
|---|---|---|
| Invalid Input | Silent failures (e.g., NaN). |
Add input validation (e.g., is_numeric()). |
| PHP Version Mismatch | Runtime errors. | Pin PHP version in composer.json. |
| Forked Package Drift | Inconsistent behavior. | Use composer.lock to freeze dependencies. |
| Business Logic Errors | Wrong conversions in production. | Unit test all critical paths. |
phpdoc or write a README.md snippet.Usage.md with Laravel-specific patterns (e.g., model accessors).Recommendation:
docs/ folder:
## Weight Conversions
Convert between units in Laravel services:
```php
// app/Services/WeightService.php
How can I help you explore Laravel packages today?