donglu8549 2012-10-04 02:06
浏览 100
已采纳

PHP静态方法/单例模式

I am designing a new architecture for my company's software product. I am fairly new to unit testing. I read some horror stories about the use of singleton and static methods, but I am not clearly understanding the problem with using them and would appreciate some enlightenment.

Here is what I am doing:

I have a multi-tier architecture. At the server side level, I am using a series of reusable objects to represent database tables, called "Handlers". These handlers use other objects, like XMLObjects, XMLTables, different Datastructures, etc. Most of these are homemade, not your prepacked objects. Anyway, on top of this layer is a pseudo-singleton layer. The primary purpose of this is to simplify higher levels of server side code and create seamless class management. I can say:

$tablehandler = databasename::Handler('tablename') 

...to get a table. I don't see the inherent problem with this. I am using a stack of handlers (an associative array) to contain instances of the different objects. I am not using globals, and all static datamembers are protected or private. My question is how this can cause problems with unit testing. I am not looking for bandwagon rhetoric, I am looking for a causal relationship. I would also appreciate any other insight to this. I feel like its an extremely flexible and efficient architecture at this point. Any help here would be great.

  • 写回答

1条回答 默认 最新

  • duancao1951 2012-10-04 04:29
    关注

    Using static methods to provide access to managed instances--whether they be singletons, pooled objects, or on-the-fly instances--isn't a problem for testing as long as you provide a way for the tests to inject their own mocks and stubs as needed and remove them once complete. From your description I don't see anything that would block that ability. It's merely up to you to build it when necessary.

    You'll experience difficulty if you have a class that makes static calls to methods that do the work without an extension point or going through an instance. For example, a call like this

    UserTable::findByEmail($email);
    

    makes testing difficult because you cannot plug in a mock, memory-only table, etc. However, changing it to

    UserTable::get()->findByEmail($email);
    

    solves the problem because the test can call UserTable::set($mock) in the setup code. For a more detailed example, see this answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: