Loading custom config for a CakePHP plugin

in CakePHP


Say you're creating a plugin that integrates some ExampleAPI and you need to store the API client configuration. You will have to create a custom config file inside your plugin, then tell the plugin bootstrap to load the config file. Finally, make sure you're loading your plugin with the bootstrap flag.

  1. Create your custom config file under plugins/ExamplePlugin/config/ExampleAPI.php with the following content:

     [ // group
            'host' => '',
            'username' => '',
            'key' => '',
        ],
    ];
  2. Create the plugin bootstrap file plugins/ExamplePlugin/config/bootstrap.php:

  3. In your src/Application.php:

    Note: 'bootstrap' => true is required

    $this->addPlugin('ExampleAPI', ['bootstrap' => true, 'routes' => false]);
    // ExampleAPI matches the plugin name
    // the bootstrap flag tells the app to execute the bootstrap file
    // the routes flag is specific to my use case, this plugin is for external API only, so no need for any routes

Note: be careful with configuration settings because plugin config files will override matching app settings, it is better to name settings with a plugin prefix

Finally, when you need to read the configuration, call \Cake\Core\Configure::read('ExampleAPI'); where ExampleAPI matches the config group. If you're trying to read the config inside plugins/ExamplePlugin/src/Plugin.php, make sure you do it after the parent::bootstrap($app) call.

Sources:

#cakephp #api #cakephp-plugin-development