VOOZH about

URL: https://deepwiki.com/mathsgod/light/3.1-app-class-initialization

⇱ App Class Initialization | mathsgod/light | DeepWiki


Loading...
Last indexed: 31 January 2026 (cf9511)
Menu

App Class Initialization

Overview

The Light\App class constructor performs a comprehensive initialization sequence that bootstraps all framework subsystems in a specific order. This initialization occurs once at application startup and prepares the framework for handling HTTP requests. The constructor at src/App.php59-147 executes nine distinct initialization phases, each building upon the previous to create a fully configured application environment.

The initialization sequence ensures that:

  • Environment configuration (timezone) is applied first
  • The dependency injection container is created before any services
  • Controllers are registered before GraphQL schema generation
  • The application mode determines caching and debug behavior
  • RBAC and menu systems are loaded with complete configuration data
  • File system adapters are initialized last since they depend on configuration

Related pages:

  • For request processing after initialization: see page 3.2 (Request Processing Pipeline)
  • For GraphQL schema creation details: see page 3.3 (GraphQL Integration)
  • For RBAC permission loading: see page 3.4 (RBAC Integration)
  • For filesystem configuration: see page 3.5 (File System Management)

Sources: src/App.php59-147


Properties Initialized by Constructor

The constructor initializes eight protected properties that form the core infrastructure of the application:

PropertyTypeInitialized AtDescription
$containerLeague\Container\ContainerLine 68Dependency injection container for autowiring
$serverLight\ServerLine 70HTTP server with routing and middleware pipeline
$modestringLines 107-119Application mode: "dev" or "prod" from Config model
$cacheCacheInterfaceLine 123Symfony cache adapter from GraphQL server
$factorySchemaFactoryLine 124GraphQLite schema factory for GraphQL API generation
$rbacRbacLine 128Role-based access control system
$menusarrayLine 130Application menu structure loaded from YAML and database
$mountManagerMountManagerLine 144Flysystem mount manager for multi-backend file operations

Two additional properties are set during request processing:

  • $auth_service (type: Auth\Service) - Created per-request in process() method

Sources: src/App.php43-57 src/App.php68 src/App.php70 src/App.php107-119 src/App.php123-124 src/App.php128 src/App.php130 src/App.php144


Initialization Phase Diagram

The constructor executes nine sequential initialization phases, each preparing infrastructure for subsequent phases:


Diagram: Constructor Initialization Phases

Sources: src/App.php59-147


Phase 1: Timezone Configuration

The constructor's first operation checks for a timezone configuration in the environment and applies it globally using PHP's date_default_timezone_set():


Diagram: Timezone Setup Logic

This ensures all date/time operations throughout the application use a consistent timezone. The timezone is typically set in the .env file as TZ=America/New_York or similar.

Sources: src/App.php62-66


Phase 2: Dependency Injection Container

The constructor creates a League\Container\Container instance which serves as the application's dependency injection container:


The container is stored in the $container property and used for:

  • Autowiring constructor dependencies in controllers
  • Registering singleton services (RBAC, MountManager, etc.)
  • Runtime service resolution during GraphQL execution

The container does not use a reflection container delegate (lines 99-101 are commented out), meaning services must be explicitly registered.

Sources: src/App.php68 src/App.php99-101


Phase 3: HTTP Server Creation

The constructor instantiates a Light\Server object, passing the container:


The Light\Server class (from the mathsgod/light-server package) provides:

  • PSR-15 middleware pipeline management
  • HTTP request routing via League Router
  • Integration with the dependency injection container

The server is stored in the $server property for later use in the run() method.

Sources: src/App.php70


Phase 4: Middleware Pipeline Registration

The App class registers itself as middleware in the server's pipeline:


This enables the process() method to intercept all requests before they reach the terminal handler. The App class implements MiddlewareInterface, allowing it to:

  • Handle OPTIONS requests for CORS preflight
  • Process file uploads via UploadMiddleware
  • Create and inject the Auth\Service per request
  • Add request and auth service to the container

Sources: src/App.php72


Phase 5: Controller and Service Registration

The constructor registers the App instance itself and 24 controller classes in the dependency injection container:


Diagram: Controller Registration in Container

Standard Controller Registration

