Build with Pulse: working patterns
These examples connect the reference APIs into small backend features. Read runtime, plugins, security and testing for the complete surrounding contracts.
Run examples in a disposable local practice database. PHP snippets belong in a booted application, not a shell. Each example states its assumptions; they do not silently install missing gameplay packages.
For one complete, uninstalled teaching example connecting these patterns, follow the Field Notes walkthrough.
Add a small API feature
The first-plugin exercise creates a complete Hello Pulse package and checks a greeting route. It remains useful as a small task example inside the larger handbook.
The underlying steps are:
- Generate a package using a verified scaffold command and inspect its manifest.
- Put backend logic in a controller/service and route it through the correct plugin route file.
- Register the package, validate it and enable it through the installed registry.
- Exercise the real request, not only the PHP syntax.
- Confirm disabling the package removes/blocks the capability.
Keep account authentication, package access and operation authorization explicit. A harmless fixed-text greeting may be public; an endpoint returning player data needs an account boundary.
Store a per-player preference
Use this in an authenticated plugin controller method receiving Illuminate\Http\Request $request:
use App\Core\Models\PluginMetadata;
$validated = $request->validate([
'preferred_colour' => ['required', 'string', 'in:blue,green,gold'],
]);
$user = $request->user();
PluginMetadata::setValue(
$user,
'my-plugin',
'preferred_colour',
$validated['preferred_colour']
);
return response()->json([
'preferred_colour' => PluginMetadata::getValue(
$user, 'my-plugin', 'preferred_colour', 'blue'
),
]);
An input {"preferred_colour":"green"} returns the same selected value and persists it for that account/plugin. The route must use authenticated access; there is no client-supplied owner ID to edit another player. The static metadata helpers work on current core User even though its metadata trait is not applied.
See data and metadata for null handling, JSON types, deletion and concurrency limits.
Award a reward exactly once in your own mechanic
A bare call to credit() can repeat if a request is retried. Your plugin needs a persistent claim record and a unique rule before changing money. This example is a transaction pattern, not a ready-made core reward endpoint.
Assumptions:
- Your migration creates
my_plugin_reward_claimswithuser_id,reward_key, timestamps and a unique(user_id, reward_key)index. - Your eligibility logic has already established this authenticated account may claim this fixed reward.
- Your active plugin context has the approved
ledger.writecapability. - Your plugin has a claim model with
user_idandreward_keyfillable and the correct table.
In that authorized plugin service, the sequence is:
Begin transaction
insert unique claim for user + reward key
credit fixed reward through EconomyService
Commit both writes
If inserting the unique claim fails, return the previously established claim outcome; do not mint again. If credit fails, roll back the claim. Use narrowly recognized duplicate-key handling appropriate to your drivers, not a catch-all that pretends all database errors mean "already claimed".
Core does not ship RewardClaim, so this page does not present an invented core class as callable code. Write concurrency and retry tests for your actual schema. Nested economy transactions participate in the outer database transaction, while transport broadcasts currently occur before outer commit; see economy limits.
Customize progression through a formula
In your enabled plugin's boot-time code, register a custom formula your mechanic will call:
use App\Core\Services\FormulaEngineService;
FormulaEngineService::registerFormula('my-plugin.exploration_reward', [
'label' => 'Exploration Reward',
'default_expression' => 'max(1, user.level * 5)',
'variables' => [
'user.level' => ['label' => 'Player Level', 'default' => 1],
],
]);
Then, in the authorized action, evaluate it with actual state:
use App\Core\Models\PlayerStat;
use App\Core\Services\FormulaEngineService;
$stats = PlayerStat::getOrCreateForUser($user->id);
$amount = (int) round(app(FormulaEngineService::class)->evaluateFormula(
'my-plugin.exploration_reward',
['user.level' => $stats->level]
));
At level 4 with this default, $amount is 20. This computes a value; it does not establish eligibility or change money. Use the once-only reward workflow and economy service when applying it. Studio tuning affects a mechanic only if it actually evaluates the named formula.
See Studio for validation/simulation, stored overrides and supported functions.
Run a periodic task
Add a listener to your enabled plugin's hooks.php:
<?php
app('hook')->addAction('pulse.minute', function (array $context): void {
logger()->info('Exploration minute task', [
'minute' => $context['minute'],
'interval' => $context['interval'],
]);
});
In a local development environment, php artisan pulse:run --interval=minute --sync processes the interval immediately; under Docker prefix it with docker compose exec backend. This runs other listeners too, so use an intentional test/practice environment.
For normal scheduling, both the scheduler and appropriate worker/queue must run. A listener attached to a catalogue name with no dispatcher never runs automatically. For repeated rewards, use durable accounting/deduplication; a periodic event is not exactly-once delivery. See hooks and operations.
Add an operator-editable record type
Use the Studio entity registration example in your plugin boot code and define the owned schema deliberately in a plugin migration. Expose only fields operators should edit.
After registration, query the Studio service/controller for that entity. Verify:
- Required fields reject missing values.
- Accepted values persist with the expected casts.
- Updating one field preserves the others.
- Bad sort fields and unexpected payload keys do not become arbitrary SQL identifiers.
- Table creation/listing side effects and role access are understood.
A record-editing schema does not itself implement a gameplay mechanic. Your runtime action must consume those records and enforce the gameplay rules.
Add an admin screen or player widget
Backend and frontend are separate contracts. A menu link alone does not implement either a component or an endpoint.
- Add the owned backend endpoint with authentication, package access and relevant role/permission checks.
- Build a Vue component using the host runtime contract; register its exact component key.
- Declare the component/view/menu/slot metadata in the package manifest expected by the relevant host app.
- Build the package runtime and update the manifest SRI information with the supported tooling.
- Refresh registration and check the manifest the browser actually receives.
- Exercise loading, empty/error, success and forbidden states on both narrow and wide screens.
Use frontend runtime, plugin packaging and slot layouts. Public frontend and Slate admin are separate Vue builds; verify which one owns your screen before editing files.
Return account information safely
In an authenticated backend handler:
use App\Core\Http\Resources\UserResource;
return new UserResource(
$request->user()->load(['roles', 'permissions', 'oauthProviders'])
);
The response is based on the resource allowlist, including only relationships deliberately loaded. It differs from returning the full raw model, which currently hides only password and remember_token. See the User output contract.
Verify before publishing a feature
Confirm source behaviour, then test the actual route and permission combinations. Validate the manifest, install/migrate in a clean test host, enable and disable, build the frontend runtime, verify integrity metadata and test upgrades with existing data. Packaging a ZIP alone is not acceptance evidence.
The testing guide distinguishes code review, runtime tests and browser checks. The coverage index distinguishes source-derived references from individually explained or tested behaviour.
Adapt patterns to game mechanics
These are design exercises for an owning plugin, not shipped core game systems. Implement and test the mechanics with the contracts above.
| Design | Decisions to make explicit |
|---|---|
| Offline progression | Bound elapsed time by a cap and zero; lock the owned claim row and persist its timestamp with the grant to prevent duplicate catch-up |
| Weighted loot/pity | Validate a nonempty set of positive weights; charge, grant and update pity state together. Record roll/weight metadata; weighted randomness alone is not a provably-fair protocol |
| Seasons | Listen at a real mechanic dispatcher; use pulse.daily only for an owned periodic task and keep a durable, idempotent rollover key |
| Territory tribute | Define ownership and currency units; use pulse.hourly, stable lock ordering and a period claim key to prevent duplicate shared-vault rewards |
A hook catalogue name does not create the mechanic. The plugin must dispatch custom events, enforce authorization and own its migration/recovery policy. SQLite examples do not establish production-driver lock behavior.