views:

159

answers:

3

In CakePHP, how can I make an array we use accessible by the whole application? Is there an equivalent of PHP's define() function?

+2  A: 

I normally use the "bootstrap.php" file located in the "config" folder.

Jefe
A: 

If you don't want to "limit" yourself to what CakePHP gives you, you can either use a global variable (yukk) or simply wrap it in a class:

class Foo {
    public static $bar = { 3, 7, 42 };
}

Or use the singleton-pattern:

class Foo {
    private static $instance = null;
    public $myVar;

    private function __construct() {
        $this->myVar = { 3, 7, 42 };
    }

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

Then you can do:

var_dump(Foo::$bar);

or

var_dump(Foo::getInstance()->myVar);
n3rd
well i use a bit of both in the bootstrap.php i set up the singleton-pattern. Thanks alot guys
Giancarlo
+12  A: 

Use the Configure class.

In app/config/bootstrap.php:

Configure::write('myArray', array(1,2,3));

Then anywhere in your app, e.g. models, views, controllers, helpers, behaviors, components etc etc just access it using:

$myArray = Configure::read('myArray'); // $myArray will contain array(1,2,3)

neilcrookes
Neil is right on. But Please keep in mind that sharing data globally like this can be a big time indicator of poor design and data flow. So use this wisely.
felixge