When there is a method to get an object, always use it!
I have just learned an important lesson. When using a framework (doesn’t matter if it’s Zend Framework, Symfony or anything else), always use a getter method of the controller object if available. There usually is a reason for why it exists. Simple example.
I was writing some controller unit tests in Zend Framework extending Zend_Test_PHPUnit_ControllerTestCase. Inside my controller I was creating a new instance of a request object like this:
$request = new Zend_Controller_Request_Http;
Instead of using the getter method:
$request = $this->getRequest();
The unit tests were failing and I did not understand why. The issue was that I was using an authentication controller plugin which checked for an authentication header and redirected request to a different controller action when the request did not have the correct header.
Of course, I had 100% coverage of the authentication plugin so I was sure the problem was inside the controller. It was simple – by creating a new instance of the request class, I was dropping any headers from the request. Therefor, all my controller tests were being redirected to a different action by the plugin, even the tests that were supposed to simulate a correctly authenticated request.
Using the getter method to get the request object solved the mysterious issue.