On plugin creation, itās common to use let the user set config values with c::set
and c::get
.
Itās also nice to have a plugin name prefix and a fallback value like this:
c::get('myplugin.hello', 'world');
When using c::get
in very many places in the plugin, it can be a bit annoying to always include the a plugin name prefix and a fallback. It takes up space in the code every time and if you want to change the fallback, it needs to be done in several places.
Here is my solution for it:
I think the namespace is important to prevent function collisions.
namespace MyNamespace;
use c;
function setOption($name, $data) {
$data = c::get('myplugin.' . $name, $data);
kirby()->set('option', 'myplugin.' . $name, $data);
}
function getOption($name) {
return kirby()->get('option', 'myplugin.' . $name);
}
What it does is that it put c::get
data into kirby()->get()
to use the correct fallback and store it globally. I see now that there is even more room for improvement, but it works.
In another file, set the values with fallback:
The benefit of it is that you only need to set this ones and then it will always be available with getOption
later.
namespace MyNamespace;
setOption('log', false);
setOption('slug', 'hello-world');
setOption('token', 'token');
In the plugin somewhere, get the option needed without the need to send prefix or fallback:
namespace MyNamespace;
echo getOption('log');
echo getOption('slug');
echo getOption('token');