calculators.rst 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. .. _customize.calculators:
  2. =========================
  3. Using a Custom Calculator
  4. =========================
  5. By default, ramsey/uuid uses `brick/math`_ as its internal calculator. However,
  6. you may change the calculator, if your needs require something else.
  7. To swap the default calculator with your custom one, first make an adapter that
  8. wraps your custom calculator and implements
  9. :php:interface:`Ramsey\\Uuid\\Math\\CalculatorInterface`. This might look
  10. something like this:
  11. .. code-block:: php
  12. :caption: Create a custom calculator wrapper that implements CalculatorInterface
  13. :name: customize.calculators.wrapper-example
  14. namespace MyProject;
  15. use Other\OtherCalculator;
  16. use Ramsey\Uuid\Math\CalculatorInterface;
  17. use Ramsey\Uuid\Type\Integer as IntegerObject;
  18. use Ramsey\Uuid\Type\NumberInterface;
  19. class MyUuidCalculator implements CalculatorInterface
  20. {
  21. private $internalCalculator;
  22. public function __construct(OtherCalculator $customCalculator)
  23. {
  24. $this->internalCalculator = $customCalculator;
  25. }
  26. public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface
  27. {
  28. $value = $augend->toString();
  29. foreach ($addends as $addend) {
  30. $value = $this->internalCalculator->plus($value, $addend->toString());
  31. }
  32. return new IntegerObject($value);
  33. }
  34. /* ... Class truncated for brevity ... */
  35. }
  36. The easiest way to use your custom calculator wrapper is to instantiate a new
  37. FeatureSet, set the calculator on it, and pass the FeatureSet into a new
  38. UuidFactory. Using the factory, you may then generate and work with UUIDs, using
  39. your custom calculator.
  40. .. code-block:: php
  41. :caption: Use your custom calculator wrapper when working with UUIDs
  42. :name: customize.calculators.use-wrapper-example
  43. use MyProject\MyUuidCalculator;
  44. use Other\OtherCalculator;
  45. use Ramsey\Uuid\FeatureSet;
  46. use Ramsey\Uuid\UuidFactory;
  47. $otherCalculator = new OtherCalculator();
  48. $myUuidCalculator = new MyUuidCalculator($otherCalculator);
  49. $featureSet = new FeatureSet();
  50. $featureSet->setCalculator($myUuidCalculator);
  51. $factory = new UuidFactory($featureSet);
  52. $uuid = $factory->uuid1();
  53. .. _brick/math: https://github.com/brick/math