Home > database >  Confige service based on session id
Confige service based on session id

Time:03-11

In my Symfony 6 project I need to store big uploaded files per user session.

As it's not a good idea to directly store these files in the session I'm using flysystem with a directory per session id and a cleanup process.

So far so good

Now as I don't want generate the file path per session id every time I want to directly configure a flysystem storage as service using the current session id as base directory like this:

flysystem:
    storages:
        session.storage:
            adapter: 'local'
            options:
                directory: '%env(APP_SESSION_STORAGE_PATH)%/%sessionId%'

This obviously does not work as there is no %sessionId% but how can I do this?

I also tried to use a factory but this also feels to be over complicated as I would have to copy the logic from flysystem-bundle to initialize this service.

I know this service only works within http context.

CodePudding user response:

Just the code-idea. Just after your "..have to copy the logic from flysystem-bundle..". Wow. I think U try to make it over complicated

I don't know your app-logic. However just like:

// config/services.yaml
services:
     _defaults:
        //..
        bind:
            $bigFileSessionStoragePath: '%env(APP_SESSION_BIG_FILE_STORAGE_PATH)%'

Your service :

// BigFileSessionStorage.php


namespace Acme/Storage;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\RequestStack;

class BigFileSessionStorage
{
   private string $bigFileSessionDirPath;

   public function __construct(
     private RequestStack $requestStack,
     private Filesystem $filesystem,
     private string $bigFileSessionStoragePath
   ){}

  public function storeBigSessionFile(File $bigSessionFile){
     $sessionBifFileDir = $this->getBigFileSessionDirectory();
     // move a Big File ..
     $this->filesystem->copy(...)
  }

  public function getBigFileSessionDirectory(): string{
    $sessionId = $this->requestStack->getSession()->getId();
    $path = $this->bigFileSessionDirPath.DIRECTORY_SEPARATOR.$sessionId;
    if (!$this->filesystem->exists($path)){
        $this->filesystem->mkdir($path);
        $this->bigFileSessionDirPath = $path;
    }
    return $this->bigFileSessionDirPath;
  }

  // TODO & so on 
  public function removeBigFileSessionDirectory(){}  
   
}

Then inject this service where U need it.

CodePudding user response:

In my opinion, a very rough option, but you can do this)

in your config/services.yaml create parameter

parameters:
    session_id: '%env(SESSION_ID)%'

After that you will be able to use the %session_id% parameter in your configurations

And set session id

 $_ENV['SESSION_ID'] = 'YOU_SESSION_ID';
  • Related