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.

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法