Universally Accessible Data in PHP

Posed under PHP on June 29, 2009.

Article

Comments

Post

Surry

Jul 01 2009

Why don't you store them in sessions?

Evan Byrne

Jul 01 2009

Surry, how would you store an object in a session? I'm talking about data that is accessible from any function or object in your application, not from page to page. I should have made that more clear in the article.

Singleton

Jul 01 2009

You should look at the Singleton and Registry Design Patterns. Your solution is as old as the hills, but ultimately a bad idea. Look up Dependency Injection, instead.

Jordan

Jul 01 2009

You could use sessions as Surry stated, or the $GLOBALS but they are both frowned upon.

I suggest using a Singleton coupled with magic setters and getters. The setters can set any data in an array. Grabbing the instance from the singleton and calling the magic get function will fetch that data.

I created an example on ASCIIBin here: http://www.asciibin.com/HHR

Evan Byrne

Jul 03 2009

That's really cool, thanks for sharing Jordan!

Jordan

Jul 03 2009

No problem! The idea isn't actually mine. I read about it in either PHP Objects, Patterns, and Practice or Pro PHP - Patterns, Frameworks, Testing and More. Both excellent books.

Evan Byrne

Jul 03 2009

Of coarse, I've read about them a little too, they just didn't come to mind for some reason...

Corey Ward

Jul 18 2009

The Zend Framework's "Zend_Registry" does as noted above regarding using a singleton and arrays with magic methods if you're interested in just having something work now without creating your own from scratch.

PS: your captchas are case sensitive if you didn't know.

Corey

Jul 20 2009

I updated the sample script Jordan posted to work more like Zend_Registry where you don't need to instantiate anything to access the data. You can instead use static regular methods.

http://www.asciibin.com/EQB

Post Comment

Capcha