Custom configuration files in CakePHP 3
Asked Answered
A

1

5

I have a CakePHP 3.3.14 application where I've created 2 subdirectories, webroot/data/downloads/ and webroot/data/master

I want to put these paths in a custom configuration file and reference them in a Controller. But I can't see how to do this.

I've followed the documentation on Configuration but it's not very clear.

So what I've done:

  • Created config/my_config.php
  • The above file defines an array:

    return [ 'downloadsPath' => 'webroot/data/downloads/', 'masterPath' => 'webroot/data/master/' ];
    
  • In config/bootstrap.php I've put: Configure::load('my_config', 'default');

How do I then use this in a Controller? If I put Configure::read('my_config.masterPath'); it gives an error saying: Class 'App\Controller\Configure' not found

If I add use Cake\Core\Configure; to the top of my Controller, that clears the error but the return value is null:

debug(Configure::read('my_config.masterPath')); // null 
Arsenic answered 28/3, 2017 at 9:24 Comment(4)
What exactly is unclear about this section that even contains examples? book.cakephp.org/3.0/en/development/…Antihero
Well, if you reference what I've actually written above with what's written there, it is quite unclear as to where I'm going wrong in my opinion. That's why I've posted the question...Arsenic
Your read call is simply wrong. 'my_config.masterPath'no idea from where you've got the idea that you have to put the file name in front. masterPath should work.Antihero
The reason I was doing it like that is because the way I (mis)understood the documentation was that you had to tell it which config file the value was specified in. For example if you had 3 config files and they all had an array key masterPath that would surely present some problem? Thanks for the advice though, I can see the error of my ways..Arsenic
S
7

Loading another config file just extends the default App.config. So just use \Cake\Core\Configure::read('masterPath') and you are good.

EDIT

If it is your goal to have different config paths you could do it like this:

// my_config.php
return [
    'MyConfig' => [
        'masterPath' => '...',
        ...
    ]
];

Then use the config like this:

<?= \Cake\Core\Configure::read('MyConfig.masterPath') ?>
Swat answered 28/3, 2017 at 11:44 Comment(3)
Also you need to add Configure::load('my_config', 'default'); in bootstrap.phpOrford
how can i write into this file ?Pluviometer
@ManojKumar book.cakephp.org/3.0/en/development/…Berton

© 2022 - 2024 — McMap. All rights reserved.