关于php:更改Laravel 5中的存储路径

Change the storage path in Laravel 5

我想将Laravel 5.1使用的存储路径更改为/home/test/storage。这样做的好处是这些文件没有存储在存储库中,我认为这非常难看。在Laravel 4中,使用bootstrap/paths.php

非常简单。

在Laravel 5中,这可以通过使用bootstrap/app.php中的$app->useStoragePath('/path/')来工作。但是,我想使用config选项定义存储路径,例如$app->useStoragePath(config('app.storage_path')。 config选项调用环境变量或返回默认位置。

这样做会导致Uncaught exception 'ReflectionException' with message 'Class config does not exist';这很有意义,因为尚未加载此函数。

启动后我尝试设置存储路径:

1
2
3
$app->booted(function () use ($app) {
    $app->useStoragePath(config('app.storage_root'));
});

这没有改变。我也尝试将其直接绑定到path.storage

1
2
3
$app->bind('path.storage', function ($app) {
    return config('app.storage_root');
});

最后一个选项部分起作用;现在,视图缓存已放置在正确的位置,但是日志仍在旧位置。


Laravel 5.3位于bootstrap / app.php

1
2
3
4
5
6
7
8
9
10
11
12
/*
|--------------------------------------------------------------------------
| Set Storage Path
|--------------------------------------------------------------------------
|
| This script allows us to override the default storage location used by
| the  application.  You may set the APP_STORAGE environment variable
| in your .env file,  if not set the default location will be used
|
*/


$app->useStoragePath( env( 'APP_STORAGE', base_path() . '/storage' ) );


这是在Laravel 5中更改存储路径的简单解决方案,就像在Laravel 4中所做的那样

在bootstrap / app.php

1
2
3
4
5
6
# new storage path
# base_path() -> returns root path
$path_storage = base_path() ."../../storage";

# override already $app->storagePath using the function
$app->useStoragePath($path_storage);

这将使存储路径与会话,视图,缓存,日志相同


在.env

中进行设置

app.php

1
'app_storage' => env('APP_STORAGE', storage_path()),

app / Providers / AppServiceProvider.php

1
2
3
4
public function register()
{
    $this->app->useStoragePath(config('app.app_storage'));
}

.env

1
APP_STORAGE=custom_location


这适用于Laravel 5.2

文件:app/Providers/AppServiceProvider.php

1
2
3
4
5
public function register() {
  ...
  $this->app->useStoragePath(config('what_ever_you_want'));
  ...
}

AppServiceProvider上调用useStoragePath不会正确执行该工作,因为AppServiceProvider在加载配置文件后被调用。因此在配置文件中对storage_path的任何使用仍将引用旧的存储路径。

为了正确解决此问题,建议您扩展Application类,然后在您自己的类的构造函数中编写以下内容。

1
2
3
4
5
6
7
8
9
10
11
    /**
     * MyApplication constructor.
     */

    public function __construct($basePath = null)
    {
        parent::__construct($basePath);
        // set the storage path
        $this->afterLoadingEnvironment(function () {
            $this->useStoragePath(/*path to your storage directory*/);
        });
    }

如果您的网站是托管网站;

将所有内容从公用文件夹移动到根文件夹

1
2
3
$app->bind('path.public', function() {
    return __DIR__;
});