Username verification class Everything in this code is completely working, but I still feel that this code needs to be refactored. any suggestions? 

&lt;?php
    class Db_CheckUsername{
        protected $_conn;
        protected $_username;
        protected $_minimumChars = 8;
        protected $_errors = array();

        public function __construct($username, $conn){
            $this-&gt;_username = $username;
            $this-&gt;_conn= $conn;
        }

        public function check(){

            $sql = "SELECT * FROM accounts WHERE username = '{$this-&gt;_username}'";

            $result = $this-&gt;_conn-&gt;query($sql);
            $numRows = $result-&gt;num_rows;

            if(preg_match('/\s/',$this-&gt;_username)){
                $this-&gt;_errors[] = "Spaces are not allowed";
            }

            if($numRows &gt; 0){
                $this-&gt;_errors[] = "Username Taken";
            }

            if(strlen($this-&gt;_username) &lt; $this-&gt;_minimumChars){
                $this-&gt;_errors[] = "Username Should Contain, atleast {$this-&gt;_minimumChars} chars";
            }

            return $this-&gt;_errors ? false : true;
        }

        public static function isUsernameCorrect($username,$conn){

        }

        public function getErrors(){
            return $this-&gt;_errors;
        }
    }
I meant to write one or two brief points when I started writing this, but erm, ended up a bit more :).  Anyway, some of the stuff is quite briefly explained, so if anything needs more elaboration/defense, let me know and I'll edit in more information.

SQL Injection

Your query that checks for the username is open to SQL injection.  You should use prepared statements.

Don't pass in the username

If you pass the username to check() instead of to the constructor, the object can be reusable.

public function check($username) { ... }


Allow configuration

You might as well allow $_minimumChars to be configured.  There's a lot of ways to go about this, but as long as it's only one configuration item, the easiest way would be an argument in the constructor:

public function __construct(mysqli $conn, $minimumChars = 8)
{
    $this-&gt;_conn = $conn;
    $this-&gt;_minimumChars = $minimumChars;
}


Be strict about types when possible (and reasonable)

If the signature is:

public function __construct(mysqli $conn, $minimumChars = 8)


And the object is created accidentally with something that is not an instance of mysqli, the error will be caught much sooner than if the strict check is not there.  Not particularly required, just there's not a very strong reason against it.

Break it up into more classes -- Part 1 - Validators

The benefit of this is very arguable with a small code base, however, later down the road, it will likely be nice.  Consider breaking each validation into its own class:

interface Validator {
    public function isValid($input);
    public function getErrors();
}

//Because I'm lazy :p
class Validator_AbstractValidator {

    private $_errors = array();

    abstract public function isValid($input);

    public function getErrors()
    {
        return $this-&gt;_errors;
    }

    protected function _addError($message) {
        $this-&gt;_errors[] = $message;
    }

}

class Validator_NoSpaces extends Validator_AbstractValidator {
    public function isValid($input) {
        //You would probably want to add a check that $input can be cast to a string
        if (preg_match('/\s/', $input)){
            $this-&gt;_addError("Spaces are not allowed");
            return false;
        }
        return true;
    }
}

class Validator_MinimumLength extends Validator_AbstractValidator {

    protected $_minLength;

    public function __construct($minLength)
    {
        if (!is_int($minLength) &amp;&amp; !ctype_digit($minLength)) {
            throw new Validator_Exception("minLength must be an integer");
        }
        $this-&gt;_minLength = (int) $minLength;
    }

    public function isValid($input)
    {
        //Once again, should probably have some kind of validation that $input
        //can be cast to a string
        if (strlen($input) &gt; $this-&gt;_minLength) {
            return true;
        } else {
            $this-&gt;_addError("Input must be at least {$this_minLength}");
            return false;
        }
    }

}


The advantage of this is that it allows you to abstract away the idea of validations, and it allows you to centralize the management of validation rules.  For example, suppose that your username and email address fields both had the requirement that they not contain spaces.

Now, what if you want to change the logic from the regular expression, to a more strict, strpos($input, ' ') === false?  If the validations are all abstracted away, you only have to change this code in one place.  If you've repeated the low level validations inside of your Db_CheckUsername, you have to change it in two places.  (This is one of the major aspects of DRY by the way.)



You may have noticed that the error messages are hard coded.  This would likely not be the desired behavior.  What you could do there is store the errors in some kind of array indexed by error type, and then instead of _addError adding a raw message, it would add an error type (which would map to an error).  (Note: this approach is 100% stolen from the Zend Framework validators :))

