Plugin config abstraction
As of Totara 15, Totara provides an abstract class for handling plugin config settings in an object-oriented way. This class improves upon the built-in get_config() and set_config() methods which have rather unintuitive or inconsistent argument order that can lead to bugs.
The base class is found in server/lib/classes/base_plugin_config.php.
This can be extended for a specific plugin or component:
// server/type/myplugin/classes/config.php namespace type_myplugin; use core\base_plugin_config; class config extends base_plugin_config { protected static function get_component(): string { return 'type_myplugin'; } }
The base class allows you to get or set specific config settings within your child class. get()Â and set() are not meant to be exposed for public usage. The goal of the config wrapper is to enforce having a proper getter/setter function for each config item so if we need to change the config item's name, then the impact should be as small as possible:
// server/type/myplugin/classes/config.php namespace type_myplugin; use core\base_plugin_config; class config extends base_plugin_config { protected static function get_component(): string { return 'type_myplugin'; } public static function get_client_id(?string $default = "default"): ?string { // Returns the 'client_id' setting or 'default' if not set. // Note that this is equivalent to calling to get_config("type_myplugin", "client_id") ?? $default return self::get('client_id', $default); } public static function set_client_id(?string $value): void { // Sets the plugin config setting. self::set('client_id', 'newvalue'); } }
In the plugin child class you can also optionally define additional configuration-related constants:
// server/type/myplugin/classes/config.php namespace type_myplugin; use core\base_plugin_config; class config extends base_plugin_config { public const MAX_RESULTS = 50; private const DEFAULT_CLIENT_ID = 'some_value'; protected static function get_component(): string { return 'type_myplugin'; } public static function get_client_id() { return static::get('client_id', static::DEFAULT_CLIENT_ID); } public static function set_client_id(string $value) { static::set('client_id', $value); } } // Example usage: config::set_client_id('new_value'); $client_id = config::get_client_id(); $max = config::MAX_RESULTS;