My personal opinion is if your function has any external dependencies (within it or passed to it) static isn't really a good candidate. Static was primarily with the idea that your class/method has zero dependencies on the class itself and externally.
Here is an example of what I'd consider an acceptable static method (granted many will still disagree with using static period!, but the below is still easily testable)
PHP Code:
class FileType
{
public static function getExtension($filename)
{
// pretend I did error checking on file length, etc)
return substr($filename, strrpos($filename, '.'));
}
}
Both the class and the method getExtension don't require anything but a string with the file name in it. There isn't any class variables or external dependencies it needs to worry about (thus testing is very straight-forward).
Once you introduce dependencies, you are better off with an instantiated object so you can mock the dependencies/implementation. If you still want to ensure only one connection is established, there are ways of introducing a singleton pattern within an instantiated class, that still gives you the benefits of mocking (there is an example of that somewhere in this forum...I'd have to spend some time searching for it).
Anytime you talk Testing and your class/method has dependencies to external sources (be it other classes, a database, another server, whatever), DI is a great option and in my opinion, a must have. Otherwise, your tests are going to be fragile and need to be updated on a regular basis as changes are made.
Bookmarks