Kirby->set vs c::set?

Which one should I use and why?

$kirby->set('option');
c::set('some-option');

Do we need both?

I’d use c::set() in my config.php.

Didn’t you say you were on vacation?:wink:

Because it’s the old and familiar syntax or because of something else?

What would you use in a plugin?

You can use both syntaxes in both the config.php and in a plugin, I think. But c::set() feels familiar in config.php.

Which option would you like to set from your plugin?

These two lines do different things:

c::set('some-option', 'some-value');
$kirby->set('option', 'some-option', 'some-value');
  • The first sets a value in the C::$data array.
  • The second one sets a value in the Kirby::$options array.

One possible source of confusion is that the Kirby class, when it is instantiated (only once because it uses a singleton pattern), makes a copy of c::$data:

$this->options = array_merge($this->options, c::$data);

Basically, Kirby “forks” the options internally. And it does it at a precise moment: after loading the config file(s), but before executing other code (including plugins and templates, if I remember correctly).

As a result, this works:

// site/config/config.php
c::set('my-option', 'LOL');

// site/templates/default.php
$cMyOption = c::get('my-option'); // "LOL"
$kMyOption = $kirby->get('option', 'my-option'); // "LOL"
if ($cMyOption === $kMyOption && $cMyOption === 'LOL') {
  echo "Yep, it works.";
}

but this doesn’t:

// site/templates/default.php
c::set('my-option', 'LOL');
$cMyOption = c::get('my-option'); // "LOL"
$kMyOption = $kirby->get('option', 'my-option'); // null
if ($cMyOption === $kMyOption && $cMyOption === 'LOL') {
  echo "Sorry, this won't work.";
}

Now, whether you should use c::set or $kirby->set('option') depends on what you’re trying to do. For project configuration, you should probably stick to c::set, and l::set for localized settings.

In controllers and templates, you probably shouldn’t be adding values to c::$data or kirby::$options (unless you have a use case where it’s needed?).

In plugins, I guess it depends on what you’re trying to do.

2 Likes