Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Making Cache, Config, and Env work in harmony (example) #193

Open
paxperscientiam opened this issue Sep 8, 2021 · 0 comments
Open

Making Cache, Config, and Env work in harmony (example) #193

paxperscientiam opened this issue Sep 8, 2021 · 0 comments

Comments

@paxperscientiam
Copy link

Hey @mattstauffer ,

This might supersede #192 idea and prior PR. Here is an example of how to get Cache, Config, and Env.

Some notes:

  1. Not sure one would want to, but Illuminate\Support\Arr is needed to parse output of Cache::get(...) as it doesn't handle dot notation.
  2. I can't beat Laravel's logic for handling cache/env for different environments. Not sure how that would be demonstrated other than copy/pasting from their source code.

Works-for-me example code:

<?PHP

/*
  Note, these variables aren't directly accessible. Use globals
  EG: Illuminate\Support\Facades\Config::get("app.cnx")
 */

use Illuminate\Container\Container;
use Illuminate\Support\Arr;
use Illuminate\Config\Repository;
use Illuminate\Support\Facades\Facade;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Cache\CacheManager;
use Dotenv\Dotenv;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Env;

defined("FILE_ROOT") ? true : define("FILE_ROOT", realpath(".."));

// create dummy app
$app = new Container();


// would want to refactor to make sure cache is used in production
try {
    // check if file exists. if not, presume production enviroment
    $dotenv = Dotenv::createImmutable(FILE_ROOT);
    $dotenv->load();
} catch (Exception $e) {
    // presume production
    error_log($e->getMessage());
}

// config setup
$config = new Repository(require(FILE_ROOT . "/backend/config/app.php"));

// bind $config to $app
$app->instance(
    'config',
    $config
);

// cache stuff
$cacheC = new Container();
$cacheC['config'] = $config->get('app.cache');
$cacheC["files"] = new Filesystem();
$cacheManager = new CacheManager($cacheC);
$cache = $cacheManager->store();

// bind $cache to $app
$app->instance(
    'cache',
    $cache
);

$cache->put('test', 'This is loaded from Redis cache.', 500);
$cache->put('app', $config->get('app'));

$config->set('test', 'rofl');

Facade::setFacadeApplication($app);

s(Config::get('test'));
s(Config::get('app.cnx'));

s(Cache::get('test'));
s(Arr::get(Cache::get('app'), 'cnx'));

s(Env::get('RUN_MODE'));

Output:
Screen Shot 2021-09-08 at 4 50 25 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant