Resources#

A resource makes a kinetis/orm entity administrable. It is a class extending Kinetis\Vector\VectorResource with a #[Resource] attribute, discovered anywhere under your application namespace.

use Kinetis\Vector\Attributes\Resource;
use Kinetis\Vector\Fields\{BelongsTo, Boolean, Id, ManyToMany, Money, Number, Select, Text};
use Kinetis\Vector\VectorResource;

#[Resource(entity: Product::class, group: 'Catalog', icon: 'mdi-package-variant', title: 'name')]
final class ProductResource extends VectorResource
{
    public function fields(): array
    {
        return [
            Id::make(),
            Text::make('sku', 'SKU')->required()->max(40)->sortable()->searchable()->filterable(),
            Text::make('name')->required()->max(200)->sortable()->searchable()->filterable(),
            Select::make('status')->of(ProductStatus::class)->badge(['active' => 'success'])->sortable()->filterable(),
            Select::make('channels')->options(['web' => 'Web shop', 'retail' => 'Retail'])->multiple()->filterable(),
            BelongsTo::to('category', CategoryResource::class)->sortable()->filterable(),
            Money::make('priceCents', 'Price')->currencyField('currency')->summarize('avg'),
            Number::make('stock')->sortable()->filterable()->summarize('sum'),
            Boolean::make('isFeatured', 'Featured')->filterable(),
            ManyToMany::to('tags', TagResource::class),
        ];
    }

    public function defaultSort(): array { return ['-createdAt']; }
    public function softDeletes(): string { return 'deletedAt'; }
    public function actions(): array { return [PublishProducts::class]; }
    public function widgets(): array { return [ProductsByStatus::class]; }
}

#[Resource] names the entity, the menu group, an icon (a Material Design Icons name) and the title field that names a record in breadcrumbs, relations and search. slug overrides the URL name; by default the mapped table name is used with underscores replaced by dashes. label and labelSingular override the display names derived from the class. meta is a free-form metadata bag (Metadata for other packages).

Metadata for other packages#

#[Resource(meta: [...])] and Field::meta($key, $value) attach namespaced metadata (vendor.key) that Vector publishes verbatim, as meta on the resource and on the field, in the descriptor (GET /vector/schema) and in toArray(). Vector itself never reads it; it is there for a package or a UI extension that builds on the descriptor. A value is a scalar, null or a list of those; anything else stops the compile.

#[Resource(entity: Customer::class, meta: ['ai.send' => false])]
final class CustomerResource extends VectorResource
{
    public function fields(): array
    {
        return [
            Id::make(),
            Text::make('name'),
            Email::make('email')->meta('ai.send', false),
        ];
    }
}

A resource or field that declares no meta publishes no meta key at all, in the descriptor or in vector_describe’s answer. A policy that hides fields keeps the meta of the fields it keeps. kinetis/vector-ai reads ai.send (Data and access).

Shell contributors#

A package that builds on Vector tells the admin, per user, what it offers through capabilities in GET /vector/schema. A class implementing Kinetis\Vector\Http\ShellContributorInterface and carrying #[ShellContributor(name: '...')] is discovered like a settings group; on every schema request it is resolved from the request scope (so it may depend on request-scoped services) and its answer is published as capabilities.<name>:

use Kinetis\Http\CurrentUserInterface;
use Kinetis\Vector\Attributes\ShellContributor;
use Kinetis\Vector\Http\ShellContributorInterface;

#[ShellContributor(name: 'acme')]
final readonly class AcmeCapabilities implements ShellContributorInterface
{
    public function __construct(private AcmePolicy $policy) {}

    public function capabilities(CurrentUserInterface $user): array
    {
        return ['reports' => $this->policy->canRunReports($user)];
    }
}

The name is lowercase letters, digits and dashes, starting with a letter, at most 40 characters. A name that is malformed, taken twice, or one of the built-in keys (audit, impersonation, queue, queues, failedJobs, queueMetrics, exportFormats, uploads) stops the compile. The answer is always a JSON object, and its key is absent when the package is not installed, which is how a UI extension tells (Customizing the UI). It is part of the descriptor’s ETag, must not block, and must never carry a secret: the descriptor is sent to the browser.

Several resources over one entity#

An entity may have more than one resource: a second view of the same rows with its own fields, policy, scope and actions, such as the demo’s profiles beside users. Each needs its own slug, since the default one, the table name, can only be taken once. Each is a resource in its own right: its policy, writes, audit trail, jobs, MCP tools and menu entry are keyed by its slug.

A relation that names its resource, BelongsTo::to('owner', ProfileResource::class), links to that one. A relation that names none (a field derived from the entity’s mapping) links to the entity’s relation target: its only resource, or, when it has several, the one marked relationTarget: true:

#[Resource(entity: User::class, title: 'name', relationTarget: true)]
final class UserResource extends VectorResource { /* ... */ }

