Skip to content

Commit 57d0901

Browse files
committed
Add documentation for custom metric models
1 parent ac97f21 commit 57d0901

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

README.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ Track page views, API calls, user signups, or any other countable events.
3737
- [Querying Metrics](#querying-metrics)
3838
- [Testing](#testing)
3939
- [Extending & Customizing](#extending--customizing)
40+
- [Custom Metric Models](#custom-metric-models)
41+
- [Custom Metric Repository](#custom-metric-repository)
42+
- [Custom Metric Manager](#custom-metric-manager)
4043

4144
## Requirements
4245

@@ -622,6 +625,73 @@ $userEndpoint = Metrics::recorded(fn ($metric) =>
622625

623626
## Extending & Customizing
624627

628+
### Custom Metric Models
629+
630+
By default, metrics are stored using the included `DirectoryTree\Metrics\Metric` model. You may use a custom model globally or per-metric.
631+
632+
#### Global Custom Model
633+
634+
To use a custom metric model for all metrics, you may create your own model instance with the below requirements:
635+
636+
1. Be fully unguarded (so the model can `fill`'ed appropriately)
637+
2. Include the same columns as the default `metrics` table
638+
3. Include the same casts as the default `Metric` model
639+
640+
```php
641+
namespace App\Models;
642+
643+
use Illuminate\Database\Eloquent\Model;
644+
645+
class CustomMetric extends Model
646+
{
647+
protected $guarded = [];
648+
649+
protected function casts(): array
650+
{
651+
return [
652+
'year' => 'integer',
653+
'month' => 'integer',
654+
'day' => 'integer',
655+
'hour' => 'integer',
656+
'value' => 'integer',
657+
];
658+
}
659+
}
660+
```
661+
662+
Once you have created your custom model, you may set it as the default using the `useModel()` method on the `DatabaseMetricManager`:
663+
664+
```php
665+
use App\Models\CustomMetric;
666+
use DirectoryTree\Metrics\DatabaseMetricManager;
667+
668+
// In your AppServiceProvider boot method
669+
DatabaseMetricManager::useModel(CustomMetric::class);
670+
```
671+
672+
#### Per-Metric Custom Model
673+
674+
To use different metric models for different metrics, use the `model()` method on `PendingMetric`:
675+
676+
```php
677+
use App\Models\ApiMetric;
678+
use App\Models\UserMetric;
679+
680+
// Store API metrics in a separate table
681+
metric('requests')
682+
->model(ApiMetric::class)
683+
->record();
684+
685+
// Store user metrics in another table
686+
metric('user:logins')
687+
->model(UserMetric::class)
688+
->with(['user_id' => Auth::id()])
689+
->record();
690+
691+
// Use the default model
692+
metric('page:views')->record();
693+
```
694+
625695
### Custom Metric Manager
626696

627697
Create your own metric manager by implementing the `MetricManager` interface:

0 commit comments

Comments
 (0)