Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In "The Clean Code Talks -- Unit Testing", Miško Hevery mentions that "as little work as possible should be done in constructors [to make classes more easily testable]'. It got me thinking about the way I have implemented my user authentication mechanism.

Having delved into MVC development through CodeIgniter, I designed my first web application to perform user authentication for protected resources in controllers' constructors in cases where every public function in that controller requires the user to be authenticated.

For controllers with public methods having mixed authentication requirements, I would naturally move the authentication from the constructor to each method requiring authentication (though I don't currently have a need for this).

I made this choice primarily

  1. to keep the controller tight, and
  2. to ensure that all resources in the controller are always covered.

As for code longevity and maintainability: given the application structure, I can't foresee a situation in which one of the affected controllers would need a public method that didn't require user authentication, but I can see this as a potential drawback in general with this implementation (i.e., requiring future refactoring).

Is this a good idea?

share|improve this question
up vote 1 down vote accepted

This is what I do too.

The simplicity of the code for checking authenticaton in the construct is more favorable to me (the construct is not too fat either).

I check the minimal permission required in the construct and individual permissions in the individual methods.

If all the method of the controller require same and only minimal permissions, i just put them in the construct.

One other form of the implementation is separating the controller for Authenticated users.

The backend controllers would extend 'Admin_Controller' which checks authentication in its construct, thereby restricting any operations it the user is not authenticated.

This makes the code more reusable and reliable.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.