Pass global data around

There are some ways to pass global data around the site.

  • Use of a static class with syntax like my::data();.
  • Use of global variables.

Both require some work to setup.

Problem

My problem was that I have some data inside a kirbytext tag that I wanted to use in the footer snippet. I did not want to run the function again, because it’s a quite large SQL query. I could cache it but no, I wanted something really simple.

Solution

I used the register set option.

This is what I did in the kirbytext tag:

kirbytext::$tags['wikipedia'] = array(
  'html' => function($tag) {
    kirby()->set('option', 'test', "DATA"); // The magic
  }
);

This is what I did in the footer snippet:

echo kirby()->get('option', 'test'); // Says "DATA"

This is just an example. It does not need to be a kirbytext tag.

To use register set option to pass data around seems to be a really simple way to use global data.

3 Likes