【问题标题】:Laravel change filesystem disks path on run timeLaravel 在运行时更改文件系统磁盘路径
【发布时间】:2018-03-21 22:44:32
【问题描述】:

我知道 filesystems.php 用于创建磁盘,我目前正在使用它,配置了 ~~ 20 个磁盘。

我对这些有一个新问题,我目前正在尝试为每个磁盘添加前缀,一个字符串。问题是运行php artisan config:cache 时正在保存路径,但我需要在运行时更改它们,例如,对于用户Sergio,它需要将Sergio/ 附加到以下磁盘,例如:

//filesystems.php
'random' => [
   'driver' => 'local',
   'root' => storage_path('app/random'),
],

然后

Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();
//outputs /var/www/html/project/storage/app/random

目标是在例如中间件中设置配置,我目前已经像这样设置了 tentant 数据库

//Middleware
Config::set('database.connections.tenant.database', "Sergio");
DB::reconnect('tenant');

我目前可以正确设置路径

Config::set('filesystems.disks.random.root',storage_path('app/Sergio/random'));

但我很担心,因为如果在该行之前我尝试到达路径,存储会将初始路径保存在内存中,而不是在更改后重新获取它。

例如。无需任何中间件即可完成此操作。

$fullPath1 = Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();

Config::set('filesystems.disks.random.root',storage_path('app/Sergio/random'));

$fullPath2 = Storage::disk("random")->getDriver()->getAdapter()->getPathPrefix();

打算发生的是$fullPath1 将输出初始路径/var/www/html/project/storage/app/random,然后$fullPath2 将输出/var/www/html/project/storage/app/Sergio/random

有没有办法让存储知道我已经更改了磁盘本地路径?

【问题讨论】:

  • 运气好吗?我遇到了类似的问题,但对于 s3 磁盘。我的磁盘很少,无法在运行时更改它们,因为它总是使用第一个配置:/
  • 不走运,如果由于某种原因在平台的某个地方在更改之前访问了文件系统,则更改不会生效
  • 我也面临同样的问题。我想将文件存储在 s3 的存储文件夹中,但不想在文件系统配置文件中定义 root => 'storage'。帮助找出解决方案

标签: laravel laravel-facade laravel-storage


【解决方案1】:

如何添加一个新配置而不是更新已经加载的配置,如下所示:

private function addNewDisk(string $diskName) 
{
      config(['filesystems.disk.' . $diskName => [
          'driver' => 'local',
          'root' => storage_path('app/' . $diskName),
      ]]);
}

在使用 Storage 门面之前,调用上面的方法,这样配置就会更新,当你使用新磁盘时,它会尝试根据更新的配置再次解析。

{
....
    $this->addNewDisk('new_random');
    Storage::disk('new_random')->get('abc.txt'); // or any another method
...

}

【讨论】:

    猜你喜欢
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 2014-07-18
    相关资源
    最近更新 更多