Skip to content

When there is a method to get an object, always use it!

2012 May 16
by Richard Knop

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:

  1. $request = new Zend_Controller_Request_Http;

Instead of using the getter method:

  1. $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.

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS