I am using Laravel "laravel/framework": "10.22.0",
I want to use php artisan cache:config
in order to improve the performance.
I do face one issue when running the command as I am using config('configName'
inside bootstrap/container.php
and all the results of config
function are null.
This is my bootstrap/app.php
<?php
/**
* @var IlluminateFoundationApplication $app
*/
$app = new IlluminateFoundationApplication(
realpath(__DIR__.'/../')
);
require(__DIR__ . '/container/container.php');
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
This is a sample of my bootstrap/container/container.php
<?php
use IlluminateFoundationApplication;
/**
* @var $app Application
*/
//------------------------------------//
// SERVICES //
//------------------------------------//
$app->singleton(
AppServicesLoggerLoggerContract::class,
function ($app) {
$d = config('logger');
$config = config('mail');
// the configs above are always null during php artisan config:cache command and this is causing exception and the cache command to fail
return new AppServicesLoggerLogger(
$app,
config('logger'),
);
}
);
I was previously using .env
function inside the container and that worked fine.
I moved all envs inside config files as recommended by Laravel documentation in order to have config:cache
working but now am facing the issue that config:cache
itself fails! as I cannot use config inside container..
If it is not possible to use config
during the DI initialisation than it will be ugly to access the configs inside the constructors of the classes instead of receiving them as parameters. It makes testing ugly and harder. With my approach it is normal testing pattern you just change the config array argument during tests.
2
Answers
I solved it in a very weird way.
I was using
app->environment()
insideconfig/logger.php
and this was causing the issue..I changed the code to env('APP_ENV') instead then tried
php artisan config:cache
again and it worked.There was no issue using
config
function inside thebootstrap
fileMoving into config is a good approach, but I don’t think it means it should move to Bootstrap
This is mainly because you’re trying to access the variable before it initializes (available).
My suggestion is,
Create a Custom Config File (
config/
directory. (ex filename: abc.php))In
.env
(or you can skip this and directly add it to config too)You can use
In LoggerServiceProvider.php
In
config/app.php