WordPress / WordPress/WordPress-Coding-Standards
Using a transient should be considered a way of caching a direct database call
Nobody has claimed this yet.
- Dominant language
- PHP
- Stars
- 2.8k
- Forks
- 521
- Avg merge
- 5d 20h
- Merged PRs (30d)
- 1
Description
Bug Description
Using a transient for caching a direct database call is not deemed acceptable but I believe it should be:
When using an external object cache, get_transient() is short-circuited to use wp_cache_get().
When not using an external object cache, it falls back to use get_option() (after ensuring that all options were loaded). And then get_option() either uses a hash lookup in all options, or wp_cache_get().
Thanks @apermo for the pointer and encouragement to file this!
Minimal Code Snippet
The issue happens when running this command:
./vendor/bin/phpcs -s --standard=WordPress transient.php
... over a file containing this code:
if ( ! get_transient( 'time' ) ) {
$wpdb->get_var( 'SELECT current_time()' );
}
Error Code
WordPress.DB.DirectDatabaseQuery.NoCaching
Environment
| Question | Answer |
|---|---|
| PHP version | 7.4 |
| PHP_CodeSniffer version | 3.10.1 |
| WordPressCS version | 3.1.0 (also tested with dev-develop 29488fe) |
| WordPressCS install type | https://github.com/WordPress/WordPress-Coding-Standards?#composer-project-based-installation |
Tested Against develop Branch?
- I have verified the issue still exists in the
developbranch of WordPressCS.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the report with ./vendor/bin/phpcs -s --standard=WordPress transient.php and inspect the implementation of WordPress.DB.DirectDatabaseQuery.NoCaching. Trace how the sniff recognizes caching before changing its behavior, then rerun the command with the provided get_transient() example and the relevant test suite to confirm the warning is no longer reported.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100