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
2009-05-25 22:41:15
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
2009-05-25 23:16:14
well i use a bit of both in the bootstrap.php i set up the singleton-pattern. Thanks alot guys
Giancarlo
2009-05-25 23:51:20
+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
2009-05-26 07:39:01
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
2009-06-03 16:39:07