开发者

What is the best way to pass or access other objects in other classes in PHP?

I need some help in planning out how to do my classes in PHP. I have a session class and a database class that I pretty much need to access inside of every other class I use (forums, mail, users, lots more classes)

So I am looking for how I should access the session class inside of my other classes, 1 option is to make it GLOBAL, another is to pass $session and $database objects into every class I use like this...

$mail = new Mail($session, $database);

but this seems pretty tedious if I have to do it for 15+ different classes? Is there a better way?

Below is an example of some methods from my sessions class that I would be calling insid开发者_高级运维e of other classes.

// set a value into session
$session->set('auto_id', 'some value for auto_id');

// get a value from session
$session->get('auto_id');


For scenarios like this i would make use of the registry pattern. This is a pretty good explanation.

The registry pattern acts like a storage for objects.

A code example is on it's way.

Edit:

In your example (new Mail($session, $database)), i think you should do this even if you use the registry pattern. This makes every thing less coupled and easier to understand and change parts independently. As I have not done so much PHP in the last couple of years, i don't know if there is any IOC-framework available, but that would help you instantiating your classes.


I'd have thought the singleton pattern would be a very good fit in this instance.

There's a nice simple tutorial (with some sample code) over at talkPHP that seems like a reasonable implementation.


For things like sessions and databases, I think global variables are fine here.


I disagree completely with using globals. I would either use the Registry pattern as suggested or make both the Session and DB themselves Singletons, although this will make unit testing much more difficult.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