How to? - Process a form using PHP (OOP style)

Posted on August 6, 2014, 1:20 pm by about-dev.com


In this post I'll show you how you can transform some procedural code into an OOP code in PHP. What OOP code means? Well, instead of using procedural PHP and some collections of functions (predefined or user-defined), we will structure our code using classes (defined by user or already defined in PHP). OOP stands for Object-Oriented Programming.

I'll use the procedural code from this post. So I have to process the information from a form: to validate them, to save them into database and to notify the user about what happend. For an easy understanding of this process I'll take it by steps.

Step 1: define the new structure of our existing project

/form_application/index.php                     --> this file contains the HTML form & processes the information sent by th user
/form_application/classes/Validator.php    --> this file contains a class that takes care of data integrity and will generate some error                                                                                         messages when the information from the user is not ok
/form_application/classes/Db.php            --> this file contains a class that represents our connection with the database; the operations                                                                                   should be: connect to the database, disconnect from the database, execute a query to                                                                                         database, get the results from the database 
/form_application/classes/User.php          --> this file contains a class that will play the role of a "database model", an object that is created based                                                                   on a database table structure; the operations should be related to this object characteristics (getters                                                                     and setters using the OOP language)

In this structure you will see that I've separated the database operations (connect, CRUD, disconnect) from the user entity because we can use that operations to several other entities. This separation can be extended: you can make the Db class abstract and define a MySQLi class or MySQL class or whatever driver you'll use, that must extend the abstract Db class. You can also create an abstract Model class, that can be extended by the User class and whatever model entity you'll have.

Step 2: define the Validator.php class

This class will contain the following methods:

public function __construct(array $params = array()){//some code here for class constructor used to instantiate this class}
public function validate(){//some code here used to validate data}
public function getIsValid(){//some code here used as getter method for private isValid property}
public function getErrors(){//some code here used as getter method for private errorMessages property}

and properties:

protected $isValid       = true;   /*
                                 used to test the validity of data (if data is                                                                                                                    
                                 invalid this property will be false, otherwise                                       
                                 will be true)
                               */
protected $errorMessages = array();  // used to collect error messages
protected $data          = array();  // used to locally store data (user data)

Step 3: define the Db.php class

This class will contain the following methods:

public function __construct(array $config = array()){//some code here for class constructor used to instantiate this class}
public function connect(){//some code here used to connect to a database server and to select a database}
//some methods for the CRUD operations (create, replace, update, delete)
public function save($object){//some code here - insert & update}
public function select($object){//some code here}
public function delete($object){//some code here}
public function disconnect(){//some code here used to disconnect form the DB server}
public function getConnection(){//some code here used as a getter method for the $conn property}

and properties:

/*
 $config = array(
  'host'  => '...',
  'user'  => '...',
  'password' => '...',
  'db_name' => '...',
 )
*/
protected $config = array();
protected $conn = null;

Step 4: define the User.php class

This class will contain the following methods:
public function __construct(array $params = array()){}

//some specific getter methods for this class private properties
public function getId(){}
public function getFirstName(){}
public function getLastName(){}
public function getEmail(){}
public function getUsername(){}
public function getPassword(){}
public function getAddress(){}

//some specific setter methods for this class private properties
public function setId($value){}
public function setFirstName($value){}
public function setLastName($value){}
public function setEmail($value){}
public function setUsername($value){}
public function setPassword($value){}
public function setAddress($value){}

//general getter and setter
public function __get($name){}
public function __set($name, $value){}

public function getData(){//some code here used to get an array with key=>value pairs for this class properties}

and properties:

//user entity properties
private $id;
private $firstName;
private $lastName;
private $email;
private $username;
private $password;
private $address;

Step 5: change the code from index.php file to use and load the above classes

if(!empty($_POST)){
            require_once('functions.php');

            $errors         = array();
            $validatorObj   = new Validator($_POST);
            $validatorObj->validate();
            if($validatorObj->getIsValid()){
                // create user object for OOP manipulation
                $userObj = new User($_POST);

                // save user object data into DB
                $dbObj = new Db(array('host'=>'localhost', 'user'=>'root', 'password'=>'', 'db_name'=>'test'));
                $dbObj->connect();
                $saved = $dbObj->save($userObj);
            }else{
                $errors = $validatorObj->getErrors();
            }
}
if(!empty($errors)):
    echo 'Please correct the following errors:';
    if(is_array($errors)):
        foreach($errors as $val):
            echo $val;
        endforeach;
    endif;
elseif(!empty($saved) && $saved == true):
    echo 'Thank you!';
    $_POST = array();
endif;

You can see that in index.php we require the functions.php file. Now this file contains one function:

function __autoload($className){
    $path = 'classes/';

    if(!empty($className) && file_exists($path.$className.'.php')){
        require_once($path.$className.'.php');
    }
}

This function is automatically used by PHP to autoload our classes so that we can use them directly, without including them separately.

Step 6: test the code

Now we have to test our code, to see if the form will be validated and if the information goes where we wanted to: into our users table.
Type the following URL into your client: http://localhost/form_application    (this will point to the index.php file which keeps your form)

You'll be able to fill the form with some values and test the validation and the saving part.

Stay tune for the "framework" style.

Download source fileshttps://github.com/about-dev/php_form_processing_oop

Related articles:


Leave a Comment:

User
Email
Website

Blog Search

Popular Blog Categories

Newsletter

Want to be informed about latest posts? Subscribe to our newsletter