Skip to content

Commit

Permalink
Move cache file out of public folder
Browse files Browse the repository at this point in the history
Allow to skip cache usin ga filter
  • Loading branch information
gmazzap committed May 12, 2020
1 parent 8d9831e commit 935cf5d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 36 deletions.
65 changes: 43 additions & 22 deletions docs/03-WordPress-Integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,28 +110,6 @@ In the *"Environment Variables"* chapter it has been presented how WP Starter se

Besides the env vars named after WordPress configuration constants there are a few that have a special meaning for WP Starter WordPress installations.

#### Cached Environment

To parse env files and setup environment variables, and then setup WordPress constants based on the environment, is a bit expensive.

Half of the reason is the env file parsing itself (which can be avoided by setting environment variables in the actual environment). The other half is the fact that WP Starter has no way to know which environment variables matching WP constants are set in the environment before trying to access them. Which means that WP Starter needs to loop **all** the possible WordPress constants, and for each of them try to access an environment variable named in the same way and if that is found finally define a constant.

To avoid this overhead at every request, the WP Starter `wp-config.php` registers a function to be run on "shutdown" that *dumps* the environment variables that have been accessed with success during the first request into a PHP file so that on subsequent requests the environment "bootstrap" will be much faster.

This cache file is saved in the same folder that contains the `wp-config.php` and is named `.env.cached.php`.

However, having a **cached environment means that any change to it will require the cache file to be deleted**. WP Starter does it via one of its steps ("flush-env-cache") so after a Composer install / update or after running WP Starter command the environment cache is always clean.

Of course it is possible to clean env cache on demand by explicitly running the command:

```shell
composer wpstarter flush-env-cache
```

(Read more about running specific steps via `wpstarter` command in the *"WP Starter Command"* chapter)

To prevent WP Starter to generate and use cached environment at all, it is possible to set the **`cache-env`** setting to false.

#### WP_ENV

`WP_ENV` is the main WP Starter specific environment variable and it determines the current application environment, for example "production", "staging", and so on.
Expand Down Expand Up @@ -197,6 +175,49 @@ switch ($environment) {

On top of that, if **`WP_ENV`** is `local`, and `WP_LOCAL_DEV` is not defined, it will be defined to `true`.

#### Cached Environment

To parse env files and setup environment variables, and then setup WordPress constants based on the environment, is a bit expensive.

Half of the reason is the env file parsing itself (which can be avoided by setting environment variables in the actual environment). The other half is the fact that WP Starter has no way to know which environment variables matching WP constants are set in the environment before trying to access them. Which means that WP Starter needs to loop **all** the possible WordPress constants, and for each of them try to access an environment variable named in the same way and if that is found finally define a constant.

To avoid this overhead at every request, the WP Starter `wp-config.php` registers a function to be run on "shutdown" that *dumps* the environment variables that have been accessed with success during the first request into a PHP file so that on subsequent requests the environment "bootstrap" will be much faster.

This cache file is saved in the same folder that contains the `.env` file and is named `.env.cached.php`.

However, having a **cached environment means that any change to it will require the cache file to be deleted**. WP Starter does it via one of its steps ("flush-env-cache") so after a Composer install / update or after running WP Starter command the environment cache is always clean.

Of course it is possible to clean env cache on demand by explicitly running the command:

```shell
composer wpstarter flush-env-cache
```

(Read more about running specific steps via `wpstarter` command in the *"WP Starter Command"* chapter)

There are several ways to prevent WP Starter to generate and use cached environment in first place.

- when `WP_ENV` env var described above is `"local"` the cache by default is not created.
- when the **`cache-env`** configuration is `false`, the cache by default is not created.
- there's a WordPress filter `'wpstarter.skip.cache-env'` that can be used to disable the cache creation.

The `'wpstarter.skip.cache-env'` filter is interesting because it allows to disable cache in specific environments by using the **`{$environment}.php`** file described above.
For example, it is possible to skip environment cache in "development" environment having a `development.php` file that contains:

```php
add_filter('wpstarter.skip.cache-env', '__return_true');
```

The filter is executed very late (so could be added in MU plugins, plugins and even themes) and also passes the environment name as second param.

For example, to only allow cache in production there a code lie the following can be used:

```php
add_filter('wpstarter.skip.cache-env', function ($skip, $envName) {
return $skip || $envName !== 'production';
});
```

#### WP_HOME

This is not a WP Starter variable, but a standard WordPress configuration constant.
Expand Down
30 changes: 16 additions & 14 deletions templates/wp-config.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,26 @@
* overridden from file, even if `WPSTARTER_ENV_LOADED` is not set.
*/
$envLoader = '{{{CACHE_ENV}}}'
? WordPressEnvBridge::buildFromCacheDump(__DIR__ . WordPressEnvBridge::CACHE_DUMP_FILE)
? WordPressEnvBridge::buildFromCacheDump(WPSTARTER_PATH . WordPressEnvBridge::CACHE_DUMP_FILE)
: new WordPressEnvBridge();

if (!$envLoader->hasCachedValues()) {
$envLoader->load('{{{ENV_FILE_NAME}}}', WPSTARTER_PATH);
$env = $envLoader->read('WP_ENV') ?? $envLoader->read('WORDPRESS_ENV');
if ($env && $env !== 'example') {
$envLoader->loadAppended("{{{ENV_FILE_NAME}}}.{$env}", WPSTARTER_PATH);
$envName = $envLoader->read('WP_ENV') ?? $envLoader->read('WORDPRESS_ENV');
if ($envName && $envName !== 'example') {
$envLoader->loadAppended("{{{ENV_FILE_NAME}}}.{$envName}", WPSTARTER_PATH);
}
$envLoader->setupConstants();
}

isset($env) or $env = $envLoader->read('WP_ENV') ?? $envLoader->read('WORDPRESS_ENV');
isset($envName) or $envName = $envLoader->read('WP_ENV') ?? $envLoader->read('WORDPRESS_ENV');

if (
$env
&& file_exists(WPSTARTER_PATH . "/{$env}.php")
&& is_readable(WPSTARTER_PATH . "/{$env}.php")
$envName
&& file_exists(WPSTARTER_PATH . "/{$envName}.php")
&& is_readable(WPSTARTER_PATH . "/{$envName}.php")
) {
require_once WPSTARTER_PATH . "/{$env}.php";
require_once WPSTARTER_PATH . "/{$envName}.php";
}

/** Set optional database settings if not already set. */
Expand Down Expand Up @@ -91,7 +91,7 @@
}

/** Environment-aware settings. Be creative, but avoid having sensitive settings here. */
switch ($env) {
switch ($envName) {
case 'local':
case 'development':
defined('WP_DEBUG') or define('WP_DEBUG', true);
Expand All @@ -117,10 +117,9 @@
defined('SCRIPT_DEBUG') or define('SCRIPT_DEBUG', false);
break;
}
if ($env === 'local' && !defined('WP_LOCAL_DEV')) {
if ($envName === 'local' && !defined('WP_LOCAL_DEV')) {
define('WP_LOCAL_DEV', true);
}
unset($env);

/** Fix `is_ssl()` behind load balancers. */
if (
Expand Down Expand Up @@ -167,12 +166,15 @@ static function ($color) use ($envLoader) {
/** On shutdown we dump environment so that on subsequent requests we can load it faster */
if ('{{{CACHE_ENV}}}' && $envLoader->isWpSetup()) {
register_shutdown_function(
static function () use ($envLoader) {
$envLoader->dumpCached(__DIR__ . WordPressEnvBridge::CACHE_DUMP_FILE);
static function () use ($envLoader, $envName) {
$skipCache = apply_filters('wpstarter.skip.cache-env', $envName === 'local', $envName);
$skipCache or $envLoader->dumpCached(WPSTARTER_PATH . WordPressEnvBridge::CACHE_DUMP_FILE);
}
);
}

unset($envName, $cacheEnv);

###################################################################################################
# I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. #
# I watched C-beams glitter in the dark near the Tannhauser gate. #
Expand Down

0 comments on commit 935cf5d

Please sign in to comment.