VOOZH about

URL: https://deepwiki.com/hypervel/auth/5.4-factory-contract

⇱ Factory Contract | hypervel/auth | DeepWiki


Loading...
Menu

Factory Contract

The Factory contract defines the interface for guard resolution and management in the authentication system. It specifies the methods that any authentication factory must implement to provide guard instances and manage default guard selection. The AuthManager class implements this contract to serve as the primary factory for creating and caching guard instances.

For detailed information about the AuthManager implementation, see AuthManager. For information about guards themselves, see Guards.

Sources: src/Contracts/Factory.php1-19


Interface Definition

The Factory interface is located at src/Contracts/Factory.php1-19 and defines two core methods:

MethodReturn TypePurpose
guard(?string $name = null)Guard|StatefulGuardRetrieves a guard instance by name, or the default guard if no name is provided
shouldUse(string $name)voidSets the default guard that the factory should serve for subsequent requests

These methods provide the minimum contract for any authentication factory implementation. The interface ensures consistent guard management across different implementations.

Sources: src/Contracts/Factory.php9-18


Implementation Architecture

The AuthManager class at src/AuthManager.php22 implements the Factory contract. The implementation uses the factory pattern to create, cache, and manage guard instances.

Factory Pattern Implementation


Sources: src/Contracts/Factory.php1-19 src/AuthManager.php22-255


Guard Resolution Method

The guard() method is the primary entry point for obtaining guard instances. It implements a caching mechanism to ensure guard instances are reused within the application lifecycle.

Resolution Flow


The resolution process follows these steps:

  1. Name Resolution src/AuthManager.php62: If no name is provided, uses getDefaultDriver() to determine the guard name
  2. Cache Check src/AuthManager.php64: Checks if the guard already exists in the guards array
  3. Guard Resolution src/AuthManager.php72-91: If not cached, calls resolve() to create the guard:
    • Retrieves configuration from auth.guards.{name}
    • Checks for custom creators in customCreators array
    • Falls back to built-in driver methods like createSessionDriver() or createJwtDriver()
  4. Caching src/AuthManager.php64: Stores the created guard in the cache for future use

Sources: src/AuthManager.php60-65 src/AuthManager.php72-91


Built-in Driver Creation

The AuthManager provides factory methods for creating built-in guard types. These methods are called by the resolve() method when a matching driver is configured.

Session Guard Creation

The createSessionDriver() method at src/AuthManager.php104-111 creates SessionGuard instances:

SessionGuard = createSessionDriver(name, config)
 ├── name: Guard name
 ├── UserProvider: Created via createUserProvider()
 └── SessionContract: Injected from container

Sources: src/AuthManager.php104-111

JWT Guard Creation

The createJwtDriver() method at src/AuthManager.php116-125 creates JwtGuard instances:

JwtGuard = createJwtDriver(name, config)
 ├── name: Guard name
 ├── UserProvider: Created via createUserProvider()
 ├── JWTManager: Injected from container
 ├── RequestInterface: Injected from container
 └── ttl: From jwt.ttl config (default 120)

Sources: src/AuthManager.php116-125


Default Guard Management

The shouldUse() method implements the Factory contract's requirement to set the default guard. This method coordinates several operations to ensure the default guard is properly configured across the authentication system.

Default Guard Flow


The shouldUse() method at src/AuthManager.php166-175 performs three operations:

  1. Default Resolution src/AuthManager.php168: Resolves the guard name using getDefaultDriver() if null provided
  2. Default Storage src/AuthManager.php170: Calls setDefaultDriver() to store the default in Hyperf Context
  3. User Resolver Update src/AuthManager.php172-174: Updates the user resolver to use the new default guard

Context-based Default Storage

The default guard is stored in Hyperf Context at key __auth.defaults.guard src/AuthManager.php182 This provides request-scoped default guard configuration, allowing different guards to be used as defaults in different contexts or requests.

MethodContext KeyPurpose
getDefaultDriver()__auth.defaults.guardRetrieves the request-scoped default guard name
setDefaultDriver()__auth.defaults.guardStores the request-scoped default guard name

Sources: src/AuthManager.php154-183


Custom Guard Registration

The Factory implementation supports extension through custom guard registration. This allows developers to add new guard types without modifying the core AuthManager class.

Extension Methods


The extend() method at src/AuthManager.php132-137 registers custom guard creators:

  • Parameters: Driver name and creator closure
  • Storage: Adds creator to customCreators array
  • Resolution: Custom creators are checked first during guard resolution

The viaRequest() method at src/AuthManager.php188-193 provides a convenient way to register callback-based guards:

  • Creates a RequestGuard instance using the provided callback
  • Internally uses extend() to register the guard creator
  • Useful for simple authentication strategies that don't require full guard implementations

Sources: src/AuthManager.php132-137 src/AuthManager.php188-193


Magic Method Delegation

The AuthManager implements the __call() magic method to delegate undefined method calls to the default guard instance. This provides a convenient API where the manager can be used as if it were a guard itself.


Example delegation at src/AuthManager.php251-254:

  • Call: $authManager->user()
  • Translates to: $authManager->guard()->user()

This allows the AuthManager to act as a facade for the default guard, simplifying common authentication operations.

Sources: src/AuthManager.php251-254


Factory Usage Patterns

Basic Guard Retrieval

// Get default guard
$guard = $factory->guard();

// Get named guard
$apiGuard = $factory->guard('api');
$webGuard = $factory->guard('web');

Setting Default Guard

// Set 'api' as default for this request context
$factory->shouldUse('api');

// Subsequent calls to guard() will return 'api' guard
$guard = $factory->guard();

Custom Guard Registration

// Register custom guard driver
$factory->extend('custom', function ($name, $config) {
 return new CustomGuard(...);
});

// Register callback-based guard
$factory->viaRequest('token', function ($request) {
 return User::findByToken($request->bearerToken());
});

Sources: src/AuthManager.php60-65 src/AuthManager.php166-175 src/AuthManager.php132-137 src/AuthManager.php188-193


Contract Implementation Summary

Factory MethodAuthManager ImplementationKey Features
guard(?string)src/AuthManager.php60-65Guard caching, default resolution, driver creation
shouldUse(string)src/AuthManager.php166-175Context-based default storage, user resolver update

Additional implementation features:

The Factory contract provides a clean abstraction for guard management while the AuthManager implementation adds sophisticated caching, extensibility, and delegation features.

Sources: src/Contracts/Factory.php1-19 src/AuthManager.php22-255