Managing config files, saving and loading settings in PocketMine-MP
Configuration files allow your plugin to store settings that users can modify. PocketMine-MP provides the Config class to easily work with YAML, JSON, and other formats.
Create a default config in your plugin’s resources folder:
resources/config.yml
# MyPlugin Configuration# Enable plugin featuresenabled: true# Maximum players in gamemax-players: 10# Spawn locationspawn: world: world x: 0 y: 64 z: 0# Messagesmessages: welcome: "Welcome to the server!" goodbye: "See you later!"# List of banned itemsbanned-items: - diamond_sword - tnt - bedrock
2
Load config in your plugin
src/MyPlugin/Main.php
<?phpdeclare(strict_types=1);namespace MyPlugin;use pocketmine\plugin\PluginBase;class Main extends PluginBase { protected function onEnable() : void { // Save default config.yml if it doesn't exist $this->saveDefaultConfig(); // Access config values $enabled = $this->getConfig()->get("enabled", true); $maxPlayers = $this->getConfig()->get("max-players", 10); $this->getLogger()->info("Enabled: " . ($enabled ? "yes" : "no")); $this->getLogger()->info("Max players: " . $maxPlayers); }}
// Get a value (returns null if not found)$value = $this->getConfig()->get("key");// Get with default value$value = $this->getConfig()->get("key", "default");// Get specific types$enabled = $this->getConfig()->get("enabled", true); // boolean$maxPlayers = (int) $this->getConfig()->get("max-players", 10); // int$message = (string) $this->getConfig()->get("welcome-message", "Hi"); // string
// Get all config as array$allData = $this->getConfig()->getAll();foreach($allData as $key => $value) { $this->getLogger()->info("$key = " . json_encode($value));}
// Set a value$this->getConfig()->set("enabled", false);$this->getConfig()->set("max-players", 20);// Set nested value$this->getConfig()->setNested("spawn.x", 100);$this->getConfig()->setNested("spawn.y", 64);// Save changes to disk$this->getConfig()->save();
Changes to the config are only saved in memory until you call save()!
// Reload from disk (discards unsaved changes)$this->reloadConfig();// Common pattern in reload command:public function reloadPlugin() : void { $this->reloadConfig(); $this->loadConfigValues(); // Re-read config values $this->getLogger()->info("Config reloaded!");}
protected function onDisable() : void { $this->getConfig()->save();}
Cache config values:
// Don't do this in hot code:$max = $this->getConfig()->get("max-players");// Instead, cache in onEnable:private int $maxPlayers;protected function onEnable() : void { $this->maxPlayers = (int) $this->getConfig()->get("max-players", 10);}