#[Resource(entity: User::class, slug: 'profiles', title: 'name')]
final class ProfileResource extends VectorResource { /* ... */ }

Compilation fails when an entity with several resources marks none of them, or more than one, naming the entity and every resource over it. An entity with a single resource needs no mark.

A resource’s hooks and policy govern its own requests only. The demo’s UserResource refuses to delete the last admin in beforeDelete(), which a delete through profiles would not run, so profiles refuses create and delete in its policy instead.

Derived or declared fields#

An empty resource derives every field from the entity’s mapping: a string column becomes a searchable Text, a backed enum a filterable Select, a stdClass or array|stdClass property (a JSON column) a Json (an array property derives nothing), a #[BelongsTo] a relation when its target has a resource, and so on. An owned #[HasMany] derives a HasMany shown as a count and a panel; editing its rows inside the parent’s form is a Repeater in relationship mode, declared, and a JSON list of strings a Tag. Declaring fields() replaces derivation entirely. See Fields.

Derivation publishes every string column, a password hash or a token included, in the list, the record page and search. An entity holding a secret needs its fields() declared, with the secret as a Password, which is only ever typed on a form: the compiler refuses one made sortable, filterable, searchable, inline editable or shown on the list or the record page, and one named as the resource’s title, which labels, searches and displays the record wherever it is named.

Definition methods#

These run once, at compile time, on an instance built without arguments, and return plain data:

Method

Declares

fields()

The fields, in order, with optional sections and tabs; see Forms.

actions()

Action classes; see Actions.

widgets()

Widget classes shown above the list; see Dashboards and widgets.

policy()

The policy class; see Authorization.

defaultSort()

The list’s order, such as ['-createdAt', 'name'].

perPage(), perPageOptions(), maxPerPage()

The default page size, the sizes offered, and the most one request may ask for.

withoutCount()

Whether a list page skips the COUNT of the match: total and lastPage are null and hasMore says whether another page follows, read from one row past the page. The admin pages it by previous and next. An export counts no further than one row past its limit. False by default; for a table large enough that counting is the slow part. See Lists and REST API.

cursorPaging()

Whether the admin pages the list by cursor, ordered by the identifier: no sort, grouping, page numbers, total or totals row. False by default. The REST API is unchanged: ?page= and ?cursor= both work on every resource.

softDeletes()

The nullable DateTimeImmutable property that marks a record trashed.

timestamps()

The properties Vector stamps on create and on every update; createdAt and updatedAt by default.

exportLimit(), exportQueueLimit(), bulkLimit()

Per-resource limits; see Limits and guarantees.

badge()

A count beside the resource in the menu.

replicable()

Whether records can be duplicated; true by default.

searchSubtitle(), searchImage()

What global search and a relation’s choice list show under the title and as a thumbnail.

fullText()

The searchable text fields a full-text index covers; see Search.

calendar()

The calendar the list offers beside the table; see Calendar and board.

board()

The board the list offers beside the table; see Calendar and board.

Request-time hooks#

These run on an instance the request container builds, so they may inject anything a controller may:

  • scope(Query $query, CurrentUserInterface $user) narrows the rows a user sees everywhere: lists, counts, exports, badges, search.

  • create() builds a new entity from the validated values, and apply() writes them to a loaded one. Returning null or false leaves it to Vector’s default writer. A columns-mode BooleanGroup appears in the values twice: under its own name, as the object of every flag, and under each flag’s property name, as that flag’s bool.

  • beforeCreate(), beforeUpdate() and beforeDelete() run after validation and before the flush; afterCreate(), afterUpdate() and afterDelete() run after the flush committed. Each receives the entity and a WriteContext, whose input is what the write was asked after validation: the field values for a create, an update or a list edit; {ids, fields} for a bulk update; {<relation>: [...], operation} for an attach or a detach; {ids, operation} for a delete or a restore.

Badges#

A badge counts the records matching a filter, as the user’s own list would count them, and shows the count in the menu:

public function badge(): Badge
{
    return Badge::count(['status' => 'open'], 'info', 'open tickets');
}

The filter uses the list grammar and must name filterable fields, with operators they take. It is counted with the resource’s scope and soft deletion applied. The UI polls GET /vector/badges every minute and after each navigation. A user who may not list the resource, or see a filtered field, gets no badge.

Calendar and board#

A resource can offer its list as a calendar, a board, or both, beside the table (see Lists). Both hooks return null by default:

use Kinetis\Vector\Board;
use Kinetis\Vector\Calendar;

public function calendar(): Calendar
{
    return Calendar::on('dueAt')->end('resolvedAt')->color('status');
}

public function board(): Board
{
    return Board::on('status')->position('position');
}

