stave.dev

Creating Entity Types

Three paths to a new entity type. Pick by how stable the type is and how much code you want to write.

Which One Do I Want?

A type with its own behaviour: write the subclass by hand. A type that is just a list of attributes, defaults and unique keys: GenericEntity::define(). The same, without writing code: the admin form.

Whichever path you take, the class ends up in the site's entity/ folder, in the Zero\Entity namespace, and autoloads from there. The framework's own classes stay in core/entity/.

1. Hand-Written Subclass

The class is a thin marker: its lowercased class name becomes the entity_type.label. That is the whole binding.

<?php
namespace Zero\Entity;

class Note extends Entity {
    public $uniq = ['title'];
}

The type is registered by the first new Note($data): the constructor in core/entity/Entity.php inserts the type, adds its partition, writes the schema rows from array_keys($data), stores the record and builds note_view.

For defaults or computed values, override the constructor. Core's own Event does:

<?php

namespace Zero\Entity;

class Event extends Entity {

    public function __construct($data){

        if(!array_key_exists("datetime", $data)){
            $data['datetime'] = date('Y-m-d H:i:s', time());
        }

        if(!array_key_exists("ip",       $data)){
            // The client, not the Cloudflare edge in front of it.
            $data['ip'] = \Zero\Core\Request::clientIp();
        }

        // A value is 255 characters at most (entity.value). A longer detail is cut
        // to fit, and the cut is logged; nothing is thrown.
        if(isset($data['detail']) && is_string($data['detail']) && mb_strlen($data['detail']) > 255){
            \Zero\Core\Console::warn("Event '" . ($data['event'] ?? '') . "': detail cut from " . mb_strlen($data['detail']) . " to 255 characters");
            $data['detail'] = mb_substr($data['detail'], 0, 255);
        }

        parent::__construct($data);
    }

}

Use it:

new \Zero\Entity\Event(['event' => 'login', 'detail' => 'ok']);
Don't Reuse a Framework Name

Zero\Entity\X resolves to core/entity/X.php before the site's entity/X.php (Application::classFile()). A site file named Event.php or Entity.php is never loaded.

2. GenericEntity::define()

One call validates a definition, writes the class file, and registers the type:

use Zero\Entity\GenericEntity;

$path = GenericEntity::define('product', [
    'attributes' => ['name', 'price', 'sku', 'status', 'created_at'],  // required
    'defaults'   => [
        'status'     => 'active',
        'created_at' => 'date:Y-m-d H:i:s',
    ],
    'uniq'       => ['sku'],
]);

The signature is define(string $entityName, array $config, bool $force = false): string. It returns the path of the class file. In order, it:

siteDir() is the constant ENTITY_SITE_DIR when defined, otherwise ZERO_ROOT . 'entity/'. Generated classes belong to the site and are never written into core/entity/ when running under Zero.

The class name is the studly-cased type name: product gives Zero\Entity\Product, product_item gives ProductItem. The generated class extends Entity. It carries public $uniq when uniq is given and a constructor that applies the defaults when defaults is given (see Default Values).

From then on, in any request, use the generated class:

use Zero\Entity\Product;

$p = new Product(['name' => 'Widget', 'price' => '29.99', 'sku' => 'WDG-1']);
$found = Product::getInstance()->where('sku', 'WDG-1');
Use the Generated Class, Not GenericEntity

new GenericEntity('product', $data) and GenericEntity::type('product') work only in the request that called define('product', ...): the config they need is held in memory, and without it they throw Undefined entity type. They also store under the type name as written, while the generated class stores under its lowercased class name, so for product_item the two are different types.

Regenerating with $force

Without $force, define() throws when the class file already exists, so a generated file is safe to edit by hand. With $force = true it overwrites a file the generator wrote for the same entity name, hand edits included. It recognises its own files by the docblock line From GenericEntity definition: 'product'. Attributes that are new are appended to the schema and the view is rebuilt; attributes left out of the new definition stay in the schema.

What define() Refuses

Each of these throws an Exception (GenericEntity::validateDefinition() and generateClassFile()):

Refused Rule
A name that is not a plain identifier Entity and attribute names must match /^[a-z_][a-z0-9_]*\z/i and be at most 64 characters.
A missing or empty attributes array It is the one required key.
A default or unique key that is not in attributes Both must name declared attributes.
A default that is not a string, number, boolean or null And a server:KEY whose key is not upper-case letters, digits and underscores.
A class name that is taken It may not match a .php file in core/entity/ (Entity, GenericEntity, Event, Test, Testcase…, case-insensitive), an existing Zero\Entity class the generator did not write, or a PHP reserved word (GenericEntity::RESERVED_NAMES: class, list, int…).
An existing class file Unless $force is true and the file was generated for the same entity name. A hand-written file, a file generated for another name, and a file that differs only in case are never overwritten.

Every value placed in a generated class goes through var_export(), and the generated source is parse-checked in memory before it is written.

3. Admin Form

/admin/entity/create is a form over GenericEntity::define(): an entity name, a list of attributes, and for each one an optional default (literal, date, uniqid or server) and a unique flag. It is EntityAdmin::create() in core/modules/Entity/Admin/EntityAdmin.php, part of the bundled Entity module's admin offering, behind allow.admin. The form calls define() without $force, so it can create a type but not redefine one.

URL What it does
/admin/entity Entity types as cards
/admin/entity/create GET shows the form, POST defines the type
/admin/entity/manage/{label} Records of one type; POST creates a record
/admin/entity/update POST, edits one attribute value
/admin/entity/delete POST, deletes records of one type

The Entity module (Zero\Core\Module\Entity) is on by default and a site switches it off with Entity = off in app/modules.ini, as this site does. Switching it off removes the screens, not the framework. The module that serves these pages is named EntityFramework so that it does not override core's Entity: it is documentation, not a replacement for it. See Bundled Modules and Admin.

Side-by-Side Comparison

Path When to use Class file Example
Hand-written subclass Types with their own constructor or methods Written by you into the site's entity/ core/entity/Event.php is the framework's own
GenericEntity::define() Code-defined types; fixtures Generated into siteDir() entity/Product.php
Admin form Admin-defined types, no deploy Generated into siteDir() by the web server's user Anything an admin creates at /admin/entity/create

Generated files are the site's source: the site's repository decides whether to commit them. define() creates a missing entity folder as 0775 and writes the class file as 0644.