Action-Contracts Architecture
How every piece of business logic sits behind a contract in src/Contracts/ with a default action in src/Actions/, and how a host application swaps any of them.
On this page
Quick Reference#
// app/Providers/AppServiceProvider.php
use AnilcanCakir\MagicStarter\Contracts\CreatesUsers;
public function register(): void
{
$this->app->bind(CreatesUsers::class, \App\Actions\MagicStarter\CreateUser::class);
}
| To do this | Do this |
|---|---|
| Replace a default action | Bind the contract to your own class in AppServiceProvider::register(). |
| Start from a stub | php artisan vendor:publish --tag=magic-starter-stubs; a published stub throws until you implement it. |
| Keep the default and add to it | Inject the default action into yours and delegate to it. |
| Know what a contract must return | The return type of the contract method, exactly. |
Introduction#
Magic Starter uses a contract-action pattern inspired by Laravel Jetstream. Every unit of
business logic is expressed as a PHP interface (a contract) in src/Contracts/ and shipped with
a working default implementation (an action) in src/Actions/. Controllers depend exclusively on
contracts: they never reference concrete action classes.
This separation gives consuming applications full control: swap any action by binding a custom class
in their own AppServiceProvider without touching package source or forking controllers.
How It Works#
Controllers#
Controllers resolve contracts at call time using app():
public function store(RegisterRequest $request): JsonResponse
{
$user = app(CreatesUsers::class)->create($request->validated());
// ...
}
No constructor injection, no direct references to CreateUser::class. The controller does not know, and does not care, which implementation is active.
Default Bindings#
MagicStarterServiceProvider::register() binds every contract to its default action:
$this->app->bind(Contracts\CreatesUsers::class, Actions\CreateUser::class);
$this->app->bind(Contracts\UpdatesUserProfiles::class, Actions\UpdateUserProfile::class);
$this->app->bind(Contracts\UpdatesUserPasswords::class, Actions\UpdateUserPassword::class);
$this->app->bind(Contracts\DeletesUsers::class, Actions\DeleteUser::class);
$this->app->bind(Contracts\SchedulesUserDeletion::class, Actions\ScheduleUserDeletion::class);
$this->app->bind(Contracts\ReleasesUserBilling::class, Actions\ReleaseUserBilling::class);
$this->app->bind(Contracts\CreatesTeams::class, Actions\CreateTeam::class);
$this->app->bind(Contracts\UpdatesTeams::class, Actions\UpdateTeam::class);
$this->app->bind(Contracts\DeletesTeams::class, Actions\SubscriptionGuardedDeleteTeam::class);
$this->app->bind(Contracts\TrashesTeams::class, Actions\SubscriptionGuardedTrashTeam::class);
$this->app->bind(Contracts\AddsTeamMembers::class, Actions\AddTeamMember::class);
$this->app->bind(Contracts\RemovesTeamMembers::class, Actions\RemoveTeamMember::class);
$this->app->bind(Contracts\InvitesTeamMembers::class, Actions\InviteTeamMember::class);
$this->app->bind(Contracts\AcceptsTeamInvitations::class, Actions\AcceptTeamInvitation::class);
$this->app->bind(Contracts\UpdatesTeamMemberRoles::class, Actions\UpdateTeamMemberRole::class);
$this->app->bind(Contracts\CreatesGuestUsers::class, Actions\CreateGuestUser::class);
$this->app->bind(Contracts\SendsOtpCodes::class, Actions\LogOtpProvider::class);
$this->app->bind(Contracts\VerifiesOtpCodes::class, Actions\CacheOtpVerifier::class);
$this->app->bind(Contracts\EnablesTwoFactorAuthentication::class, Actions\EnableTwoFactorAuthentication::class);
$this->app->bind(Contracts\ConfirmsTwoFactorAuthentication::class, Actions\ConfirmTwoFactorAuthentication::class);
$this->app->bind(Contracts\DisablesTwoFactorAuthentication::class, Actions\DisableTwoFactorAuthentication::class);
$this->app->bind(Contracts\GeneratesNewRecoveryCodes::class, Actions\GenerateNewRecoveryCodes::class);
$this->app->bind(Contracts\ResolvesSocialUsers::class, Actions\ResolveSocialUser::class);
$this->app->bind(Contracts\CreatesUsersFromProvider::class, Actions\CreateUserFromProvider::class);
$this->app->bind(Contracts\ConnectsSocialAccounts::class, Actions\ConnectSocialAccount::class);
$this->app->bind(Contracts\DisconnectsSocialAccounts::class, Actions\DisconnectSocialAccount::class);
$this->app->bind(Contracts\SetsUserPasswords::class, Actions\SetUserPassword::class);
All bindings use bind() (not singleton()), so a fresh instance is created per resolution.
TwoFactorAuthenticationProvider and Social\AppleProviderFactory are the only singletons in the
package.
Consumer Override#
Override any action by calling bind() after the package provider has run. Because
AppServiceProvider registers last, your binding wins:
// app/Providers/AppServiceProvider.php
use App\Actions\MagicStarter\CreateUser;
use AnilcanCakir\MagicStarter\Contracts\CreatesUsers;
public function register(): void
{
$this->app->bind(CreatesUsers::class, CreateUser::class);
}
All Contracts#
User Management#
CreatesUsers
Namespace: AnilcanCakir\MagicStarter\Contracts\CreatesUsers
Default action: Actions\CreateUser
public function create(array $input): Authenticatable;
Creates a newly registered user. $input contains the raw registration payload; the action is
responsible for validation, hashing, feature-gated fields (locale, timezone, newsletter), and
sending email verification when enabled.
CreatesGuestUsers
Namespace: AnilcanCakir\MagicStarter\Contracts\CreatesGuestUsers
Default action: Actions\CreateGuestUser
public function create(array $input): Authenticatable;
Creates or retrieves a guest user keyed by device_id. Guest users have null email and
null password. Use firstOrCreate semantics: calling this twice with the same device ID must
return the same user.
UpdatesUserProfiles
Namespace: AnilcanCakir\MagicStarter\Contracts\UpdatesUserProfiles
Default action: Actions\UpdateUserProfile
public function update(Authenticatable $user, array $input): void;
Validates and persists profile changes (name, email, avatar, locale, timezone) for the given user.
UpdatesUserPasswords
Namespace: AnilcanCakir\MagicStarter\Contracts\UpdatesUserPasswords
Default action: Actions\UpdateUserPassword
public function update(Authenticatable $user, array $input): void;
Validates current_password / password / password_confirmation and persists the new hashed
password.
DeletesUsers
Namespace: AnilcanCakir\MagicStarter\Contracts\DeletesUsers
Default action: Actions\DeleteUser
public function delete(Authenticatable $user): void;
Permanently deletes the user and all associated data. It is the irreversible end of the scheduled
deletion pipeline, so it runs from magic-starter:purge-deleted-users once the grace period is over,
not from DELETE user. The default action deletes the user's owned teams through DeletesTeams
(so its billing guard runs on each), detaches memberships, removes the linked social identities and
tokens, and, after the outermost transaction commits, revokes the Apple grants and deletes the
profile photo. It refuses a user who owns a shared team or whom a subscription bills; the purge
hands a shared team on first (always for an orphan, and for any user with
account_deletion.hand_on_shared_teams on). Any additional teardown belongs here.
SchedulesUserDeletion
Namespace: AnilcanCakir\MagicStarter\Contracts\SchedulesUserDeletion
Default action: Actions\ScheduleUserDeletion
public function schedule(Authenticatable $user, bool $orphan = false, bool $immediately = false): array;
The one entry point to the deletion pipeline, for a user's own request and for an identity provider
reporting the account deleted ($orphan = true). It refuses a user who owns a shared team (unless
account_deletion.hand_on_shared_teams is on) or a billing team, or whom a subscription bills
directly unless account_deletion.billing is release (422 owns_shared_teams,
team_has_active_subscription or subscription_active), then releases the user's billing through
ReleasesUserBilling when that is on, revokes every token, drops the push devices, stamps
deletion_scheduled_at and dispatches UserDeletionScheduled. Nothing is deleted in the request:
with $immediately a queued PurgeUserNow purges the account right away instead of after the
grace period. It returns the billing report, ['cancelled' => [], 'store' => []] unless billing is
released and something bills the user; ProfileController puts it in the 202 body as
data.billing. An implementation of this contract has to return it. See
Account Deletion.
ReleasesUserBilling
Namespace: AnilcanCakir\MagicStarter\Contracts\ReleasesUserBilling
Default action: Actions\ReleaseUserBilling
public function release(Authenticatable $user): array;
Ends what bills a user before their account is locked, when account_deletion.billing is
release. The default action cancels every Stripe subscription the user has that could still bill
or activate, through TrialCardGateway::cancel() (no proration, no final invoice), and reports a
store subscription (which only the customer can cancel, in the store) without touching it. A
subscription it cancels is ended in the local Cashier row too, because the purge and DeletesUsers
hold an account while a card subscription is valid and neither releases anything. Returns
['cancelled' => [['provider' => 'stripe', 'id' => 'sub_...']], 'store' => [['provider' => 'app_store', 'manage_url' => null]]], both lists empty for a user nothing bills. Throws
Support\BillingReleaseFailed when a rail refuses or cannot be reached; the scheduler answers that
with 422 billing_release_failed and locks nothing. It runs before the scheduler's own lock
transaction, so it may make remote calls; a caller that schedules inside a transaction of its own
(the Apple account-deleted handler) holds it open across them. See
Releasing Billing.
Social Login#
These contracts are bound whatever the social-login feature says, and only exercised while it is on.
A refusal is a SocialSignInRefused carrying a stable code.
| Contract | Default action | Role |
|---|---|---|
ResolvesSocialUsers |
Actions\ResolveSocialUser |
resolve(VerifiedIdentity, Request): Authenticatable. Maps an identity to its linked user, or creates one. Never links by email. |
CreatesUsersFromProvider |
Actions\CreateUserFromProvider |
create(VerifiedIdentity, Request): Authenticatable. Writes a new password-less user and its link atomically. |
ConnectsSocialAccounts |
Actions\ConnectSocialAccount |
connect(Authenticatable, VerifiedIdentity, ?string $refreshToken, ?string $clientId, ?bool $ownerConfirmed): Model. Refuses rather than moves a link. |
DisconnectsSocialAccounts |
Actions\DisconnectSocialAccount |
disconnect(Authenticatable, string $provider): void. Refuses the last sign-in method of a password-less user. |
SetsUserPasswords |
Actions\SetUserPassword |
set(Authenticatable, array $input): void. Writes a first password only. |
A replacement ConnectsSocialAccounts has to honour $ownerConfirmed: a link is provisional
(owner_confirmed = false) when it came with an unverified provider email, and a proof of mailbox
control (a password reset, an email verification) deletes it. See
Social Login.
Team Management#
All team contracts are only exercised when Features::hasTeamFeatures() returns true. Routes and
controllers for teams are conditionally registered.
CreatesTeams
Namespace: AnilcanCakir\MagicStarter\Contracts\CreatesTeams
Default action: Actions\CreateTeam
public function create(Authenticatable $user, array $input): Model;
Validates and creates a new team owned by $user. Returns the persisted team model.
UpdatesTeams
Namespace: AnilcanCakir\MagicStarter\Contracts\UpdatesTeams
Default action: Actions\UpdateTeam
public function update(Authenticatable $user, Model $team, array $input): void;
Validates and applies name/settings changes to $team. $user is the authenticated actor for
authorization checks.
DeletesTeams
Namespace: AnilcanCakir\MagicStarter\Contracts\DeletesTeams
Default action: Actions\SubscriptionGuardedDeleteTeam
public function delete(Model $team): void;
Permanently deletes the team: the purge. It removes the photo, the memberships and the invitations,
and on a team model that uses SoftDeletes it force deletes rather than trashes. The default is
Actions\SubscriptionGuardedDeleteTeam, which refuses while a store subscription or a valid Stripe
subscription is billing the team, for DELETE teams/{team} and the account purge alike. With the
restorable delete on, DELETE teams/{team} goes through
TrashesTeams instead, and this contract is what the magic-starter:purge-trashed-teams command and
the account purge call. A host that bound or extended the earlier StoreSubscriptionGuardedDeleteTeam
has to switch to it.
TrashesTeams
Namespace: AnilcanCakir\MagicStarter\Contracts\TrashesTeams
Default action: Actions\SubscriptionGuardedTrashTeam
public function trash(Model $team, ?int $restoreDays = null): void;
public function restore(Model $team): void;
The restorable half of a team delete, used only with the restorable-teams feature on. trash() clears
current_team_id for everyone on the team, cancels its pending invitations, writes restore_until
($restoreDays, else magic-starter.teams.restore_days) and soft deletes it; members stay attached. restore() clears
deleted_at and restore_until, and throws a ValidationException once restore_until is not in the
future. Both throw a LogicException for a team model that does not use SoftDeletes. The default
refuses to trash a team a payment rail is still billing, with the same sentences as DeletesTeams; a
host that needs more, such as a plan limit on restoring, extends Actions\TrashTeam or the guarded
class and rebinds the contract.
AddsTeamMembers
Namespace: AnilcanCakir\MagicStarter\Contracts\AddsTeamMembers
Default action: Actions\AddTeamMember
public function add(Authenticatable $user, Model $team, string $email, string $role): void;
Attaches an existing application user (looked up by $email) directly to the team pivot with the
given $role. Does not send an invitation; use InvitesTeamMembers for email-based flows.
RemovesTeamMembers
Namespace: AnilcanCakir\MagicStarter\Contracts\RemovesTeamMembers
Default action: Actions\RemoveTeamMember
public function remove(Authenticatable $user, Model $team, Model $teamMember): void;
Detaches $teamMember from $team. $user is the actor for authorization. The implementation
must prevent team owners from removing themselves.
InvitesTeamMembers
Namespace: AnilcanCakir\MagicStarter\Contracts\InvitesTeamMembers
Default action: Actions\InviteTeamMember
public function invite(Authenticatable $user, Model $team, string $email, string $role): Model;
Creates a TeamInvitation record with a random token and sends TeamInvitationNotification to
$email. Returns the invitation model. Acceptance is AcceptsTeamInvitations.
AcceptsTeamInvitations
Namespace: AnilcanCakir\MagicStarter\Contracts\AcceptsTeamInvitations
Default action: Actions\AcceptTeamInvitation
public function accept(Authenticatable $user, Model $invitation): void;
Joins the invitation's team as $user and deletes the invitation. The endpoint
(POST invitations/{token}/accept) looks the token up and checks that $user's email is the
invitation's, then calls this; the default action holds the rest. It returns only after a join,
and refuses everything else:
Support\TeamInvitationRefused(aValidationException) withrefusal()ofexpiredoralready_joined. The invitation is deleted either way. The endpoint answers these with its own 410 and 200.- Whatever
ensureCanJoin()throws, which the endpoint lets through as the validation error it is.
The join runs in one DB::transaction with the team row read FOR UPDATE, so two accepts for the
same team are serialised. To gate who may join (a member cap, say), extend the default action and
override its protected function ensureCanJoin(Model $team, Authenticatable $user): void. It is
empty by default, runs inside that transaction with $team locked and freshly read, after the
already-a-member check and before the attach, and is not called for an expired invitation or a
user who already belongs. Throw a ValidationException (with a stable code, as
RemoveTeamMember does) to refuse: the transaction rolls back and the invitation stays.
class CappedAcceptTeamInvitation extends AcceptTeamInvitation
{
protected function ensureCanJoin(Model $team, Authenticatable $user): void
{
if ($team->users()->count() >= 5) {
throw ValidationException::withMessages(['invitation' => 'This team is full.']);
}
}
}
UpdatesTeamMemberRoles
Namespace: AnilcanCakir\MagicStarter\Contracts\UpdatesTeamMemberRoles
Default action: Actions\UpdateTeamMemberRole
public function update(Authenticatable $user, Model $team, Model $teamMember, string $role): void;
Changes the pivot role for $teamMember on $team. $user is the actor for authorization.
Two-Factor Authentication#
2FA contracts work against the TwoFactorAuthenticatable trait on the user model. The
TwoFactorAuthenticationProvider singleton (Support\TwoFactorAuthenticationProvider) handles
TOTP secret/QR generation and code verification underneath.
EnablesTwoFactorAuthentication
Namespace: AnilcanCakir\MagicStarter\Contracts\EnablesTwoFactorAuthentication
Default action: Actions\EnableTwoFactorAuthentication
public function enable(mixed $user): array;
Generates a TOTP secret and recovery codes, stores them on the user (encrypted), and returns
['secret' => ..., 'qr_code' => ..., 'recovery_codes' => [...]]. 2FA is not active until
ConfirmsTwoFactorAuthentication succeeds.
ConfirmsTwoFactorAuthentication
Namespace: AnilcanCakir\MagicStarter\Contracts\ConfirmsTwoFactorAuthentication
Default action: Actions\ConfirmTwoFactorAuthentication
public function confirm(mixed $user, string $code): void;
Verifies the TOTP $code against the user's unconfirmed secret. On success, marks 2FA as
confirmed. Throws a validation exception if the code is invalid.
DisablesTwoFactorAuthentication
Namespace: AnilcanCakir\MagicStarter\Contracts\DisablesTwoFactorAuthentication
Default action: Actions\DisableTwoFactorAuthentication
public function disable(mixed $user): void;
Clears the TOTP secret, recovery codes, and confirmed-at timestamp from the user model.
GeneratesNewRecoveryCodes
Namespace: AnilcanCakir\MagicStarter\Contracts\GeneratesNewRecoveryCodes
Default action: Actions\GenerateNewRecoveryCodes
public function generate(mixed $user): array;
Generates a fresh set of recovery codes, stores them (encrypted) on the user, and returns the plain-text codes to be displayed once to the user.
OTP / Phone Verification#
These contracts are intentionally thin stubs in the default package: the default implementations log to disk or use a cache. Production deployments must override both contracts with real SMS/OTP-service integrations.
SendsOtpCodes
Namespace: AnilcanCakir\MagicStarter\Contracts\SendsOtpCodes
Default action: Actions\LogOtpProvider (logs to Laravel log, development only)
public function send(string $phone, string $code): void;
Delivers $code to $phone (E.164 format). Override with Twilio, Vonage, AWS SNS, or any other
SMS gateway.
VerifiesOtpCodes
Namespace: AnilcanCakir\MagicStarter\Contracts\VerifiesOtpCodes
Default action: Actions\CacheOtpVerifier (cache-backed, suitable for single-server setups)
public function verify(string $phone, string $code): bool;
Returns true when $code is the valid, unexpired code for $phone. The default implementation
stores codes in the Laravel cache. Override for distributed environments or third-party OTP
verification services.
Override Pattern#
To replace any action, create your class, implement the corresponding contract, then bind it in
AppServiceProvider::register():
<?php
namespace App\Providers;
use App\Actions\MagicStarter\CreateUser;
use App\Actions\MagicStarter\SendsOtpViaTwilio;
use AnilcanCakir\MagicStarter\Contracts\CreatesUsers;
use AnilcanCakir\MagicStarter\Contracts\SendsOtpCodes;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(CreatesUsers::class, CreateUser::class);
$this->app->bind(SendsOtpCodes::class, SendsOtpViaTwilio::class);
}
}
Your custom CreateUser must implement AnilcanCakir\MagicStarter\Contracts\CreatesUsers: that
is the only contract. Method signatures must match exactly.
Published Stubs#
The package ships pre-generated stub files for the most commonly customized actions. Publish them with:
php artisan vendor:publish --tag=magic-starter-stubs
This copies the following files into app/Actions/MagicStarter/:
| Stub file | Contract |
|---|---|
CreateUser.php |
CreatesUsers |
CreateTeam.php |
CreatesTeams |
UpdateUserProfile.php |
UpdatesUserProfiles |
UpdateUserPassword.php |
UpdatesUserPasswords |
DeleteUser.php |
DeletesUsers |
AddTeamMember.php |
AddsTeamMembers |
RemoveTeamMember.php |
RemovesTeamMembers |
InviteTeamMember.php |
InvitesTeamMembers |
UpdateTeam.php |
UpdatesTeams |
UpdateTeamMemberRole.php |
UpdatesTeamMemberRoles |
DeleteTeam.php |
DeletesTeams |
After publishing, register each stub in AppServiceProvider::register() as shown in the
Override Pattern section above. Stubs are skipped for SendsOtpCodes and
VerifiesOtpCodes because those require an external service and cannot be stubbed generically.
Action Implementation Guide#
Follow these conventions when writing custom action classes to stay consistent with the package patterns.
1. Implement exactly one contract#
class CreateUser implements CreatesUsers
{
public function create(array $input): Authenticatable { ... }
}
One class, one contract. Do not implement multiple contracts in a single class.
2. Validate inline with Validator::make#
Validation belongs inside the action, not in the caller:
$validated = Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255'],
'password' => ['required', 'string', 'min:8'],
])->validate();
validate() throws ValidationException automatically, which Laravel converts to a 422 response.
3. Resolve models via MagicStarter::*Model()#
Never hardcode App\Models\User or App\Models\Team:
$userModel = MagicStarter::userModel(); // resolves configured user model
$teamModel = MagicStarter::teamModel(); // resolves configured team model
$user = $userModel::query()->create($attributes);
This ensures the action works regardless of which model class the consumer has configured.
4. Gate feature-specific logic with Features#
if (Features::hasTeamFeatures()) {
// team-related side effects
}
if (Features::hasNewsletterSubscriptionFeatures()) {
// newsletter side effects
}
Never assume a feature is active. Guard every feature-specific branch.
5. Use numbered inline comments#
Document flow steps with sequential inline comments so the action reads like a recipe:
public function create(array $input): Authenticatable
{
// 1. Validate input.
$validated = Validator::make($input, $rules)->validate();
// 2. Build attributes.
$attributes = [...];
// 3. Persist the user.
$user = MagicStarter::userModel()::query()->create($attributes);
// 4. Handle side effects.
if (Features::hasNewsletterSubscriptionFeatures() && ...) { ... }
return $user;
}
6. Use Arr::get for optional fields#
use Illuminate\Support\Arr;
$locale = Arr::get($validated, 'locale', 'en');
Arr::get is null-safe and accepts a default, avoiding isset chains.
7. Return types must match the contract exactly#
If the contract declares array, return array. If it declares Model, return a Model (or
subclass). Do not widen or narrow the return type.
Related Documentation#
- Service Provider: where every default binding is registered.
- Installation: publishing the action stubs.
- Account Deletion: the deletion contracts in use.
- Teams: the team contracts in use.