Skip to content

Instantly share code, notes, and snippets.

@jacksleight
Last active December 16, 2022 11:29
Show Gist options
  • Save jacksleight/37740ac27d3dd4b13d0a2150b2311e6b to your computer and use it in GitHub Desktop.
Save jacksleight/37740ac27d3dd4b13d0a2150b2311e6b to your computer and use it in GitHub Desktop.
Statamic Computed Value Classes
<?php
Statamic::booted(function () {
foreach (app()['files']->files(app_path('Values')) as $file) {
$class = $file->getBasename('.php');
$fqcn = $this->app->getNamespace()."Values\\{$class}";
if (is_subclass_of($fqcn, Values::class)) {
$object = app($fqcn);
$collections = $fqcn::$collections;
$fields = Arr::except(get_class_methods($object), '__construct');
foreach ($collections as $collection) {
foreach ($fields as $field) {
Collection::computed(
$collection,
$field,
fn ($entry, $value) => $object->$field($entry, $value)
);
}
}
}
}
});
<?php
namespace App\Values;
class ExampleValues extends Values
{
public static $collections = ['pages', 'articles'];
// $entry->example
public function example($entry, $value)
{
// do something and return
}
}
<?php
namespace App\Values;
abstract class Values
{
public static $collections = [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment