How to make a variable available for the duration of the page request

I’m trying to limit the number of database reads per page request. Currently, each time the get_avatar hook fires, I make a call to get_option() which returns some data. The $data returned doesn’t change for the duration of the page request so I have many redundant calls to get_option() taking place (because get_avatar fires multiple times on some of my pages).

function my_check() {
    $data = get_option( 'blah' );
    return $data;
}

function my_func( $avatar, $id_or_email, $size, $default, $alt ) {
    if ( my_check() ) {
        // Do something.
    }
}
add_filter( 'get_avatar', 'my_func', 10, 5 );

My first thought was to use object-oriented PHP to make $data a class variable but I feel a class is overkill for this simple scenario. Then I thought about making $data a global variable, but then realised globals are bad. So I’ve ruled out these two approaches.

Is there another way I can make the $data variable available for the duration of the page request? My aim is to avoid multiple calls to get_option().

Note: The value of $data may change in-between page requests.

1 Answer
1

A class provides structure, and if it’s what you need to do it then do it. The alternative would be a global variable, which is bad practice and should be avoided ( and makes reliable unit testing near impossible )

However, your entire premise is unnecessary. WordPress already stores the option in its caches, so no second database call occurs.

Otherwise yes, a class or object would be the answer

Leave a Comment