VOOZH about

URL: https://deepwiki.com/hypervel/auth/5-contracts-and-interfaces

⇱ Contracts and Interfaces | hypervel/auth | DeepWiki


Loading...
Menu

Contracts and Interfaces

Purpose and Scope

This page provides an overview of all contracts (interfaces) defined in the hypervel/auth package and explains their purpose, relationships, and role in the system architecture. Contracts form the foundation of the authentication and authorization system, enabling dependency injection, testability, and extensibility.

For detailed documentation of specific contracts and their implementations, see:


Overview

The hypervel/auth package defines seven core contracts located in the src/Contracts/ namespace. These interfaces establish the contract between different components of the authentication and authorization system, allowing implementations to be swapped without modifying dependent code.

Why Contracts Matter

Contracts provide several key benefits:

  1. Dependency Inversion: High-level components depend on abstractions rather than concrete implementations
  2. Testability: Mock implementations can be easily injected for testing
  3. Extensibility: Custom implementations can be registered without modifying core code
  4. Type Safety: PHP type hints ensure correct method signatures
  5. Documentation: Interfaces serve as self-documenting API specifications

Contract Categories

The contracts are organized into two primary categories based on their role in the system:

CategoryContractsPurpose
AuthenticationAuthenticatable, Guard, StatefulGuard, UserProvider, FactoryDefine how users are identified, validated, and managed
AuthorizationAuthorizable, GateDefine how access permissions are checked and enforced

Contract Hierarchy

Complete Contract Structure


Sources: src/Contracts/Guard.php1-39 src/Contracts/Authenticatable.php1-24 src/Contracts/UserProvider.php1-26 src/Contracts/Factory.php1-19 src/Contracts/Authorizable.php1-14


Authentication Contracts

Authenticatable Interface

The Authenticatable contract defines the interface that all user models must implement. It provides methods for retrieving the user's unique identifier and authentication password.

Location: src/Contracts/Authenticatable.php8-23

Key Methods:

  • getAuthIdentifierName(): Returns the name of the unique identifier field (e.g., 'id')
  • getAuthIdentifier(): Returns the user's unique identifier value
  • getAuthPassword(): Returns the user's hashed password

See: Authenticatable Contract for detailed documentation.


Guard Interface

The Guard contract defines the base interface that all authentication guards must implement. Guards are responsible for authenticating users and maintaining authentication state.

Location: src/Contracts/Guard.php7-38

Key Methods:

  • check(): Determine if user is authenticated
  • guest(): Determine if user is a guest (not authenticated)
  • user(): Get the currently authenticated user
  • id(): Get the authenticated user's identifier
  • validate(array $credentials): Validate credentials without authentication
  • setUser(Authenticatable $user): Manually set the authenticated user

See: Guard Contract for detailed documentation including StatefulGuard.


UserProvider Interface

The UserProvider contract defines how users are retrieved from persistent storage and how credentials are validated.

Location: src/Contracts/UserProvider.php8-25

Key Methods:

  • retrieveById($identifier): Retrieve user by unique identifier
  • retrieveByCredentials(array $credentials): Retrieve user by credentials (e.g., username)
  • validateCredentials(Authenticatable $user, array $credentials): Validate password against user

See: UserProvider Contract for detailed documentation.


Factory Interface

The Factory contract defines the interface for creating and managing guard instances. The AuthManager class implements this contract.

Location: src/Contracts/Factory.php7-18

Key Methods:

  • guard(?string $name): Get or create a guard instance by name
  • shouldUse(string $name): Set the default guard name

See: Factory Contract for detailed documentation.


Authorization Contracts

Authorizable Interface

The Authorizable contract defines the interface for entities (typically users) that can be authorized to perform actions.

Location: src/Contracts/Authorizable.php7-13

Key Methods:

  • can(iterable|string $abilities, mixed $arguments): Check if entity has given abilities

See: Authorizable Contract for detailed documentation.


Contract Implementation Mapping

Authentication Flow with Contracts


Sources: src/Contracts/Factory.php1-19 src/Contracts/Guard.php1-39 src/Contracts/UserProvider.php1-26 src/Contracts/Authenticatable.php1-24


Authorization Flow with Contracts


Sources: src/Contracts/Authorizable.php1-14 src/Access/Authorizable.php1-44 src/Access/AuthorizesRequests.php1-77


Supporting Traits

While not contracts themselves, several traits provide default implementations of contract methods:

Authenticatable Trait

Provides default implementation of the Authenticatable contract for Eloquent models.

Namespace: Hypervel\Auth\Authenticatable

See: Authenticatable Contract for usage details.


Authorizable Trait

Provides implementation of the Authorizable contract with convenient authorization methods.

Location: src/Access/Authorizable.php10-43

Methods Provided:

  • can(iterable|string $abilities, mixed $arguments): Check abilities
  • canAny(iterable|string $abilities, mixed $arguments): Check any ability
  • cant(iterable|string $abilities, mixed $arguments): Check inability (negation)
  • cannot(iterable|string $abilities, mixed $arguments): Alias for cant()

All methods delegate to the Gate contract implementation via dependency injection.

Sources: src/Access/Authorizable.php1-44


AuthorizesRequests Trait

Provides authorization methods for controller classes.

Location: src/Access/AuthorizesRequests.php11-76

Methods Provided:

  • authorize(mixed $ability, mixed $arguments): Authorize for current user
  • authorizeForUser(?Authenticatable $user, mixed $ability, mixed $arguments): Authorize for specific user
  • parseAbilityAndArguments(mixed $ability, mixed $arguments): Parse ability name from controller method
  • normalizeGuessedAbilityName(string $ability): Map controller methods to abilities
  • resourceAbilityMap(): Define controller method to ability mappings

The trait automatically maps RESTful controller methods to authorization abilities:

Controller MethodAbility
indexviewAny
showview
create, storecreate
edit, updateupdate
destroydelete

Sources: src/Access/AuthorizesRequests.php1-77


Contract Relationships

Dependency Graph


Sources: src/Contracts/Factory.php1-19 src/Contracts/Guard.php1-39 src/Contracts/UserProvider.php1-26 src/Contracts/Authenticatable.php1-24 src/Contracts/Authorizable.php1-14


Contract Usage Patterns

Implementing Custom Guards

To create a custom guard, implement the Guard contract (or StatefulGuard for session-based guards):


Register the guard via AuthManager::extend().


Implementing Custom User Providers

To create a custom user provider, implement the UserProvider contract:


Register the provider via AuthManager::provider().


Making Models Authenticatable

To make a model authenticatable, implement the Authenticatable contract:


Or use the Authenticatable trait for default implementation.


Making Models Authorizable

To enable authorization checks on a model, implement the Authorizable contract:


This enables calls like $user->can('edit-post', $post).


Type Hierarchy Table

ContractNamespaceKey MethodsImplemented By
AuthenticatableHypervel\Auth\ContractsgetAuthIdentifier(), getAuthPassword()User models, GenericUser
GuardHypervel\Auth\Contractscheck(), user(), validate()SessionGuard, JwtGuard, RequestGuard
StatefulGuardHypervel\Auth\ContractsExtends Guard, adds login(), logout()SessionGuard
UserProviderHypervel\Auth\ContractsretrieveById(), validateCredentials()EloquentUserProvider, DatabaseUserProvider
FactoryHypervel\Auth\Contractsguard(), shouldUse()AuthManager
AuthorizableHypervel\Auth\Contractscan()User models (via trait)
GateHypervel\Auth\Contractsallows(), denies(), authorize()Gate class

Sources: src/Contracts/Guard.php1-39 src/Contracts/Authenticatable.php1-24 src/Contracts/UserProvider.php1-26 src/Contracts/Factory.php1-19 src/Contracts/Authorizable.php1-14


Contract-Based Dependency Injection

The contracts enable dependency injection throughout the system. The ConfigProvider registers contract bindings in the DI container:


This allows components to depend on contracts rather than concrete implementations:


The DI container automatically resolves these dependencies at runtime.


Method Signature Patterns

Guard Contract Pattern

All guard methods follow a consistent pattern:

  • Check methods (check(), guest()): Return bool
  • Retrieval methods (user(), id()): Return nullable values
  • Validation methods (validate()): Accept credentials array, return bool
  • Setter methods (setUser()): Accept Authenticatable, return void

Sources: src/Contracts/Guard.php7-38


UserProvider Contract Pattern

All provider methods use type-safe signatures:

  • Retrieval methods: Return ?Authenticatable (nullable)
  • Validation methods: Return bool
  • Credential parameters: Use array type for flexibility

Sources: src/Contracts/UserProvider.php8-25


Authorizable Contract Pattern

Authorization methods accept flexible parameters:

  • Abilities: Accept iterable|string for single or multiple checks
  • Arguments: Accept mixed for resource-specific data
  • Return type: Always bool

Sources: src/Contracts/Authorizable.php7-13 src/Access/Authorizable.php15-42


Summary

The contracts in hypervel/auth establish a clear separation between interface and implementation, enabling:

  1. Flexibility: Multiple authentication strategies (session, JWT, custom)
  2. Testability: Mock implementations for unit testing
  3. Extensibility: Custom guards, providers, and authorization logic
  4. Type Safety: Compile-time checks for correct usage
  5. Dependency Injection: Loose coupling between components

For implementation details of each contract, refer to the child pages listed at the beginning of this document.

Refresh this wiki

On this page