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

余生颓废 提交于 2020-01-16 21:59:44

问题


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 inside 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');

回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/2067251/what-is-the-best-way-to-pass-or-access-other-objects-in-other-classes-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!