Most controllers use simple registration at src/App.php74-97 Each call to $this->container->add(ClassName::class) enables the GraphQL schema factory to autowire constructor dependencies when instantiating controllers during query execution.

Registered controller classes:

  • Light\Controller\AppController - Application configuration mutations
  • Light\Controller\SystemController - System information queries
  • Light\Controller\AuthController - Authentication mutations
  • Light\Controller\UserController - User CRUD operations
  • Light\Controller\RoleController - Role management
  • Light\Controller\EventLogController - Audit log queries
  • Light\Controller\UserRoleController - User-role assignments
  • Light\Controller\PermissionController - Permission management
  • Light\Controller\ConfigController - Configuration CRUD
  • Light\Controller\UserLogController - User session logs
  • Light\Controller\MailLogController - Email audit logs
  • Light\Controller\TranslateController - Translation management
  • Light\Controller\WebAuthnController - WebAuthn/FIDO2 operations
  • Light\Controller\SystemValueController - System value management
  • Light\Controller\MyFavoriteController - User favorites
  • Light\Controller\FileSystemController - File operations
  • Light\Controller\RevisionController - Revision history queries
  • Light\Controller\DatabaseController - Database management
  • Light\Controller\DriveController - Drive configuration
  • Light\Controller\CustomFieldController - Custom field management

Factory-Based Registration

The FileManagerController uses a factory closure at src/App.php86-88 to inject $this->getDrive(0):


This ensures the controller receives the first configured filesystem drive (index 0) as a constructor dependency.

Model Container Configuration

After controller registration, the container is provided to the Light\Model base class at src/App.php103 via static method:


This static call enables all model classes extending Light\Model to access the container for dependency injection in their instance methods.

Sources: src/App.php74-103


Phase 6: Application Mode Detection

The constructor attempts to load the application mode ("dev" or "prod") from the Config model:


Diagram: Mode Detection Logic

The mode value determines two critical parameters:

Mode$debug$defaultLifetimeBehavior
"prod"false0No debug output, cache indefinitely
"dev"true15Include debug/trace, 15-second cache TTL
Exceptiontrue15Database not ready, default to dev mode

The mode is stored in the $mode property and later checked by isDevMode() to control debug output in responses.

Sources: src/App.php104-119


Phase 7: GraphQL Server Initialization

The constructor creates a Light\GraphQL\Server instance with the mode-dependent parameters:


The GraphQL server (from the mathsgod/light-graphql package) provides:

  • Symfony cache adapter for schema caching
  • GraphQLite SchemaFactory for annotation-based schema generation
  • Integration with the dependency injection container

Cache Extraction

The cache is extracted and stored:


This cache is used throughout the application for configuration caching and GeoIP lookups.

Schema Factory Configuration

The schema factory is extracted and configured:


Configuration steps:

  1. Namespace Registration - addNamespace("Light") enables the factory to scan the Light namespace for GraphQL types, queries, and mutations
  2. Type Mapper Factory - Adds Light\Db\GraphQLite\Mappers\TypeMapperFactory to automatically map database model classes to GraphQL types

The factory is later used in the handle() method to create the GraphQL schema via $this->factory->createSchema().

Sources: src/App.php121-126


Phase 8: RBAC and Menu Loading

The constructor initializes the RBAC system and loads menu configurations:


RBAC Initialization

The loadRbac() method at src/App.php306-366 performs a complex initialization sequence:


Diagram: RBAC Loading Sequence

The RBAC loading creates four system roles with inheritance:

RoleParentSystem Permission
Administrators(root)#administrators
Power UsersAdministrators#power users
UsersPower Users#users
EveryoneUsers#everyone

Additional roles are loaded from:

  • Role model - Custom role hierarchies from database
  • permissions.yml - Default permissions mapped to roles
  • Permission model - Runtime permissions assigned to roles/users
  • UserRole model - User-to-role assignments

The loaded RBAC instance is registered in the container at src/App.php365:


Menu Loading

The loadMenu() method at src/App.php174-191 loads menu structures from multiple sources:


Diagram: Menu Loading Flow

Menu sources in load order:

  1. menus.yml - System default menus with permissions
  2. Config model (name="menus") - Custom menus from database
  3. Conditional File Manager menu - Added if file_manager feature is enabled

Sources: src/App.php128-130 src/App.php306-366 src/App.php174-191 src/App.php365


Phase 9: Filesystem Mount Manager Setup

The final initialization phase creates a MountManager with all configured filesystems:


Diagram: Mount Manager Initialization

Filesystem Configuration Loading

The getFSConfig() method at src/App.php695-715 loads filesystem configurations:


Diagram: Filesystem Configuration Loading

Sources: src/App.php695-715

Filesystem Creation

For each configuration, getFS(int $index) at src/App.php717-787 creates the appropriate Flysystem instance based on the type field:

Type StringAdapter ClassCode LocationPackage
"local"League\Flysystem\Local\LocalFilesystemAdapterLines 723-742league/flysystem
"aliyun-oss"AlphaSnow\Flysystem\Aliyun\AliyunFactoryLines 745-747alphasnow/aliyun-oss-flysystem
"s3"League\Flysystem\AwsS3V3\AwsS3V3AdapterLines 749-778league/flysystem-aws-s3-v3
"hostlink"HL\Storage\AdapterLines 780-784hostlink/hostlink-storage-adapter

Each adapter is wrapped in a League\Flysystem\Filesystem instance with configuration-specific options (visibility, public URLs, etc.).

Mount Manager Registration

The MountManager is created at src/App.php144 and registered in two locations:


Diagram: Mount Manager Registration

This dual registration enables access via:

  • $app->getMountManager() - Direct property accessor at src/App.php149-152
  • Constructor injection - GraphQL controllers can type-hint MountManager::class

The mount manager enables filesystem access via protocol prefixes like local://path/to/file or s3://bucket/key using the name field from configuration as the protocol.

Sources: src/App.php134-146 src/App.php149-152 src/App.php717-787


Initialization Completion

After all nine phases complete, the App instance is fully initialized with:

  • Timezone configured globally
  • Dependency injection container populated with 24+ services
  • HTTP server ready with middleware pipeline
  • Application mode detected (dev/prod)
  • GraphQL schema factory configured
  • RBAC system loaded with roles, permissions, and user assignments
  • Menu system loaded from YAML and database
  • Filesystem mount manager ready with all configured backends

The constructor returns control to the calling code (typically the entry point script), and the App instance is ready to process HTTP requests via the run() method.

Sources: src/App.php59-147


Dual Role: Middleware and Request Handler

The Light\App class implements both MiddlewareInterface and RequestHandlerInterface (declared at src/App.php38), enabling it to function in two distinct roles within the request lifecycle.

Middleware Role: process() Method

The process() method src/App.php500-537 acts as middleware that prepares the request before passing it to the next handler:


Diagram: Middleware Processing Flow

Key responsibilities in the middleware phase:

  • CORS Handling: Returns empty 200 response for OPTIONS requests
  • Body Parsing: Decodes JSON request body if not already parsed
  • File Upload Processing: Uses GraphQL\Upload\UploadMiddleware to handle multipart uploads
  • Authentication Setup: Creates Auth\Service instance with JWT validation
  • Container Registration: Adds request and auth service to DI container
  • GraphQL Configuration: Sets authentication and authorization services on schema factory

Request Handler Role: handle() Method

The handle() method src/App.php154-170 acts as the terminal request handler that executes the GraphQL query and returns the response:


Diagram: Request Handler Flow

The handler performs the following operations:

  1. Query Execution - Calls execute() which parses GraphQL query/variables from request body
  2. Schema Creation - Uses $this->factory->createSchema() to generate schema from annotations
  3. GraphQL Execution - Invokes GraphQL::executeQuery() with schema, query, and Context
  4. Response Formatting - Returns JsonResponse with conditional debug information based on $this->mode

Sources: src/App.php154-170 src/App.php500-537 src/App.php567-579


Service Registration and Container Setup

The constructor registers numerous services and controllers in the League Container, making them available for dependency injection throughout the application:

Controller Registration

All GraphQL controllers are registered as container services src/App.php72-95:


Diagram: Controller Registration in DI Container

Runtime Service Registration

During the process() phase, additional services are registered dynamically src/App.php527-528:

  • ServerRequestInterface::class: The current PSR-7 request object
  • Auth\Service::class: The authentication service for the current request
  • Rbac::class: The RBAC system (registered in loadRbac() at src/App.php359)
  • League\Flysystem\MountManager::class: File system mount manager src/App.php143

