Skip to content

Instantly share code, notes, and snippets.

@PurpleBooth
Created April 12, 2019 14:51
Show Gist options
  • Save PurpleBooth/9053c9080654256363eed1480c0a7376 to your computer and use it in GitHub Desktop.
Save PurpleBooth/9053c9080654256363eed1480c0a7376 to your computer and use it in GitHub Desktop.
<?php
namespace Armakuni\Demo\PhpCounter;
use Google\Cloud\Datastore\DatastoreClient;
class CounterService
{
private $datastore;
/**
* CounterService constructor.
* @param DatastoreClient $datastore
*/
public function __construct(DatastoreClient $datastore)
{
$this->datastore = $datastore;
}
/**
* @return int
*/
public function incrementCounter(): int
{
$this->addOne();
return $this->getCount();
}
private function addOne(): void
{
$counterKey = $this->datastore->key('Counter');
$counterKey = $this->datastore->allocateId($counterKey);
$counter = $this->datastore->entity($counterKey, []);
$this->datastore->upsert($counter);
}
/**
* @return int
*/
private function getCount(): int
{
$query = $this->datastore->query()
->keysOnly();
$results = $this->datastore->runQuery($query);
return iterator_count($results);
}
}
<?php
$count = Tracer::inSpan(
['name' => 'count'],
function () use ($datastore) {
return (new CounterService($datastore))->incrementCounter();
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment