Skip to main content
Version: v1 (Current)

Application services, caching and route binding

Application services live under app/Services; this guide covers representative backend lookup/cache services even though it appears in the frontend contributor section. The dashboard HTTP client and URL helper are documented in frontend routing. External synchronization uses the separate entity sync architecture.

Services do not all implement a repository abstraction or one cache protocol. BaseServiceInterface is an empty marker in the reviewed source: it does not require find, cache keys, invalidation or authorization. Inspect the particular service, caller and model observer before extending a workflow.

Choose the owning service​

  1. Locate the controller/action and model relation for the operation.
  2. Inspect the actual service method, parameter types, return value and context sources.
  3. Check cache keys, tags, lifetime and every input that changes the query.
  4. Trace writes and observer registration to their invalidation calls.
  5. Verify authorization separately; a cached model lookup is not an action permission check.

The earlier generic ExampleService contained invalid PHP and invented examples() relationships. Use current service methods rather than copying a universal template.

Project lookups​

ProjectService.findCached($id, $uniqueKey = 'slug', $routeName = null) obtains the team from getPermissionsTeamId(), falling back to Context::get('team_id') when that value is PHP-falsy (the source uses if (! $team)). It uses a 300-second tagged cache and queries the selected column. The ordinary branch filters team_id; a supplied route name beginning system. skips that filter.

Its eager loads include active shortcuts/top shortcuts, system tags and the team's ID/slug. It returns the first matching project or null. It does not authorize the requester or prove every related resource is visible.

Within an already-authorized request with validated team context:

use App\Services\ProjectService;

$project = app(ProjectService::class)->findCached($projectSlug, 'slug');
if ($project === null) {
abort(404);
}
// Apply the intended action policy before using the project for that action.

$projectSlug must come from validated intended context; this fragment does not set membership or grant access. Do not let an untrusted caller select a system. route-name argument to bypass the ordinary team filter.

The cache key includes team, lookup column and value, but not the system-route flag. Because that flag changes query scope, source alone does not prove safe cache separation between system and ordinary calls sharing those key inputs. Test both call orders before relying on that separation. Other project lookup methods also have different scope/return contracts: findSlugById queries by numeric ID, while projectTeamLookup returns project/team lookup information. Do not substitute one for an authorized project fetch.

ProjectService.getCacheTags() returns projects; supplying a project ID also adds project-specific tag names. The reviewed findCached() uses the general tag set. bustCache($projectId) flushes its selected tags, including the shared projects tag. Do not describe this as a guaranteed single-key eviction or assume adding a project tag narrows every cache entry's lifecycle.

Team lookups and key identity​

MethodCurrent contract
`TeamService.findCached(intstring $teamId)`
`TeamService.findCachedBySlug(intstring $slug)`
TeamService.bustCache(int $teamId, string $slug)Forgets ID key, explicit slug key and dashboard-mask-tier key, then busts team quota cache

findCached() uses team_{$teamId} for both integer and string inputs, whereas explicit slug lookup uses team_slug_{$slug}. A numeric string is treated as a slug by the query but can share the first method's key with an integer ID. Its slug lookup also uses a different key from findCachedBySlug(). Choose the method/input type deliberately; a method accepting a union type is not proof that ID and slug caches are interchangeable or invalidated together.

Both lookup methods use the teams / all_teams_list tag set. A cached team is not evidence of membership or effective project permissions. If a slug changes, inspect old and new keys: observer calls using the current slug do not alone prove all earlier slug-key entries were removed.

Portal lookups and invalidation​

ProjectPortalService.find($val, Project $project, $key = 'id') scopes through $project->portals() and calls find($val). It does not use $key to switch to a slug column. Its key/tag helper signatures expect numeric portal IDs; do not infer general slug support from the public method's int|string value type.

The lookup caches for 60 * 60 * 24 seconds. It loads portal domains, access codes and configured authentication methods, decodes method config where valid JSON and attaches a navigation list. The old example's domains/theme eager-load list was not the current method.

Portal key/tag names include project/portal identity plus shared project/portal and current-team tags. bustCache($projectId, $portalId) clears domain lookups, page access maps, widgets, authentication methods and navigation, flushes the selected tagged entries, and calls ProjectPortalPageService.bustProjectCache() because page caches include portal active state. These are explicit dependencies, not automatic discovery of every related cache.

Domain lookup, navigation, widgets and default-portal URL are separate methods/caches. A changed portal record does not establish that a browser service worker or remote client has consumed fresh configuration. The portal guide covers those runtime boundaries.

Observer invalidation​

The reviewed models register ProjectObserver, TeamObserver and ProjectPortalObserver. Their model-event paths call the corresponding services, with different related work:

  • Project create/update/delete/restore/force-delete paths bust project/quota data and selected subscription-related state.
  • Team create/update/delete/restore/force-delete paths call TeamService.bustCache with current ID/slug.
  • Portal create/update/delete/restore/force-delete paths call the portal invalidator. Portal saving also updates its PWA config epoch for relevant dirty columns; an update can dispatch pwa-config-changed when those columns changed.

This does not guarantee that every write invalidates every cache. Query-builder updates, quiet saves, suppressed events, imports and other batch paths can have separate behavior. Inspect their actual reconciliation steps. “Restored” invalidation is not the same as rebuilding a cache immediately: a later read may repopulate it.

For a new cached query, identify its invalidation owner and every relevant mutation, including relationship changes, deletes and identifier changes. Test a read/write/read sequence as well as the cold read. If an observer dispatches a browser event, verify delivery and client consumption separately.

Cache behavior and failure handling​

A remember() callback queries the database on a cache miss. It is not automatically an exception fallback when the cache backend is unavailable. The representative methods do not wrap every tag/read/write in a database-fallback handler. Design explicit error handling where the operation requires it; do not silently treat a backend failure as a confirmed miss.

Use a cache store that supports the actual tagged operations. Passing tests with an array/mocked store does not prove deployed Redis connectivity, namespace behavior or distributed invalidation. Tags are identifiers used by the cache implementation, not an inherent team/project authorization hierarchy.

Cache keys should distinguish inputs that change results: parent identity, ID versus slug, selected column, route scope, filters and any audience-dependent values. Do not put user-specific query results under a global key without reviewing that audience boundary. Positive data can become stale even when null results are re-queried; test misses and hits deliberately.

Cache flushes, database writes and external side effects are not one atomic transaction merely because a service coordinates them. Consider transaction ordering, job dispatch and stale reads in the actual caller. Avoid using broad production cache clearing as an unreviewed troubleshooting shortcut.

Route child binding​

Project.resolveChildRouteBinding() resolves the child relationship/model, derives its service name (using getServiceName if available), and calls the service's find method if present. It passes the value, Project, selected field or related model route key, and child type. Without such a service method it delegates to Laravel's parent implementation.

The called service must actually honor the field and scope arguments. ProjectPortalService.find() illustrates why a general binding signature does not prove every service supports custom route keys. Model binding also does not replace the controller/policy's action authorization.

Team.resolveChildRouteBinding() is different: it rejects nonnumeric values for pluginApiTokens and otherwise delegates to the parent implementation. It does not implement the generic service-dispatch pattern shown in the prior guide. Test the exact nested route, ownership and not-found behavior rather than assuming Project and Team share one resolver.

External integrations​

Entity sync uses registered builders, request plans and remote transports; supported adapters and failure/replay semantics are documented in the sync overview and reference. Do not promise Salesforce or generic device sync from the existence of a service namespace. Provider credentials and inbound import adapters have their separate integration contracts.

Verification and troubleshooting​

SymptomInspect
Lookup returns a different parent/resourceExact argument type, column, team context, system-route flag, parent relation and key collision
Slug change still returns old contentOld/new key families, observer arguments and actual mutation path
One update evicts more than expectedShared tags and flush semantics; do not assume tag names are a hierarchical restriction
Database changed but cached UI did notQuiet/bulk write path, invalidation owner, subsequent cache hit and client refresh
Cache outage raises an exceptionActual error handling; miss callback is not a guaranteed outage fallback
Nested route resolves wronglyProject versus Team resolver, service find implementation and actual supported route key
Correct record resolves but action deniedPrincipal/effective permission and policy, independently of lookup/cache behavior

Current source entry points are ProjectService, TeamService, ProjectPortalService, their observers/model registrations and Project/Team child-binding methods. Validate cold/hit/invalidation behavior and tenant boundaries with controlled data in the configured cache backend before deploying a new cache contract.