-2

I'm trying to learn about Object Oriented Programming and I want to turn this code into such. I've got some knowledge so far from google and here and in particular http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762.

The way I understand it is I need classes that contain a certain set of instructions that can be used with universal objects outside of those classes.

My idea so far has been to set up a User class where names are stored (coming from a HTML/PHP form).

class User {
public $nameStore, $fName, $lName, $email;

   public function __construct ($fName, $lName, $email) {

       $this->$fN = $fName;
       $this->$lN = $lName;
       $this->$eN = $email;
   }

Like the above^. But I'm still confused about where other instructions of my code should go. That's where I need the most help. From what I've read, it hasn't helped me get the full grasp of what I need to do. If someone could help get me started in the right direction on how to make my code into an OOP type I would greatly appreciate it. Thanks!

Below is my procedural code that I want to convert to OOP.

<?php 

session_start();

$formNames = $_POST['names'];

$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used

$email = '@grantle.com';

$fullnames = explode(", ", $_POST['names']);

if ($active == true) {
    $active = '1';
    //sets activate checkbox to '1' if it has been selected
}


/*----------------------Function to Insert User-------------------------*/

function newUser($firstName,$lastName,$emailUser,$active,$conn){
    //a function to insert a user into a database is here
}

//newUser function enters names in database
/*-------------------------End Function to Insert User--------------------*/

/*-----------------------Function for Errors------------------------------*/

function errorCheck($formNames, $nameSplit, $fullname){

    $isValid = false;

        if (empty($fullname)) {
            $_SESSION['error'][] = '<br><br> Error: Name Missing Here: '.$fullname.'<br><br>';
        } elseif (empty($nameSplit[0])) {
            $_SESSION['error'][] = '<br><br> Error: First Name Missing Here: '.$fullname.'<br><br>';
        } elseif (empty($nameSplit[1])) {
            $_SESSION['error'][] = '<br><br> Error: Last Name Missing Here: '.$fullname.'<br><br>';
        } elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
            $_SESSION['error'][] = '<br><br> Error: Illegal Character Found in: '.$fullname.'<br><br>';
        } else {
            $isValid = true;
        }

        return $isValid;
}

//errorCheck function tests for errors in names and stops them from being entered in the
//database if there are errors in the name. Allows good names to go through
/*-----------------------------End Function for Errors---------------------*/

/*--------------------------Function for Redirect--------------------------*/

function redirect($url){
    $string = '<script type="text/javascript">';
    $string .= 'window.location = "' .$url. '"';
    $string .= '</script>';

    echo $string;
}

//redirect function uses a javascript script to redirect user because headers have already been sent.
/*-----------------------------End Function for Redirect-----------------------*/

//  Connect to database
    I connect to the database here//

// Initialize empty error array
$_SESSION['error'] = array();

foreach ($fullnames as $fullname) {
    $nameSplit = explode(" ", $fullname);

    //I open the database here
                //opens the database

    if (errorCheck($formNames, $nameSplit, $fullname)) {

        $firstName = $nameSplit[0];//sets first part of name to first name
        $lastName = $nameSplit[1];//sets second part of name to last name
        $emailUser = $nameSplit[0].$email;//sets first part and adds email extension

        newUser($firstName,$lastName,$emailUser,$active,$conn);//do this BELOW only for names that have no errors

    }//ends if of errorCheck
}//ends fullnames foreach

    if (count($_SESSION['error']) == 0) {
        redirect('viewAll.php');
    } else {
        redirect('form.php');
    }
    /*Redirects to viewAll page only once and as long as no errors have been found*/
Alei
  • 51
  • 1
  • 8
  • 3
    I'm not sure if you'd agree but I found it useful when I learnt OOP to Google search for random PHP classes and then read other peoples classes from gitHub etc, viewing usage examples and seeing how it works. Often "learner" classes are too simple to give practical advise on Real Life uses, so download some gitHub classes and try and use them, then try and make your own..... good luck – Martin Jan 15 '16 at 14:51
  • Thanks, I'll do that – Alei Jan 15 '16 at 14:56
  • Also try to use GET/SET methods to store data in the class : http://stackoverflow.com/questions/10616866/is-it-worth-making-get-and-set-methods-in-oop – Martin Jan 15 '16 at 14:58
  • Also read up on Seperation of Concerns, that's what OOP is for. https://www.google.co.uk/search?q=php+seperation+of+concerns – Martin Jan 15 '16 at 15:32

1 Answers1

0

Your

class User {
public $nameStore, $fName, $lName, $email;

   public function __construct ($fName, $lName, $email) {

       $this->$fN = $fName;
       $this->$lN = $lName;
       $this->$eN = $email;
   }

I would break this up into more specific parts such as GET and SET for each value you are trying to store in the Class:

class User {
    private $fName, $lName, $email;

   public function set_firstname($fname){
       $this->fName = $fname;
}

   public function set_surname($lName){
       $this->lName = $lName;
}

   public function set_email($email){
       $this->email = $email;
}
    public function get_email(){
    return $this->email;
}
    public function get_fname(){
    return $this->fName;
}
    public function get_surname(){
    return $this->lName;
}

Then when you create the class, you can add and return each value individually, rather than forcing yourself to do them all at once. This is more flexible. But you can also add the values at the creation of the class as well if you wish, using the __construct similar to what you had already:

   public function __construct ($fName = null, $lName = null, $email = null) {
       if(!empty($fName)){
           $this->set_firstname($fName);
       }
      if(!empty($lName)){
           $this->set_surname($lName);
       }
       if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false){
           $this->set_email($email);
       }
   }

What this does is for each non-empty value it runs the corresponding SET method. Also checking that the email value is valid before saving it. If no values are passed to the class then it doesn't save anything.

Your setting up of the class is incorrect, firstly you need to include the class file into the working PHP so at the top of your page add:

include "path/to/users.class.php";

And then initiate the class correctly:

    $userClassInstance = new User($firstName,$lastName,$emailUser);

When the above line runs, you will then have a User object containing three variables referenced as $userClassInstance. you can do var_dump($userClassInstance);

Be careful as your code has newUser as one line and also has an incorrect number of variables in the construct statement. Generally all the functions in a page should be placed inside an appropriate class, so all your string management functions such as errorCheck() could be put into the Users class to check the values given before assigning them to the variables in the class.

Finally, to view the stored variables you would then do:

print $userClassInstance->get_fname(); //will outout the value of the class $fName
Martin
  • 22,212
  • 11
  • 70
  • 132