在PHP中传递或访问其他类中的其他对象的最佳方法是什么? [英] What is the best way to pass or access other objects in other classes in PHP?

查看:91
本文介绍了在PHP中传递或访问其他类中的其他对象的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助规划如何在PHP中我的课。我有一个会话类和数据库类,我几乎需要访问每个其他类我使用(论坛,邮件,用户,更多的类)



我正在寻找我应该如何访问会话类里面的其他类,1选项是使其GLOBAL,另一个是传递$ session和$数据库对象到每个类我使用像这样...

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

但是如果我要为15+个不同的类做这件事,这似乎很乏味?有更好的方法吗?



以下是我在其他类中调用的会话类中的一些方法的示例。

  //将值设置为session 
$ session-> set('auto_id','auto_id'的一些值)

//从会话中获取值
$ session-> get('auto_id');


解决方案

a href =http://martinfowler.com/eaaCatalog/registry.html =nofollow noreferrer>注册表模式。这是一个非常好的说明



注册表模式就像对象的存储。



代码示例就是这样。 / p>

编辑:



在你的例子中(new Mail($ session,$ database)),即使您使用注册表模式也要这样做。这使得每一件事都更少的耦合,更容易理解和独立地改变部件。因为我在过去几年里没有这么多PHP,我不知道是否有任何IOC框架可用,但这将帮助你实例化你的类。


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

解决方案

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.

这篇关于在PHP中传递或访问其他类中的其他对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