Create or Modify Counters


  • Use the countersFor.increment method to create a new Counter or modify an existing Counter's value.

  • If the Counter exists, increment will add the specified number to the Counter's current value.
    If the Counter doesn't exist, increment will create it and set its initial value.

  • For all other countersFor methods see this Overview.

  • In this page:


increment usage

Flow:

  • Open a session.
  • Create an instance of countersFor.
  • Call countersFor.increment.
  • Call session.saveChanges for the changes to take effect.

Note:

  • Modifying a Counter using increment only takes effect when session.aaveChanges() is executed.
  • To decrease a Counter's value, pass the method a negative number to the increment method.

Example

// Open a session
$session = $docStore->openSession();
try {
    // Pass the countersFor constructor a document ID
    $documentCounters = $session->countersFor("products/1-A");

    // Use `countersFor.increment`:
    // ============================

    // Increase "ProductLikes" by 1, or create it if doesn't exist with a value of 1
    $documentCounters->increment("ProductLikes");

    // Increase "ProductPageViews" by 15, or create it if doesn't exist with a value of 15
    $documentCounters->increment("ProductPageViews", 15);

    // Decrease "DaysLeftForSale" by 10, or create it if doesn't exist with a value of -10
    $documentCounters->increment("DaysLeftForSale", -10);

    // Execute all changes by calling SaveChanges
    $session->saveChanges();
} finally {
    $session->close();
}

Syntax

public function countersFor(string|object $idOrEntity): SessionDocumentCountersInterface;
Parameter Type Description
idOrEntity string or object The object to create or modify counters for

public function increment(?string $counter, int $delta = 1): void;
Parameter Type Description
counter string Counter name
delta int Increase Counter by this value.
Default value is 1.
For a new Counter, this number will be its initial value.