Calendar::on($start) places each record by a Date or DateTime field. end($field) names where an event ends, a field of the same type; without it an event is its start alone. title($field) names what an event shows, the resource’s title field by default. color($field) colours the events by a single Select’s option colours, the theme’s primary colour otherwise. A Date start makes all-day events and a DateTime start timed ones; allDay() shows a DateTime calendar’s events on the days they span instead.

Board::on($field) makes a column of each option of a single Select, in the options’ declared order, with their labels and colours. title($field) names what a card shows, the resource’s title field by default. position($field) names an integer field that orders each column and enables reordering within it, cards that share a position following their primary key: a dropped card takes the position after the card above it, and the cards below that would no longer follow it are renumbered, all in one POST /vector/r/{resource}/changes transaction that checks each record’s version. Give each new record a position of its own (the demo’s tickets take the next one in their status in beforeCreate()): a column of equal positions renumbers every card below a drop. Without a position field a column follows defaultSort(), then the primary key, and a move writes the select alone with PATCH, sending If-Match when the entity has a #[Version].

The compiler refuses, naming the resource: a calendar start or end that is not a filterable Date or DateTime field, an end of another type than the start or the start itself, a colour field that is not a single Select or whose options have no colours, a board field that is not a single Select editable on update and filterable, a position field that is not an integer Number editable on update and sortable, a title field that maps no column, and any of these fields that neither the index nor the show page shows (a list request cannot return it). A user who may not see the calendar’s start or the board’s field gets neither mode; an end, colour or position field they may not see is left out, and a title falls back to the resource’s.

The descriptor publishes them as the resource’s calendar (start, end, title, color, allDay) and board (field, title, position), null when not declared.

Checked at build#

Compilation refuses, naming the class and field: a field that maps no property, a #[BelongsTo] declared without BelongsTo::to(), a relation to an unregistered resource, a sortable field without a column, a searchable field that is neither a string column nor a BelongsTo, a searchable BelongsTo whose target’s title field is not a string column, a filterable collection, a summary over a non-numeric column, a default sort over a field that is not sortable, an unadministered identifier, a softDeletes() property that is not a nullable DateTimeImmutable, duplicate field, action or widget names, a slug already taken, and an entity with several resources but not exactly one relationTarget. It refuses a fullText() that names no field, names a field twice, or names one that is not a searchable Text, Textarea, Markdown, Email, Url or Slug field, and a configuration that is not a plain lowercase name. It refuses a calendar() or board() that breaks the rules of Calendar and board. The pages on Fields and Forms list what each feature refuses besides.

Listing what compiled#

vector:list compiles the registry afresh, as kinetis build would, and prints its resources, settings groups and dashboards; it reads and writes no cache. A compile error fails it with the same message. The labels are the declared ones, before translation, and every resource is listed whatever its policy: what a given user sees is GET /vector/schema or the MCP tool vector_describe. In the demo:

$ vendor/bin/kinetis vector:list
Resources:
Slug               Label              Group    Entity                          Resource                                Connection
-----------------  -----------------  -------  ------------------------------  --------------------------------------  ----------
agents             Agents             Support  App\Domain\Support\Agent        App\Vector\Support\AgentResource        support
categories         Categories         Catalog  App\Domain\Category             App\Vector\CategoryResource             default
customer-profiles  Customer profiles  Sales    App\Domain\CustomerProfile      App\Vector\CustomerProfileResource      default
customers          Customers          Sales    App\Domain\Customer             App\Vector\CustomerResource             default
labels             Labels             Support  App\Domain\Support\Label        App\Vector\Support\LabelResource        support
order-lines        Order lines        Sales    App\Domain\OrderLine            App\Vector\OrderLineResource            default
orders             Orders             Sales    App\Domain\Order                App\Vector\OrderResource                default
products           Products           Catalog  App\Domain\Product              App\Vector\ProductResource              default
profiles           Profiles           Access   App\Domain\User                 App\Vector\ProfileResource              default
support-teams      Teams              Support  App\Domain\Support\Team         App\Vector\Support\TeamResource         support
tags               Tags               Catalog  App\Domain\Tag                  App\Vector\TagResource                  default
ticket-replies     Ticket replies     Support  App\Domain\Support\TicketReply  App\Vector\Support\TicketReplyResource  support
tickets            Tickets            Support  App\Domain\Support\Ticket       App\Vector\Support\TicketResource       support
users              Users              Access   App\Domain\User                 App\Vector\UserResource                 default

Settings groups:
Name       Label            Class
---------  ---------------  ---------------------------------
branding   Branding         Kinetis\Vector\Settings\Branding
jobs       Background jobs  Kinetis\Vector\Settings\Jobs
languages  Languages        Kinetis\Vector\Settings\Languages
store      Store            App\Vector\Settings\StoreSettings

Dashboards:
Name  Label     Class
----  --------  -----------------------------------
main  Overview  App\Vector\Dashboards\MainDashboard

A resource in no navigation group shows a dash (-) in the Group column.

See also#