Query evaluation

Learn how to evaluate queries in real-time.

This guide provides practical examples of using the Drupal SDK to evaluate CQL queries from your site.

Basic usage

Inject the Plug service into a block, controller, or service, then call evaluate to run CQL queries in real-time. This method returns the result of the evaluation.

For example, here is a block that greets returning visitors by evaluating the user is returning query:

web/modules/custom/my_module/src/Plugin/Block/GreetingBlock.php
1234567891011121314151617181920212223242526272829303132333435363738394041424344
<?php
declare(strict_types=1);
namespace Drupal\my_module\Plugin\Block;
use Croct\Plug\Plug;use Drupal\Core\Block\Attribute\Block;use Drupal\Core\Block\BlockBase;use Drupal\Core\Plugin\ContainerFactoryPluginInterface;use Drupal\Core\StringTranslation\TranslatableMarkup;use Symfony\Component\DependencyInjection\ContainerInterface;
#[Block(    id: 'greeting',    admin_label: new TranslatableMarkup('Visitor greeting'),)]final class GreetingBlock extends BlockBase implements ContainerFactoryPluginInterface{    private Plug $croct;
    public function __construct(array $configuration, string $pluginId, mixed $pluginDefinition, Plug $croct)    {        parent::__construct($configuration, $pluginId, $pluginDefinition);
        $this->croct = $croct;    }
    public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition): self    {        return new self($configuration, $pluginId, $pluginDefinition, $container->get(Plug::class));    }
    public function build(): array    {        $returning = $this->croct->evaluate('user is returning') === true;
        return [            '#markup' => $returning ? $this->t('Welcome back!') : $this->t('Welcome to Croct!'),            // Personalized per visitor, so vary the render cache by session.            '#cache' => ['contexts' => ['session']],        ];    }}

The result of the evaluation is not restricted to boolean values. For example, you can use the following query to find out the location from which the user is accessing your site:

$location = $croct->evaluate('location');

In this case, the result of the evaluation is a geographic location:

Query result
12345678910111213
{  "continent": "North America",  "continentCode": "NA",  "country": "United States",  "countryCode": "US",  "region": "New York",  "regionCode": "NY",  "state": "New York",  "stateCode": "NY",  "city": "Denver",  "district": null,  "timeZone": null}

Fault tolerance

We recommend always handling errors when evaluating queries to protect your site from unexpected errors, downtime, and network failures.

Pass a fallback, and the SDK returns it whenever the query cannot be evaluated:

use Croct\Plug\EvaluationOptions;
$options = EvaluationOptions::defaults()->withFallback(false);$returning = $croct->evaluate('user is returning', $options);

In this example, the $returning variable is set to false if the evaluation fails, ensuring that the site continues to work as expected. Without a fallback, a failed evaluation throws an exception, which you can catch to handle the error yourself.

Context variables

In some cases, you may want to pass additional information that can be used by the query in the evaluation process.

For example, let’s say you want to check whether the user is accessing your site from one of a list of countries. The SDK allows you to pass this information as an attribute to the query:

use Croct\Plug\EvaluationOptions;
$options = EvaluationOptions::defaults()->withAttribute('countries', ['United States', 'Canada', 'Mexico']);$result = $croct->evaluate("context's countries include location's countryName", $options);

Any attribute you pass will be available in the query as the context variable.