Skip to content

Commit

Permalink
Add settings for cache duration
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelreichor committed Dec 30, 2024
1 parent a66236f commit 7b73f09
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@

- Add support for search query.
- Add `EVENT_REGISTER_ELEMENT_TYPES` for defining custom element types.
- Add settings for cache duration.
- Change file and class name of `FieldTransformerEvent` to `RegisterFieldTransformersEvent`.
7 changes: 7 additions & 0 deletions src/QueryApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use craft\base\Plugin;
use craft\events\RegisterUrlRulesEvent;
use craft\web\UrlManager;
use craft\base\Model;
use samuelreichoer\queryapi\models\Settings;
use yii\base\Event;
use yii\log\FileTarget;

Expand Down Expand Up @@ -51,6 +53,11 @@ function(RegisterUrlRulesEvent $event) {
);
}

protected function createSettingsModel(): ?Model
{
return new Settings();
}

private function initLogger(): void
{
$logFileTarget = new FileTarget([
Expand Down
5 changes: 5 additions & 0 deletions src/config/craft-query-api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php
/*
return [
'cacheDuration' => 69420,
];*/
10 changes: 10 additions & 0 deletions src/models/Settings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace samuelreichoer\queryapi\models;

use craft\base\Model;

class Settings extends Model
{
public ?int $cacheDuration = null;
}
6 changes: 5 additions & 1 deletion src/services/ElementQueryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Exception;
use samuelreichoer\queryapi\events\RegisterElementTypesEvent;
use samuelreichoer\queryapi\helpers\Utils;
use samuelreichoer\queryapi\QueryApi;

class ElementQueryService extends Component
{
Expand Down Expand Up @@ -51,8 +52,11 @@ public function __construct()
*/
public function executeQuery(string $elementType, array $params): array
{
// Get cache duration
$craftDuration = Craft::$app->getConfig()->getGeneral()->cacheDuration;
$duration = App::env('CRAFT_ENVIRONMENT') === 'dev' ? 0 : $craftDuration;
$configDuration = QueryApi::getInstance()->getSettings()->cacheDuration;

Check failure on line 57 in src/services/ElementQueryService.php

View workflow job for this annotation

GitHub Actions / PHPStan

Access to an undefined property craft\base\Model::$cacheDuration.
$duration = $configDuration ?? $craftDuration;

$hashedParamsKey = Utils::generateCacheKey($params);
$cacheKey = 'queryapi_' . $elementType . '_' . $hashedParamsKey;

Expand Down

0 comments on commit 7b73f09

Please sign in to comment.