Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Reference Measurement Laravel Package

baks-dev/reference-measurement

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require baks-dev/reference-measurement
    

    Ensure your project uses PHP 8.4+ (check composer.json and .php-version).

  2. First Use Case: Import the package and create a measurement instance:

    use BaksDev\ReferenceMeasurement\Measurement;
    
    $length = new Measurement('10', 'm'); // 10 meters
    echo $length->getValue(); // 10
    echo $length->getUnit();  // 'm'
    
  3. Key Classes to Explore:

    • Measurement: Core class for handling values and units.
    • Unit: Enum-like class for predefined units (e.g., Unit::METER, Unit::KILOGRAM).
    • Converter: For unit conversions (e.g., meters ↔ feet).

    Where to look first:

    • src/Measurement.php (core logic).
    • src/Unit.php (supported units and validation).
    • src/Converter.php (conversion logic).

Implementation Patterns

Common Workflows

1. Creating and Validating Measurements

// Valid creation
$mass = new Measurement('5', 'kg'); // Valid (kilogram exists)

// Invalid creation (throws \InvalidArgumentException)
try {
    $invalid = new Measurement('5', 'xyz'); // 'xyz' is not a supported unit
} catch (\InvalidArgumentException $e) {
    // Handle error (e.g., log or return user-friendly message)
}

2. Unit Conversion

use BaksDev\ReferenceMeasurement\Converter;

$converter = new Converter();
$feet = $converter->convert($length, 'ft'); // Converts 10m to ~32.8084ft

3. Working with Unit Enums

use BaksDev\ReferenceMeasurement\Unit;

// Check if a unit exists
if (Unit::has('km')) {
    $distance = new Measurement('1.5', 'km');
}

// Get all length units
$lengthUnits = Unit::getLengthUnits(); // ['m', 'km', 'cm', ...]

4. Integration with Laravel Models

use Illuminate\Database\Eloquent\Model;
use BaksDev\ReferenceMeasurement\Measurement;

class Product extends Model {
    protected $casts = [
        'weight' => Measurement::class, // Casts to Measurement object
    ];

    public function setWeightAttribute($value) {
        $this->attributes['weight'] = new Measurement($value, 'kg');
    }

    public function getWeightInPoundsAttribute() {
        return (new Converter())->convert($this->weight, 'lb');
    }
}

Tip: Use Laravel’s Attribute Casting to automatically convert database values to Measurement objects.

5. Batch Processing

$measurements = [
    new Measurement('1', 'm'),
    new Measurement('2', 'km'),
];

$converted = array_map(
    fn($m) => (new Converter())->convert($m, 'ft'),
    $measurements
);

Gotchas and Tips

Pitfalls

  1. Unit Validation Strictness:

    • The package does not auto-correct typos (e.g., 'kG' or 'M'). Always validate user input:
      if (!Unit::has($userInputUnit)) {
          throw new \InvalidArgumentException("Unsupported unit: {$userInputUnit}");
      }
      
  2. Floating-Point Precision:

    • Conversions may introduce floating-point errors. Round results for display:
      $converted = $converter->convert($measurement, 'ft');
      $rounded = round($converted->getValue(), 2); // e.g., 32.81ft
      
  3. Immutable Objects:

    • Measurement objects are immutable. To "modify" them, create a new instance:
      $newMeasurement = new Measurement($measurement->getValue(), 'ft');
      
  4. Laravel Eloquent Quirks:

    • Database Storage: The package does not handle serialization to/from the database. Use Attribute Casting (as shown above) or manually serialize:
      $measurement->serialize(); // Returns string like "10|m"
      Measurement::deserialize('10|m'); // Reconstructs object
      
  5. Missing Units:

    • The package supports SI units only (e.g., no imperial gallons or custom units). Extend Unit if needed (see Extension Points).

Debugging Tips

  1. Check Supported Units:

    dd(Unit::all()); // List all supported units
    
  2. Conversion Debugging:

    • Log intermediate values to verify calculations:
      $converter = new Converter();
      $baseValue = $measurement->getValue();
      $convertedValue = $converter->convert($measurement, 'ft')->getValue();
      logger()->debug("Converted {$baseValue} {$measurement->getUnit()} to {$convertedValue} ft");
      
  3. Error Handling:

    • Wrap Measurement creation in a try-catch to handle invalid units gracefully:
      try {
          $measurement = new Measurement($value, $unit);
      } catch (\InvalidArgumentException $e) {
          return response()->json(['error' => 'Invalid unit'], 400);
      }
      

Extension Points

  1. Adding Custom Units:

    • Extend the Unit class or create a custom enum. Example:
      // In a service provider or config file
      Unit::addCustomUnit('custom', 'CustomUnit', ['base_unit' => 'm', 'conversion_factor' => 0.1]);
      
    • Note: This requires modifying the package’s source or forking it.
  2. Custom Converters:

    • Implement the ConverterInterface to add domain-specific conversions:
      class CustomConverter implements ConverterInterface {
          public function convert(Measurement $measurement, string $targetUnit): Measurement {
              // Custom logic here
          }
      }
      
  3. Laravel Service Provider:

    • Bind the package to the container for easier dependency injection:
      // In AppServiceProvider
      $this->app->bind(Measurement::class, fn() => new Measurement(...));
      $this->app->bind(Converter::class, fn() => new Converter());
      
  4. Localization:

    • Override unit names/abbreviations by publishing the package’s config (if supported in future versions) or manually patching:
      Unit::setLabel('m', 'метр'); // Russian label for meter
      

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor