Skip to content

About

Track users between visits in Symfony

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Client Bundle

Latest Version Software License Build Status Code Coverage

Recognize returning visitors in your Symfony application and attach your own metadata to each of them.

The bundle assigns every visitor a stable client id, stored in a first‑party cookie (setono_client_id by default) that also remembers when the visitor was first and last seen. On top of that you can persist arbitrary metadata per client — for example the first Google click id (gclid) a visitor arrived with, an A/B test variant, or a referrer. Metadata is lazy: if you never read or write it, the bundle never touches the database.

Typical use cases: first‑party analytics, marketing attribution, returning‑visitor personalization.

Contents

Requirements

Version
PHP >= 8.1
Symfony ^6.4 or ^7.0
Doctrine ORM ^2.17 or ^3.0
Doctrine DBAL ^3.7 or ^4.0
DoctrineBundle ^2.11.3

Installation

composer require setono/client-bundle

If you use Symfony Flex the bundle is registered automatically. Otherwise, enable it manually in config/bundles.php:

return [
    // ...
    Setono\ClientBundle\SetonoClientBundle::class => ['all' => true],
];

The bundle stores metadata in the table setono_client__metadata (columns client_id and metadata) on your default Doctrine connection, and a postGenerateSchema listener adds that table to the schema Doctrine generates. If you intend to store metadata, create the table with Doctrine Migrations:

php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate

If you only need the client id cookie and never store metadata, the table is never queried — but generating it now keeps things simple if you add metadata later.

Usage

Get the current client

The simplest way to access the current visitor is to type‑hint Setono\Client\Client in a controller — the bundle resolves it for you:

use Setono\Client\Client;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

final class HomeController extends AbstractController
{
    public function index(Client $client): Response
    {
        return $this->render('home.html.twig', [
            'clientId' => $client->id,
        ]);
    }
}

Anywhere else (services, subscribers) inject ClientContextInterface:

use Setono\ClientBundle\Context\ClientContextInterface;

final class SomeService
{
    public function __construct(private readonly ClientContextInterface $clientContext)
    {
    }

    public function __invoke(): void
    {
        $client = $this->clientContext->getClient();
        // $client->id, $client->metadata
    }
}

A request gets one client, however often you ask for it, also in kernel.terminate listeners that run after the response is sent. Outside a request (console commands, workers) there is no visitor to recognize, so every call returns an anonymous client of its own, which is never stored.

Read and write metadata

$client->metadata is a key/value store. Using it for the first time lazily loads the metadata from the database. At the end of the request it is stored, but only if it changed: a key was set to a new value or expiry, removed, or dropped because it expired. Setting a key to the value and expiry it already has is not a change.

$metadata = $client->metadata;

$metadata->set('variant', 'B');           // store a value
$metadata->set('promo', 'X', ttl: 3600);  // optional TTL in seconds; without one, the key never expires

$metadata->has('variant');                // true
$metadata->get('variant');                // 'B' — throws if the key is missing, so guard with has()
$metadata->remove('variant');

foreach ($metadata as $key => $value) {   // iterate everything
    // ...
}

Set metadata from a request

A common pattern is to capture data from the incoming request — here, the Google click id:

use Setono\ClientBundle\Context\ClientContextInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class GoogleClickIdSubscriber implements EventSubscriberInterface
{
    public function __construct(private readonly ClientContextInterface $clientContext)
    {
    }

    public static function getSubscribedEvents(): array
    {
        return [KernelEvents::REQUEST => 'capture'];
    }

    public function capture(RequestEvent $event): void
    {
        if (!$event->isMainRequest() || !$event->getRequest()->query->has('gclid')) {
            return;
        }

        $this->clientContext->getClient()->metadata->set(
            'google_click_id',
            $event->getRequest()->query->get('gclid'),
        );
    }
}

Read the cookie in JavaScript

The cookie is intentionally not HttpOnly, so you can read it from JavaScript (e.g. to send the client id to a third‑party tag). Its value is a Setono\Client\Cookie from setono/client as a string; that class defines the format.

Skip storing the cookie (consent)

Because the cookie identifies a visitor, you may need consent before storing it. Listen to PreStoreCookieEvent (dispatched on the response, before the cookie is written) and set $event->store = false to skip it for that request. If the current client is a new client, i.e. its client id was made up for this request, as for a visitor without a valid cookie, the bundle doesn't store its metadata either, because no later request could recognize it. The metadata of other clients is still stored:

use Setono\ClientBundle\Event\PreStoreCookieEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class CookieConsentSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [PreStoreCookieEvent::class => 'onPreStore'];
    }

    public function onPreStore(PreStoreCookieEvent $event): void
    {
        if (!$this->hasConsent($event->request)) {
            $event->store = false;
        }
    }

    // ...
}

