Nizmon
Nizmon

Reputation: 43

PHP Form Validation Best Practice

This isn't so much of a how do you do something, but more of a best practice question.

I'm building a simple login application for an internal project using the php-advanced-login framework. The way I'm validating the login form, password reset and login via cookie using using a class that is initialized when a user submits the form. The class then validates everything and any errors are returned in an array and shown in the form.

<?php if(isset($_POST['submit_login'])){
//load class
}
<!doctype html>
//form

My questions is, having everything in this class seems like a bit of a mess (it seems like it's harder to maintain than how I use to do it explained further on), it's all in there because there is lots of code re-use. The way I've done it before is just to split my code up into several php files with functions and just include them when needed. Each php file is a lot shorter and easier to maintain in my opinion. I don't use any real advantages of using a class over just methods.

Whats your opinion on this if you've managed to follow my rambling? Should I use a class and have everything together, just use functions, another better way?

Upvotes: 0

Views: 351

Answers (1)

mickadoo
mickadoo

Reputation: 3483

Since you mentioned in the comments that you don't want to use a framework I think the cleanest way to do this is at least mimic some of the features of most frameworks. This includes:

  • Creating a logical directory structure. You might have directories for config, validation, utilities, view, model. It should be obvious where to look for something. If your app ever grows to the point where you will need to migrate to a framework having a similar structure will be helpful
  • Create classes that have one function. You could do this with functions, but having all the functions available to you at global level clutters things up. You might have functionality to check if a password is valid. For this you'd maybe hash the input password, load the user from the database and compare the stored password with the user's one. To make your functions nice and neat you could split this up. However without an object encapsulating this you'd now have x number of functions available globally. You may also need variables for storing the hashing algorithm parameters. Other areas of the code won't need to use this, so hide them inside an object.
  • Keep shared functionality in small simple classes that can be used as required. Something like reading a cookie might be used in a few places. In this case I think objects don't have much benefit over classes, however if you want to write tests (and I highly recommend you do) you'll find it easier to use testing frameworks (PHPUnit, PHPSpec) with objects. You also never know when you're "simple function" will become more complex

BTW The github repo you linked to is unmaintained

Upvotes: 1

Related Questions