PHP - Creating Your Own PHP SessionStorage
Tags: php, laravel, coding, tutorial
Published: 2023-08-04 18:06:43


# Creating Your Own PHP NativeSessionStorage Library

## Introduction

PHP sessions are a fundamental feature for storing user-specific data across requests. The native `$_SESSION` superglobal is commonly used, but in this tutorial, we'll learn how to create our own custom session storage library called `NativeSessionStorage`. This library will implement the `SessionStorageInterface`, which will enable us to work with PHP sessions in a more structured and extensible manner.

## Prerequisites

Before we begin, ensure you have the following:

- PHP version 7.4 or higher installed on your system.
- A basic understanding of PHP and object-oriented programming.

## Step 1: Defining the Interface

Let's start by defining the `SessionStorageInterface`. This interface will enforce the methods that any class implementing it should have.

```php
<?php
declare(strict_types=1);

namespace YourNamespace\Session\Storage;

use ArrayAccess;

interface SessionStorageInterface extends ArrayAccess
{
    public function get(string $key, $default = null);
    public function put(string $key, $value = null): void;
    public function all(): array;
    public function has(string $key): bool;
    public function remove(string $key): void;
}
```

The `SessionStorageInterface` extends `ArrayAccess` to ensure that our custom session storage class behaves like an array.

## Step 2: Implementing the NativeSessionStorage

Now, let's create our `NativeSessionStorage` class that implements the `SessionStorageInterface`.

```php
<?php
declare(strict_types=1);

namespace YourNamespace\Session\Storage;

use function session_start;
use function session_status;
use const PHP_SESSION_NONE;

class NativeSessionStorage implements SessionStorageInterface
{
    private array $storage;

    public function __construct(array $options = [])
    {
        if (session_status() === PHP_SESSION_NONE) {
            if (!session_start($options)) {
                throw new \RuntimeException('Failed to start the session.');
            }
        }

        $this->storage = &$_SESSION;
    }

    // Implement the methods from the SessionStorageInterface
    // ...

    // Implement the ArrayAccess methods
    // ...
}
```

## Step 3: Implementing the Methods

In the `NativeSessionStorage` class, implement the methods declared in the `SessionStorageInterface`. These methods will allow us to get, set, check, and remove session data.

```php
// ...
class NativeSessionStorage implements SessionStorageInterface
{
    // ...

    public function get(string $key, $default = null)
    {
        return $this->storage[$key] ?? $default;
    }

    public function put(string $key, $value = null): void
    {
        $this->storage[$key] = $value;
    }

    public function all(): array
    {
        return $this->storage;
    }

    public function has(string $key): bool
    {
        return isset($this->storage[$key]);
    }

    public function remove(string $key): void
    {
        unset($this->storage[$key]);
    }

    // Implement the ArrayAccess methods
    // ...
}
```

## Step 4: Usage

Now, let's see how we can use our `NativeSessionStorage` library in our PHP project.

```php
<?php
// Include the autoload.php file that loads the classes
require_once 'path/to/autoload.php';

use YourNamespace\Session\Storage\NativeSessionStorage;

// Create a new session storage instance
$sessionStorage = new NativeSessionStorage();

// Set a value in the session
$sessionStorage->put('username', 'JohnDoe');

// Get a value from the session
$username = $sessionStorage->get('username');

// Check if a key exists in the session
if ($sessionStorage->has('username')) {
    echo "Welcome back, $username!";
} else {
    echo "Welcome, Guest!";
}

// Remove a value from the session
$sessionStorage->remove('username');
```

## Conclusion

Congratulations! You've successfully created your own `NativeSessionStorage` library. This custom library provides a clean and organized way to work with PHP sessions, making your code more maintainable and extensible.

Remember to test your library thoroughly to ensure it works as expected in various scenarios. Feel free to customize the implementation to fit your specific project needs and explore additional features you can add to enhance its functionality.

Ideal for small project
Simple and easy!
https://github.com/devcoder-xyz/php-session

Happy coding!

---