Configuration

All options are optional; the defaults are shown below:

setono_client:
    cookie:
        # Name of the cookie that holds the client id.
        # NOTE: changing this makes every visitor with the old cookie name look like a new client.
        name: setono_client_id

        # Cookie lifetime, expressed as any string strtotime() can parse.
        expiration: '+365 days'

How it works

  • Current client — CookieBasedClientContext recognizes the client by the cookie of the main request. A request without a valid cookie gets a new client, with a new client id. CachedClientContext wraps the client context, including your decorators, and gives each request one client, until its kernel.terminate listeners are done.
  • Cookie — on each main response, StoreClientSubscriber writes the cookie of the current client and bumps lastSeenAt. The cookie always holds the client id of the current client: when that differs from the id in the request's cookie (e.g. because a decorator chose another client), the cookie gets the new id and fresh timestamps.
  • Lazy metadata — the metadata store (MetadataStoreInterface) loads $client->metadata lazily, with Metadata::lazy() from setono/client. The database is queried only the first time you use it, and a client without a stored row gets empty metadata. StoreClientSubscriber stores it on the main response, right after the cookie, and the store writes the row only if the metadata changed (Metadata::hasChanged(), which doesn't load it).
  • Storage — the store reads and writes its table with DBAL, not with an entity manager, so it never flushes changes your application didn't flush, and your Doctrine listeners don't see its writes.

Extending the bundle

Every moving part is a service behind an interface, so you can swap or decorate it:

Concern Interface
Resolving the current client Setono\ClientBundle\Context\ClientContextInterface
Loading and storing metadata Setono\ClientBundle\MetadataStore\MetadataStoreInterface

To add behaviour, decorate the relevant service rather than replacing it outright — that is exactly how the bundle composes its own defaults.

To change which client a request gets, e.g. to recognize a logged‑in user's client on another device, decorate ClientContextInterface:

use Setono\Client\Client;
use Setono\ClientBundle\Context\ClientContextInterface;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;

#[AsDecorator(ClientContextInterface::class)]
final class UserClientContext implements ClientContextInterface
{
    public function __construct(#[AutowireDecorated] private readonly ClientContextInterface $decorated)
    {
    }

    public function getClient(): Client
    {
        // return another client, or the decorated one
        return $this->decorated->getClient();
    }
}

The bundle's CachedClientContext decorates the interface with the lowest priority (-1024), so it wraps your decorator and a request gets one client however often it's asked for, even if your decorator creates a client on every call. The cookie then stores the client id of your client. It must be a non‑empty UTF-8 string of at most 255 bytes.

If your decorator makes up client ids that no later request could recognize without the cookie, e.g. random ones, extend AbstractClientContext and create those clients with newClient(), like the bundle does for a visitor without a cookie. When the cookie isn't stored, the bundle then doesn't store their metadata either:

use Setono\Client\Client;
use Setono\ClientBundle\Context\AbstractClientContext;
use Setono\ClientBundle\Context\ClientContextInterface;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;
use Symfony\Component\HttpFoundation\RequestStack;

#[AsDecorator(ClientContextInterface::class)]
final class BotClientContext extends AbstractClientContext
{
    public function __construct(
        #[AutowireDecorated] private readonly ClientContextInterface $decorated,
        private readonly RequestStack $requestStack,
    ) {
    }

    public function getClient(): Client
    {
        $request = $this->requestStack->getMainRequest();
        if (null === $request || !$this->isBot($request)) {
            return $this->decorated->getClient();
        }

        // Without a client, newClient() creates one with a generated client id
        return $this->newClient($request, new Client('bot-' . bin2hex(random_bytes(16))));
    }

    // ...
}

A client id that a later request can recognize, e.g. one derived from the logged-in user, isn't a new client's: return that client as it is, and its metadata is stored even when the cookie isn't.

Inject ClientContextInterface, not CookieBasedClientContext: it skips CachedClientContext, so a request without a client cookie would get a new client on every call. Don't decorate CachedClientContext itself. It also listens to kernel.terminate, and Symfony would move that listener to your decorator.

Likewise, inject MetadataStoreInterface, not DoctrineDbalBasedMetadataStore: it skips your decorators of MetadataStoreInterface.

Contributing

git clone https://github.com/Setono/client-bundle.git
cd client-bundle
composer install

Quality tooling (also run in CI):

Command Purpose
composer phpunit Run the test suite
composer analyse Static analysis (PHPStan, level: max)
composer check-style / composer fix-style Coding standard (ECS)
composer infection Mutation testing (requires a coverage driver)
vendor/bin/composer-dependency-analyser Detect unused/undeclared dependencies

License

This bundle is released under the MIT License.

About

Track users between visits in Symfony

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages