Fulcrum

one declaration every read and write

Fulcrum is a PHP framework for building systems of record. You declare what an entity is; the engine does the rest — the schema mapping, the editor, the list, the search, the links between entities, and a full snapshot of every version a row has ever had.

Internal documentation. Fulcrum is not a public release.

An engine, not a scaffold

Most data frameworks generate code. You run a command, get a controller and a set of views, and from then on the application is yours to maintain — the framework has left the building. Fulcrum does the opposite. A module is a description that stays a description, and one engine class interprets it on every request, for the rest of the system's life.

That single interpreter is the whole point. Because there is exactly one path from a form to a table, there is exactly one place where types are coerced, one place where deleted rows are hidden, one place where an old version of a row is snapshotted before it is replaced. Change that path once and every screen in the application changes with it.

Fulcrum ships as two trees: an engine (the framework — the module base class, the API front door, database and helper libraries) and a client (one specific application — its module declarations, its configuration, its themes). Neither reaches into the other by relative path; they are joined by two constants, FULCRUM_PATH and CLIENT_PATH, so the same engine can carry more than one application and be upgraded underneath them.

A module is an entity, a table, and three views of the same fields

Everything in a Fulcrum application is a module: a PHP class extending the engine's module base, backed by exactly one table. Almost all of it is one array. $modconfig names the table and then describes the entity three times over — how it is searched, how it appears in a list, and what its detail editor contains — because those are genuinely different views and pretending they are one produces bad versions of all three.

class notes extends module {

  public $modconfig = [
    'database' => ['table' => 'notes'],

    'search' => [
      'date_from' => ['dbfield'=>'date_entered', 'title'=>'From',
                      'type'=>'date',   'compare'=>'>='],
      'tsearch'   => ['dbfield'=>['note','comment'], 'title'=>'Search',
                      'type'=>'text',   'compare'=>'like%..%'],
      'answered'  => ['dbfield'=>'comment', 'title'=>'Dealt with',
                      'type'=>'ynx',    'compare'=>'cynx'],
    ],

    'list' => [
      'date_entered' => ['dbfield'=>'date_entered','title'=>'Date','type'=>'string'],
      'note'         => ['dbfield'=>'note','title'=>'Note','type'=>'stringbr',
                         'data'=>['maxlength'=>'500']],
    ],

    'detail' => [
      'date_entered' => ['dbfield'=>'date_entered','title'=>'Date','type'=>'date',
                         'data'=>['default'=>'today','allowedit'=>'Admin']],
      'user'         => ['dbfield'=>'user','title'=>'User','type'=>'userselect'],
      'note'         => ['dbfield'=>'note','title'=>'Note','type'=>'textarea',
                         'data'=>['w'=>'300px','h'=>'150px']],
      'viewings'     => ['dbfield'=>'function:attach','title'=>'Viewings',
                         'type'=>'textarea'],
    ],

    'triggers' => [
      'note_saved' => ['trigger'=>'postform', 'action'=>'http://localhost:3849/analyse'],
    ],
  ];
}

From that array the engine derives the edit form, the list grid, the search panel, the WHERE clause, the type coercion in both directions across the database boundary, and the API surface. Nothing else has to agree with anything: the renderer and the SQL builder read the same declaration, so an input cannot drift from the column it writes to.

What a field entry says

dbfield
The column. May be a list of columns, so one search box spans several. May be function:name for a field computed by a method rather than stored, or count:hook for a live count of related records, which the engine turns into the necessary joins.
type
Chooses the control and the storage handling together — from string, date, price, emailaddress and mobilenumber, through pulldown, multicheckbox, userselect and ynx, to latlong, bitflags, json, image, pdf and child, which renders another module's records inline.
compare
Search fields only: the operator this criterion applies — >=, like%..%, notlike, a range, or a named comparison the engine implements.
data
Everything contextual: a default value, control dimensions, a truncation length, option lists, and allowedit — the roles for whom this one field is writable.
validators
Rules applied before a write lands: notnull, unique, nonunique, numeric, positiveinteger, date, emailaddress, checkmobile, url. A rule the set does not cover is added to the engine, not worked around in the module.
triggers
Fire on an engine event — a save, say — and call out to a named URL. How a module notifies the rest of a system without knowing anything about it.

The comparison vocabulary is worth a moment because it is where most hand-written queries would otherwise go. Dates are expressed in the words people actually use — today, overdue, this week and next, within 45 days — and the engine resolves them at query time, so a saved search stays correct next month. Ranges are proportional: within takes a figure and a tolerance either side of it, which is how you ask for "around this much" without computing the bounds. And linked asks whether a record has, or has not, any relation of a given kind — an existence test across the link table, expressed as a search field like any other.

Beyond the array, a module can override startup() to shape itself per session or role, preprocess() and postprocess() to act either side of a write, and identify() to name itself. That is the whole of the interface most modules need.

Two columns are the framework's

Any table a module runs on must carry an id primary key and a nullable, indexed history_id. The second is what makes a row current: a live row has history_id IS NULL. Everything else in the table is a previous version of something.

The first is more interesting than it looks. Ids do not come from AUTO_INCREMENT; they come from a shared generator that keeps one counter per table above a common base, allocated atomically and re-checked against the target table before use. The effect is that an id is unique across the whole system, not just within its table — and that is what lets every relationship in the application live in a single table, as the next section describes.

CREATE TABLE `notes` (
  `id`         INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `history_id` INT NULL DEFAULT NULL,
  -- module fields --
  KEY `history_id` (`history_id`)
);

Omit history_id and the module still works — it just falls back to resolving current rows with a join against the history table on every single listing. The column is detected at load time, so the fast path is opt-in by schema, not by configuration.

Relations live in one table, named by hook

Fulcrum does not put foreign keys in module tables. Every relationship in the system — a note attached to a person, a photo attached to an item, a document attached to a case — is a row in one global link table: three integers, a hook and two ids, unique together. Because ids are unique system-wide, that table needs no type column and no module names to be unambiguous.

The kind of relationship a link represents is its hook: a named, directional pair declared once in a hooks table, carrying the label each side sees the other by — one module's "Photos" is the other's "Belongs to". Two modules can be related several ways at once, each its own hook, so the same pair of ids can appear in link more than once and mean different things. Adding a relationship to a running system is a row of configuration, not a schema migration.

module A id history_id …fields module B id history_id …fields link hook a b hooks table: (A, verb) ↔ (B, verb) — one row per named relationship
Adding a new kind of relationship means adding a hook, not altering a table. Nothing about module A changes when module B starts pointing at it.

The consequence worth knowing is that traversal has to be explicit about which hook it means. The engine gives you two ways in, and they are not interchangeable: loadselection($parentId) reads the link table by hook and returns everything joined that way, independent of who is looking; the child-list path additionally applies the child module's own default filter, which is what you want on screen and not what you want in a report.

Moving a relationship is its own primitive. interlink() toggles a single link off one record and on to another — a genuine move, leaving no copy behind — which is how records get merged or re-parented without rewriting either side's fields.

Updates do not overwrite; they snapshot

When a module with history enabled updates a row, the engine first inserts a copy of the row as it currently stands — same table, new id, old values — then writes a row into the single global history table recording which table and record changed, what operation caused it, which user did it, and when. Only then is the original row updated in place.

before id 20000481 history_id NULL · value “A” update after id 20000481 history_id NULL · value “B” id 20000902 history_id 4471 · value “A” history 4471 who · when · why
The record keeps its identity. The version that was replaced keeps the data. One update leaves two rows in the table, and only one of them is live.

Deletion works the same way: a delete on a history-tracked module is a tombstone, not a DELETE, and there is a restore to undo it. The row stays, the audit trail stays, and it simply stops satisfying history_id IS NULL. History is per module — a module can turn it off, and modules that do get hard deletes with no recovery, which is a choice worth making consciously rather than by omission.

Because the versions sit in the module's own table, they are searchable with the module's own search. On top of the ordinary criteria the engine can filter by what happened to a field rather than what it holds: went from empty, went to empty, changed at all, or was touched by any change. "Which records had their owner reassigned last month" is a search, not a report someone has to write.

This design is the reason Fulcrum insists that all data access go through the engine's own methods. The engine's read path applies the live-row filter for you; hand-written SQL does not, and quietly counts every historical version as if it were a current record. The rule inside a Fulcrum project is absolute: no raw SQL, not even for a read-only check. If the engine cannot express something, the fix is to extend the engine.

A small vocabulary of operations

Every screen, script and API call in a Fulcrum application is assembled from the same short list of engine calls. There is no second way to do any of them. Reads are methods on the module; state changes go through one dispatcher, engine($verb).

searchresults()
Runs the module's current search, returning ids, rendered rows, or the SQL itself. Applies the live-row filter, so historical versions never appear in a result.
loadselection()
Loads the records linked to a parent under a hook. Reads the link table directly — session-independent and complete.
rendereditor()
Loads one record by id and builds its editor from the detail declaration.
engine('postform')
The only write. Creates a record, or updates one when an id is supplied — validating, coercing and snapshotting on the way through.
engine('delete') · ('restore')
Retires a record, and brings it back. A tombstone where history is on; a real delete where it is off.
engine('collapse') · interlink()
Merge selected records into one survivor, re-pointing the losers' links; or move links between records under a named hook. The two halves of any de-duplication.
engine('clone') · ('export')
Duplicate a record; take result sets out as CSV or PDF, built from the same list declaration that renders them on screen.
engine('import')
Idempotent ingest from another system. Foreign ids are mapped to local ones and kept, so the same feed re-run updates rather than duplicates.
engine('savesearch') · ('retrievesearch')
Searches are data. They can be named, stored, recalled, and logged — the search panel is not a throwaway form.
engine('runfunction')
Calls a named method on the module. The escape hatch for application logic, reachable identically from the interface and the API.
preprocess() / postprocess()
The module's own hooks either side of a write — where derived fields, notifications and cross-module effects belong.

There are no transactions. Every statement autocommits, so a multi-step operation that fails part way leaves partial work behind rather than rolling back. Sequences that touch several records need to be written so that an interrupted run is detectable and re-runnable.

One endpoint, a queue of commands

Fulcrum exposes itself to the outside world through a single API file. A request names a module and carries a commands object; the engine instantiates that module and applies the commands in order against it, so state set by one command is visible to the next. Setting a search and then asking for the results is two commands in one round trip, not two requests.

POST /fulcrumapi2.php
{
  "module": "notes",
  "commands": {
    "search":   { "status": "open", "owner": "kb" },
    "listids":  {},
    "postform": { "id": 20000481, "fields": [ … ] }
  }
}

The set is small and maps onto the engine rather than onto screens: search, searchfield, searchorder and numrows to set up a query; listids, listdata and pagesize to read it back; renderEditor for one record; linkedIds, listChildren, switchToChild and linkChild to move around relations; postform, deleteRecord and interlink to change things; runfunction and getFunctions for what the module adds itself.

One command is worth calling out. exportModuleConfig hands the caller the module's own declarations — its fields, types, options and search criteria. A separate front end can then build its forms and filters from the same source the server validates against, instead of keeping a second copy of the data model that drifts.

Responses have the same shape for every module: rows keyed by id, alongside headers and paging state. Only the field set differs, and the field set is the declaration. A client written against one module is structurally written against all of them.

Things that catch people out

  • Command order is semantics. Sorting and paging must be set before the listing command that consumes them, or they apply to the next request instead of this one.
  • An update is an update because the payload contains id. Omit it and you get an insert, silently, every time.
  • The children-of-a-parent listing applies the child module's own default filter and the caller's current selection. For a complete set, walk the links instead.

Authorisation

One gate runs before dispatch: a caller must hold a valid session, or originate on the local machine. Loopback is decided from the connection's own address and never from a forwarded-for header, which is a distinction worth keeping — trusting the header once made the gate bypassable by anyone who could set it.

Beyond that, named modules can be listed as gated, admitting only an administrative role, with exceptions punched through by matching the exact shape of a command payload rather than by widening a role. Anything that must genuinely be prevented is prevented in the engine methods themselves, which is the boundary every caller shares.

A module's permissions() declaration decides what appears in the built-in interface and nothing else. It is not an authorisation boundary and the API does not consult it — the gated list is a separate mechanism, kept in step by hand. Treating the two as one is the mistake this framework most invites.

Building on it

An implementation is a client tree: a directory of module classes, a configuration file naming the engine and the database, whatever JSON its workflows need, and a theme. The web root is the client, not the engine — every entry point is a few lines that load the client configuration and hand off — so a client that needs to intercept one of them fattens its own stub rather than patching the framework. Include paths put the client ahead of the engine, which is the main override seam.

Adding an entity to a running system is three things: a table with the two framework columns, a module class declaring its fields, and hook rows for however it relates to what already exists. No migration of other modules, no touching the engine.

Screens are configuration too. A workspace is declared as a set of named panes — this module here, that module's children under a given hook there — and the engine composes the multi-pane interface from it. Selecting a record in one pane is what fills the pane below it, because the panes are related by hook and the engine already knows how to follow one.

What the engine deliberately does not decide is left in a system configuration block: the system's name, which modules are gated, the phone-number rules for the country it operates in, error reporting, extra menu items and markup to inject into the shell, and the database connections — including the separate store used for uploaded images and documents, which are kept out of the working database and served through a single scaled-and-cached endpoint. A development instance can also be told to neuter all outbound mail, which turns a copy of a live system into a safe one.

Extension points, in the order to reach for them

declare a field
Most requirements are a field of an existing type with an existing validator.
override a lifecycle method
startup() to shape the module per session or role, preprocess() and postprocess() for effects around a write, changetrigger() for what a specific value changing should cause.
name a method after a type
Define inputrender_<type> or validate_<type> on the module and the engine will find them. A field type or a rule can be local to one entity without the framework knowing about it.
declare a trigger
Fire a URL on a save. The way a Fulcrum module hands work to something outside PHP — a queue, a worker, an analyser — without either side knowing the other's internals.
override an engine method
Narrow the read and write paths themselves when a rule must hold for every caller, native interface and API alike.
extend the engine
A type or validator that more than one implementation would want belongs in the framework, where every implementation gets it. This is the sanctioned move when the engine is missing something — not a bypass in the client.

Configuration as data

Long-lived business rules that change more often than code — the stages of a process, what follows what, how long each may sit — are better held as a JSON document the engine reads than as branches in a module. Records then reference a stage by a stable string key rather than a position, so new stages can be added freely and only renaming or removing one is a breaking change. The same document goes out over the API, which lets a separate front end render a workflow it does not itself define.

The engine takes the same approach to matching. A ruleset is a declared library of named criteria, each holding the condition that decides it. The engine compiles a selection of them into a query two ways at once: as filters that narrow the result, and as scoring terms that are summed and sorted on. Relevance ordering therefore comes from the same declaration as the filtering, and a new criterion is a line of configuration rather than a change to a query somewhere.

A representative implementation

The system Fulcrum was built for is a sales and client-management back office: a few dozen modules covering people, the things being sold, the requirements a buyer has stated, and the notes, documents, appointments and messages that accumulate around them. Its interesting parts are all relations and history rather than screens. A requirement is linked to candidate items by a matching hook, and rules declared per feature translate in both directions — from a stated requirement into a query over items, and from an item back into the set of requirements it could satisfy. Its message and document trails are child modules under hooks, so a record's whole story is a link traversal. And because every module keeps snapshots, a record that looks wrong today can be read back to the version and the user that made it so.

None of that is in the framework. It is a client tree of declarations over the same engine described above — which is the test Fulcrum is meant to pass: an application should be describable, not programmed.