What are the best practices for managing external dependencies, such as session variables, within PHP classes?

When managing external dependencies such as session variables within PHP classes, it is best practice to pass them as parameters to the class constructor or methods rather than accessing them directly within the class. This helps improve the class's reusability, testability, and overall maintainability.

<?php

class MyClass {
    private $session;

    public function __construct($session) {
        $this->session = $session;
    }

    public function getSessionValue($key) {
        return $this->session[$key] ?? null;
    }

    public function setSessionValue($key, $value) {
        $this->session[$key] = $value;
    }
}

// Example usage
$session = $_SESSION;
$myClass = new MyClass($session);
$myClass->setSessionValue('user_id', 123);
echo $myClass->getSessionValue('user_id');

?>