3

In my website I have an inc file containing some values that are needed on all blocks of a page. For reasons related to the performances, I would like not to use the php "require" function in each block. Is there a way to load this file at page level and make the values available in all blocks?

Do I have to do that in the template_preprocess function?

2

Yes this can be done in hook_preprocess_block.

inc file:

function get_some_vars() {
  static $vars = array();

  if (empty($vars)) {
    $vars['foo'] = expensive_function_1();
    $vars['bar'] = expensive_function_2();
  }

  return $vars;
}

.module/template.php file:

function MYMODULE_preprocess_block(&$vars) {
  require_once 'my.inc'; // or module_load_include, depends where your code is

  $vars += get_some_vars();
}

It's not the exact desired workflow you described in the question, but it has a similar effect; require_once will only include the file once per request, and the variables will only be prepared once per request. There is the function call overhead, but given that themes don't have the concept of always-available-vars (as far as I know each theme call is an isolated instance as it were), I think this is the closest you'll get without patching the theme system.

  • thank you. My only fear is that it takes too much time to read the file for each block. It would be perfect if the file is read at page level and then the values are available also at block level. – lorenzo Jan 17 '16 at 6:05
  • Have a look through the docs for require_once - In the above code the include file is read exactly once per request, regardless of the number of blocks that are rendered, which was your goal in the original question. Memory and other overheads are also all kept at their minimum. I don't think it's possible to perform the task you're asking in a more efficient way. Have you actually determined that the file stat is causing you a real world problem? If not, have a hunt around and read up on the term "premature optimisation" - it might make you think twice about where to concentrate your efforts – Clive Jan 17 '16 at 10:58
  • thank you!. The problem is exactly that the file is read once per request. It means that if I have 10 blocks in a page that require the same file, the file will be read ten times. It is a really inefficient and it surprise me that there is not a workaround for that in Drupal. – lorenzo Jan 17 '16 at 17:51
  • A request is a single page build - using static vars and require_once the file will only be included once no matter how many blocks there are on a page. Drupal doesn't need a specific feature for this, it's a part of php itself – Clive Jan 17 '16 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.