How can the use of a SessionFactory class help in creating and managing session data in PHP applications?

The use of a SessionFactory class can help in creating and managing session data in PHP applications by providing a centralized way to handle session initialization, configuration, and management. This can help improve code organization, reduce redundancy, and make it easier to maintain and scale session handling in the application.

<?php

class SessionFactory {
    public static function startSession() {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
    }

    public static function setSessionData($key, $value) {
        self::startSession();
        $_SESSION[$key] = $value;
    }

    public static function getSessionData($key) {
        self::startSession();
        return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
    }

    public static function unsetSessionData($key) {
        self::startSession();
        unset($_SESSION[$key]);
    }

    public static function destroySession() {
        self::startSession();
        session_destroy();
    }
}

// Example usage
SessionFactory::setSessionData('username', 'john_doe');
$username = SessionFactory::getSessionData('username');
echo $username; // Output: john_doe