phpoctobercms

How to extend relation Config October CMS


how to extend controller to add a config relation fileds.

for now i found that i can add a new file like this

 myController::extend(function($controller){

$controller->relationConfig = '~/plugins/path/languages/config_relation.yaml';
        }); 

in this situation the method erase my config files already exist and add a new one so it trigger an error because the others already relation behavior not exist.


Solution

  • This was recently discussed and documented here:

    myController::extend(function($controller) {
    
        // Implement the relation controller if it doesn't exist already
        if (!$controller->isClassExtendedWith('Backend.Behaviors.RelationController')) {
            $controller->implement[] = 'Backend.Behaviors.RelationController';
        }
    
        // Implement the relationConfig property with our custom config if it doesn't exist already
        $myConfigPath = '~/plugins/path/languages/config_relation.yaml';
        if (!isset($controller->relationConfig)) {
            $controller->addDynamicProperty('relationConfig', $myConfigPath);
        }
        else {
            // Ensure that we have an instantiated config object to work with
            $config = $controller->makeConfig($controller->relationConfig);
    
            // Instantiate our custom config object to work with
            $myConfig = $controller->makeConfig($myConfigPath);
    
            // Merge the above two
            $controller->relationConfig = (object) array_merge((array) $config, (array) $myConfig);
        }
    }
    

    The following function is new and currently in develop branch:

    public function mergeConfig($configA, $configB)
    {
        $configA = $this->makeConfig($configA);
        $configB = $this->makeConfig($configB);
        return (object) array_merge((array) $configA, (array) $configB);
    }
    

    So in future, after develop branch is merged into master, you will be able to use the following code to merge configs:

    UsersController::extend(function($controller) {
    
        // Implement behavior if not already implemented
        if (!$controller->isClassExtendedWith('Backend.Behaviors.RelationController')) {
            $controller->implement[] = 'Backend.Behaviors.RelationController';
        }
    
        // Define property if not already defined
        if (!isset($controller->relationConfig)) {
            $controller->addDynamicProperty('relationConfig');
        }
    
        // Splice in configuration safely
        $myConfigPath = '$/myvendor/myplugin/controllers/users/config_relation.yaml';
    
        $controller->relationConfig = $controller->mergeConfig(
            $controller->relationConfig,
            $myConfigPath
        );
    
    }