Break it up into more classes -- Part 2 - Element

This obviously leaves your code in a rather awkward spot, though the obvious solution of replacing the validations in the check method with the validators is essentially the solution.

What I would do is abstract away the idea of form element.  You could take the idea as far as a you want (rendering, data manipulation, so on), but I'll just focus on validation:

//We want the element to have an isValid method and a getErrors method()
//(you could make a separate interface for this, but really an element is
//just a collection of Validator instances)
interface Form_ElementInterface extends Validator { }

class Form_Element_AbstractElement extends Validator_AbstractValidator implements Form_ElementInterface
{

    protected $_validators = array();

    public function addValidator(Validator $validator)
    {
        $this-&gt;_validators[] = $validator;
    }

    public function getValidators()
    {
        return $this-&gt;_validators;
    }

    protected function _addErrors(array $errors)
    {
        foreach ($errors as $error) {
            $this-&gt;_addError($error);
        }
    }

    public function hasErrors()
    {
        return (count($this-&gt;getErrors()) !== 0);
    }

    public function isValid($input)
    {
        foreach ($this-&gt;_validators as $validator) {
            if (!$validator-&gt;isValid($input)) {
                $this-&gt;_addErrors($validator-&gt;getErrors());
            }
        }
        return !$this-&gt;hasErrors();
    }

}

class Form_Element_Username extends Form_Element_AbstractElement
{
    public function __construct($minLength = 8)
    {
        $this-&gt;addValidator(new Validator_NoSpaces());
        $this-&gt;addValidator(new Validator_MinimumLength($minLength));
        //...
    }
}


Some of the names have gotten a little bleh, but hopefully the concept is still there.  (I can never decide what to name interfaces/abstract classes...)

I don't particularly like the design of Form_Element_Username there.  I would probably just use the elements from the outside instead of creating a complicated graph of objects and dependencies (a mysqli would have to be passed through there for example).

$username = new Form_Element();
$username-&gt;addValidator(new Validator_NoSpaces());
$username-&gt;addValidator(Validator_UserNotExists($db));


Or if you decided to take the flexible error message route, it may look like:

$username = new Form_Element();
$username-&gt;addValidator(new Validator_NoSpaces(array(
    'messages' =&gt; array(
        Validator_NoSpaces::CONTAINS_SPACE =&gt; "Usernames cannot contain spaces"
    ),
)));
$username-&gt;addValidator(Validator_UserNotExists(array(
    'db' =&gt; $db,
    'messages' =&gt; array(
        Validator_UserNotExists::USERNAME_EXISTS =&gt; "The username provided already exists",
    ),
)));


Note that passing in an array of arguments instead of proper separate parameters is often bad practice.  (In fact, it's definitely bad practice here.)  It has the advantage though of allowing you to easily store data in config files and then construct validators based on that.

Break it up into more classes -- Part 3 - Form

(Not going to write code on this as the concept should be clear by now.)

Just as an Element is a collection of validations, a form is, in a lot of ways, just a collection of elements.  You could extend the idea of elements and validators to entire forms which would provide centralized management of form logic, and much cleaner use than the 10-20 lines it would take to make each element in the way presented above.

class Form_UserRegistration extends Form_AbstractForm
{
    //In the constructor or some kind of setup method (called by the abstract constructor),
    //you would want to a username element, a password element, and so on
}


Then the usage:

$errors = null;
$regForm = new Form_UserRegistration();

if ($_SERVER['REQUEST_METHOD'] === "POST") {
    if ($regForm-&gt;isValid($_POST)) {
        //Create the user
    } else {
        //Render these under the form or something
        $errors = $regForm-&gt;getErrors();
    }
}


Design note

It's a bit of an odd design to mutate the errors array behind the scenes while only returning a bool from isValid.  In particular, it may be a bit cleaner design to directly return the array of errors.  I didn't go with this approach because it complicates use of the objects, and the framework I'm most familiar with does it with two separate methods, so it's just what I'm used to.

Basically, the isValid method could look like:

For completeness:

public function validate($input) {
    $errors = array();

    if (...) {
        $errors[] = "...";
    }

    return $errors;

}

//Usage:
$errors = $obj-&gt;validate($input);
if (count($errors)) {
    //errors
} else {
    //success
}


(Or you could return true in place of the empty array)

ZF Credit

I should mention that Validator and Element concepts are highly based on the Zend Framework Zend_Validate_Interface and Zend_Element_Abstract classes.