views:

66

answers:

1

I have read many times on the web that when dealing with dependency in PHP that it is good to use dependency injection instead of Globals because it makes it easiar to test. Can someone explain how this make it easiar to test? And what I would use to do the test?

+2  A: 

I'd suggest learning about Unit Testing and taking a look at a few tools available for PHP. I would recommend PHPUnit, but there is also SimpleTest, which I know some people prefer.

Minimizing the scope of mutable data is just a good idea in general. As far as testing goes, you can write unit tests that exercise small, atomic pieces of functionality without worrying that variables have been changed as a side effect of some other operation. If you want to test that the state of an object is a, b, or c, you know what you need to test because you know exactly what operations can effect the state. If your state is global, you have no idea what other operations in your application could effect it, leaving you with a difficult to maintain pile of spaghetti.

Joshua Bloch explains this nicely in Effective Java, Item 29. I'd recommend reading that, even if he isn't using PHP, the concept is the same.

As for Unit Testing, I'd recommend Pragmatic Unit Testing published by The Pragmatic Programmers. There are versions for Java / JUnit and C# / NUnit, but the concepts are totally applicable to PHP, especially if you use PHPUnit which follows the xUnit patterns quite closely.

Paul Osman