App

Introduction

The App class is the central component of JiFramework. It serves as the main entry point to the framework's functionalities, initializing and providing access to all the core classes and services. By creating an instance of the App class, you gain immediate access to various utilities and helpers without the need to instantiate them individually.

This class simplifies the development process by managing dependencies and ensuring that all components are properly configured and ready to use. It integrates essential features such as database connections, authentication, session management, error handling, caching, and more.

Method: __construct(string $connectionName = 'primary')

Description: Initializes the App instance and sets up all the core components of JiFramework. This includes starting the session, setting up error handling, enforcing rate limits, checking access controls, and initializing various helpers and utilities.

Parameters:

  • $connectionName (string, optional): The name of the database connection to use. Defaults to 'primary'.

Returns: An instance of the App class.

Usage:

require __DIR__ . '/vendor/autoload.php';

use JIFramework\Core\App\App;

// Create a new App instance
$app = new App();

// Now you can access various components
$db = $app->db;
$auth = $app->auth;
$logger = $app->logger;
 

Explanation:

  • Session Initialization: The constructor starts the session by calling Config::initSession().
  • Error Handling: Sets up the ErrorHandler and registers it to handle errors and exceptions.
  • Rate Limiting: Initializes the RateLimiter and enforces rate limits based on configuration.
  • Access Control: Initializes AccessControl and checks if the current user has permission to access the application.
  • Component Initialization: Instantiates all the core components and assigns them to public properties for easy access.

exit()

Method: exit(int $statusCode = 200, string $msg = ''): void

Description: Exits the script execution with the provided HTTP status code and message. This method sends an HTTP response code and outputs a message before terminating the script.

Parameters:

  • $statusCode (int, optional): The HTTP status code to send. Must be a valid HTTP status code (100-599). Defaults to 200.
  • $msg (string, optional): The message to send in the response body. Defaults to an empty string.

Returns: void

Usage:

// Inside your application logic
if ($someErrorCondition) {
    $app->exit(400, 'Bad Request: Invalid parameters.');
}

// Or simply exit with a custom message
$app->exit(500, 'Internal Server Error: An unexpected error occurred.');
 

Explanation:

  • The method validates the provided $statusCode to ensure it's within the valid HTTP status code range.
  • Sets the HTTP response code using http_response_code($statusCode).
  • Outputs the provided $msg.
  • Terminates script execution using exit.

Public Properties (Components)

The App class initializes and exposes various components as public properties. These components provide a wide range of functionalities essential for building web applications.

Components List

  • $db (QueryBuilder): Database query builder for interacting with the database.
  • $auth (Auth): Authentication manager for handling user and admin authentication.
  • $sessionManager (SessionManager): Manages session data, CSRF tokens, and flash messages.
  • $dateTimeHelper (DateTimeHelper): Utilities for date and time operations.
  • $fileManager (FileManager): Handles file uploads, deletions, and manipulations.
  • $stringHelper (StringHelper): String manipulation utilities.
  • $pagination (PaginationHelper): Assists with pagination logic and rendering.
  • $url (UrlHelper): Utilities for URL parsing and manipulation.
  • $httpRequest (HttpRequestHelper): Handles HTTP requests.
  • $environment (EnvironmentHelper): Provides information about the server and execution environment.
  • $encryption (Encryption): Encryption and decryption utilities.
  • $cache (CacheManager): Manages caching of data.
  • $executionTimer (ExecutionTimer): Measures script execution time.
  • $rateLimiter (RateLimiter): Enforces rate limiting policies.
  • $language (LanguageManager): Manages multi-language support (initialized if Config::MULTI_LANG is true).
  • $errorPageHandler (ErrorPageHandler): Handles custom error pages.
  • $logger (Logger): Logs messages and errors.
  • $errorHandler (ErrorHandler): Handles errors and exceptions.
  • $accessControl (AccessControl): Manages access permissions and blocks unauthorized access.
  • $validator (Validator): Validates data against specified rules.
     
Usage Examples

Accessing the Database Query Builder

// Using the App instance
$db = $app->db;

// Perform a database query
$users = $db->table('users')->where('status', 'active')->get();

// Display the results
foreach ($users as $user) {
    echo htmlspecialchars($user['name']) . '
';
}
 

Using the Authentication Component

// Access the Auth component
$auth = $app->auth;

// Log in a user
if ($auth->userLogin($email, $password)) {
    echo 'Login successful!';
} else {
    echo 'Invalid credentials.';
}

// Check if a user is logged in
if ($auth->isUserLoggedIn()) {
    $user = $auth->getUser();
    echo 'Welcome, ' . htmlspecialchars($user['name']);
}

 

Managing Sessions and CSRF Tokens

// Access the SessionManager
$session = $app->sessionManager;

// Generate a CSRF token
$token = $session->generateCsrfToken();

// Include the token in a form
echo '';

// Verify the CSRF token on form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$session->verifyCsrfToken($_POST['_csrf_token'])) {
        die('Invalid CSRF token.');
    }
}

 

Logging Messages

// Access the Logger
$logger = $app->logger;

// Log an informational message
$logger->info('User accessed the dashboard.');

// Log an error message
$logger->error('Failed to retrieve data from the API.');

 

The App class is designed to streamline your development process by providing immediate access to all core components of JiFramework. By leveraging the App class, you can focus on building your application's logic without worrying about initializing and managing individual components.

Make sure to explore each component's documentation for more detailed information on their functionalities and how to use them effectively within your application.