phpcakephpcakephp-3.xcakedccakephp-3.4

Dynamically Loading Plugin Configuration Files in CakePHP 3


Question: How do I load a configuration file from a Plugin/config Directory?

Demo Project: https://github.com/CakePHPKitchen/CakeDC-Users-Permissions-Example

I am using CakeDC/users plugin and it has a permissions.php file that it loads the RBAC permissions from. From what I can tell, it either loads the default permissions file that is in the user plugin's config folder OR it loads the permissions.php file from the app/config folder.

Now for my app skeleton I have a bunch of permissions in the app/config/permissions.php, however, I do not want to modify that file as I will be doing git pulls from the upstream repo and I would like to avoid conflicts.

So what I would like to do is, in the app skeleton bootstrap

I would like to

foreach(Plugin::loaded() as $plugin) {

     $path = Plugin::path($plugin) . 'config/permissions.php';

     if(file_exists($path)) {

        Configure::load($path, 'default', true);
     }
}

But I am getting the following error....

 Error: The application is trying to load a file from the /Users/jlroberts/Projects/JeffreyLRobertsCom/CakePHPKitchen/PluginDemos/plugins/SharpAgent/config/permissions plugin. 

 Make sure your plugin /Users/jlroberts/Projects/JeffreyLRobertsCom/CakePHPKitchen/PluginDemos/plugins/SharpAgent/config/permissions is in the /Users/jlroberts/Projects/JeffreyLRobertsCom/CakePHPKitchen/PluginDemos/plugins/ directory and was loaded.

Any ideas on how I can load the permissions.php file from the Plugin/config directory?


Solution

  • EDITED: You can load permissions.php file from the Plugin as it is doing now, but change the contents of permissions.php to preserve existing permissions defined in configuration, for example:

    config/permissions.php

    $permissions = [
        // add your app permissions here
        [
            // ...
        ],
    ];
    
    // there are more permissions in this config key, defined across your plugins
    $morePermissions = \Cake\Core\Configure::read('MyPermissions');
    $allPerms = array_merge($permissions, $morePermissions);
    
    return ['CakeDC/Auth.permissions' => $allPerms];
    

    Then inside each plugin you could have:

    YOUR_PLUGIN/config/bootstrap.php

    $permissions = \Cake\Core\Configure::read('MyPermissions');
    $someMorePermissions = [
        [
            // permissions injected into the app from this plugin
        ]
    ];
    
    $permissions = array_merge((array)$permissions, $someMorePermissions);
    \Cake\Core\Configure::write('MyPermissions', $permissions);
    

    Allowing each plugin to dynamically inject/manage permissions into the app.

    I've created a c9.io environment with this code here https://ide.c9.io/steinkel/users-35-custom-permissions