Where to put golbal variable and constant?

EX: we have a
global $extentions;
$extentions = array(
‘jpg’ => ‘jpg’,
‘jpeg’ => ‘jpeg’,
‘gif’ => ‘gif’,
‘png’ => ‘png’
);
and we would like to access it ( $extentions) in view, element, layout, model, controller, I would like to put those variables and constant in one file, where (which folder) can we put the file how we access each variables in the file? and how can we do this without using Configure::read() and Configure::write()?

Thanks,

Not sure if this is necessarily a good practice, but you can define constants in bootstrap.php and then access them anywhere.

For variables, you can set them in the AppController, i.e.

public $myVar = 'test';

And then access them in all other controllers through $this->myVar.

You can also then set them to view in the AppController’s beforeFilter:

$this->set('myVar', $this->myVar);

However, you won’t be able to use them in the models in this way; You’ll need to instantiate the AppController for instance like this:

use App\Controller\AppController;

public function test()
{
    $app = new AppController();
	
    $myVar = $app->myVar;
    ...

Which isn’t really ideal.

So if you need these variables in the models, a better way may be to reverse it and set them inside of a model instead of the AppController.

You’ll be able to access them for instance like this:

$this->Users->myVar;

Perhaps someone else knows of other (and maybe better) ways.

1 Like