0

In OOP PHP witch is better to let a factory return, new instance or the same instance, when it comes to performance and unit testing.

Eg. is creating new instances each time a class is to be used considered bad practice?

user555
  • 1,564
  • 2
  • 15
  • 29

2 Answers2

3

You dont want to have Factories return the same instance. You want them to return new instances. That's the point of a Factory. Singletons have no use in PHP. If you want to limit an instance to just one instance, then create it once and inject it where it is needed.

Performance-wise it is negligible whether you return the same instance or create a new one. That is, unless you are doing very costly work in the ctor (like connecting to a database), which you shouldnt anyway.

For unit-testing, you want your Factories to return fresh instances and not the same ones, because that would be global state. Test should happen in isolation and not with the state of some instance from a previous test still in place, because that is more error prone.

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
1

Returning the same instance is best suited for the Singleton Pattern. Factories shouldn't care what they're returning... only that it fits certain criteria.

If your factory is returning a database connection, it's probably best if it returns a singleton connection instead of creating a new one.

Mike B
  • 31,886
  • 13
  • 87
  • 111