Special Factory Registration

The FileManagerController uses a factory function to inject the default drive src/App.php84-86:


Sources: src/App.php72-95 src/App.php527-528 src/App.php359 src/App.php143 src/App.php84-86


Integration Points

The Light\App class serves as the integration hub for all major subsystems. The following diagram shows the relationships between the App class and its dependencies:


Diagram: App Class Integration with Subsystems

Key Accessor Methods

The App class provides accessor methods for major subsystems:

MethodReturn TypePurpose
getContainer()ContainerInterfaceAccess the DI container
getSchemaFactory()SchemaFactoryAccess GraphQL schema factory
getAuthService()Auth\ServiceAccess authentication service
getRbac()RbacAccess RBAC system
getCache()CacheInterfaceAccess Symfony cache
getDatabase()AdapterCreate database adapter via Light\Db\Adapter::Create()
getMailer()MailerCreate configured PHPMailer instance
getDrive(int $index)DriveGet file system drive by index
getFS(int $index)FilesystemGet Flysystem instance by index

Sources: src/App.php479-487 src/App.php489-492 src/App.php474-477 src/App.php222-225 src/App.php217-220 src/App.php227-279 src/App.php840-845 src/App.php723-793


Public API Methods

The App class exposes several public methods for querying and managing application state:

Configuration Queries

MethodReturn TypeDescription
isDevMode()boolReturns true if mode is not "prod"
isTwoFactorAuthentication()boolChecks if 2FA is enabled via Config model
isFileManagerEnabled()boolChecks if file manager feature is enabled
isRevisionEnabled(string $model)boolChecks if revision tracking is enabled for a model
hasFavorite()boolChecks if MyFavorite table exists

Token Management

MethodReturn TypeDescription
getAccessTokenExpire()intReturns access token lifetime in seconds (default: 900)
getRefreshTokenExpire()intReturns refresh token lifetime in seconds (default: 604800)
setAccessTokenCookie(string $token)voidSets access token as HTTP-only cookie
setRefreshTokenCookie(string $token)voidSets refresh token as HTTP-only cookie
userLogin(User $user)voidPerforms complete login: creates JWT, sets cookies, logs to UserLog

Menu and Permission Management

MethodReturn TypeDescription
getMenus()arrayReturns hierarchical menu structure
getFlatMenus()arrayReturns flattened menu array without children
addMenus(array $menus)voidAdds menus to the menu array
getCustomMenus()arrayLoads custom menus from Config model
getPermissions()arrayDiscovers all permissions from @Right annotations and menus
addRolePermissions(string $role, array $permissions)voidAdds permissions to a role in RBAC

Utility Methods

MethodReturn TypeDescription
run()voidStarts the HTTP server with configured routes
getDriveResponse(int $index, string $path)ResponseInterfaceServes a file from a drive as HTTP response
getRpId()stringReturns WebAuthn Relying Party ID
getRpEntity()PublicKeyCredentialRpEntityReturns WebAuthn RP entity
getIpLocation(string $ip)arrayGets geolocation data for IP address (cached)

Sources: src/App.php575-578 src/App.php469-472 src/App.php588-594 src/App.php795-808 src/App.php693-699 src/App.php596-606 src/App.php608-623 src/App.php625-640 src/App.php642-691 src/App.php205-208 src/App.php188-203 src/App.php210-215 src/App.php580-586 src/App.php386-466 src/App.php288-298 src/App.php849-904 src/App.php534-558 src/App.php810-820 src/App.php822-838 src/App.php906-921


Summary

The Light\App class is the architectural cornerstone of the Light framework, serving multiple critical roles:

  1. PSR-15 Middleware: Intercepts requests to set up authentication, file uploads, and container services
  2. PSR-15 Request Handler: Executes GraphQL queries and formats responses
  3. Service Orchestrator: Manages the lifecycle of all major subsystems (RBAC, cache, file systems)
  4. Dependency Injection Hub: Registers and provides access to 20+ controllers and core services
  5. Configuration Manager: Loads and provides access to system configuration from multiple sources

The class is instantiated once at application startup, initializes all subsystems in its constructor, and then processes all incoming HTTP requests through its middleware/handler pipeline. Its central position makes it the primary integration point for all framework functionality.

Sources: src/App.php1-922

Refresh this wiki

On this page