0

I'm having hard times, learning desing patterns. And, I've been reading quite a lot. But, I'm only interested to know, about two things: Adapter & Factory patterns.

From what I undestood, (which is close to nothing)
Factory Pattern helps create objects on the fly
Adapter Pattern helps adapt your class from changes made externally.

That is the only thing I undetood. Which is why, I am looking for simples possible, practical examples on either both if possible. on how to use them. So, I am providing just, two simple classes, only to help any demostrate the purpose of the two patterns I mentioned. And, How they can improve my classes, or do anything helpful.

Let's say, this class helps check somethings in a string.

 class Sanitize{

     public $errors = []; 

    function checkEmail($email){
        if(!isset($email) || empty($email)){
            return $this->error = ' <em> Email is required </em>';
        }else if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
            return $this->error = ' <em> Please enter a valid email address </em>';
        }else if(strlen($email) > 40){
            return $this->error = ' <em> Email should be less than 40 characters long </em>';
        }else{
            return true;
        }
    }


    function checkPassword($pass, $re_pass, $min, $max){
        if(empty($pass) && empty($re_pass)){
            return  $this->error = ' <em> You must enter a password to register </em>'; 
        }else if($pass !== $re_pass){
            return  $this->error = ' <em> Your passwords are not the same </em>'; 
        }else if(strlen($pass) < $min || strlen($pass) > $max){ 
            return  $this->error = ' <em> Passwords should be between, $min to $max characters in length </em>';
        }else{
            return true;
        }
    }

    function Check_Age($year, $month, $day){
        if($year > date('Y')-13){
            return $this->error = '<em> You must be over 13 years old, to register </em>';
        }else{
            return true;
        }
    }


    function checkErrors(){
       return $this->errors; 
    }



 }

And, let's assume this class helps with database queries.

class QueryClass{
    public $conn;
    private $error;

    function __construct($conn){
        $this->conn = $conn;
    }


    function checkExsitingData($column, $table, $value, $input){

        try{  $stmt = $this->conn->prepare("SELECT $column FROM $table WHERE $value = ?");
              $stmt->execute(array($input));
        }catch(PDOExeption $e){
                return $this->error = ' Unknown error occured. Please try again later.';
        }

        if($stmt->rowCount() !== 0){
            return $this->error = ' This email is already registred, please try password recovery or create new account ';
        }else{
            return true;
        }
    }




    function registerPerson($P){

        try{  $stmt = $this->conn->prepare("INSERT INTO clients (person_name, timeof_reg) VALUES (?, NOW())");
              $stmt->execute(array($P['username']);
        }catch(PDOExeption $e){
                return $this->error = '<em> Date could not be submitted into database </em>';
        }
    }


        // for "contact us" page form
    function guestbookSubmit($table, $P){

        try{
                $stmt = $this->conn->prepare("INSERT INTO $table (username, email, telephone, message) VALUES (?,?,?,?) ");
                $stmt->execute(array($P['username'], $P['email'], $P['telephone'], $P['message']));
        }catch(PDOException $e){
                return $this->error = '<em> Some errros occured while sending your email. Please try again later </em>';
        }

        if($stmt->rowCount() === 0){
            return ' <em> Your Details, could not be submitted </em>'.spy($stmt->conn);
        }else{
            return true;
        }

    }



    function insertToDatabase($tableName, $postGlobal = []){

        $stmt = $this->conn->prepare("INSERT INTO clients (company, tel, city, email, category)
                                      VALUES (?,?,?,?,?)
            ");

        $stmt->execute( array(
                        $postGlobal['company'],
                        $postGlobal['tel'],
                        $postGlobal['city'],
                        $postGlobal['email'],
                        $postGlobal['category']
                  )
          );

        return ($stmt->rowCount() == 0) ? $this->error = 'Insert failed, please try again later' : (int)$this->conn->lastInsertId();




    }

Don't pay attention to the mistakes in the classes, I copy pasted, an ancient code of mine, just to give this simple example.

Now, having said that, say if I wanted to validate an e-mail and submit it to database, I probably would do...

 $Sanitize = new Sanitize(); 
 $checkEmail = $Sanitize->checkEmail($_POST['email']); 
 if(!$Sanitize->checkErrors){

    $QueryClass = new QueryClass(new PDO('mysql:host; .....')); 
    $checkDuplicate = $QueryClass->checkExsitingData('email', 'tableName', 'email', $_POST['email']); 

    if($checkDuplicate){
        echo 'Email exists';
    }else{
    $InsertToDb = $QueryClass->insertToDatabase('emails', $_POST);

    if($InsertToDb){
        echo 'Email is inserted into database';
    }else{
        echo 'query failed';
        }
    }



 }

Now, what I want to know, is that ... you have seen my classes, and I need opinions, as to how I can apply even a smallest portion of Adapter or Factory pattern to better anything in that code. Because, I am sure, this is the only way I can undestand the use cases for them.

BTW: I am trying to create a large-scale news website, which is a personal and very important project for me, with many functionalities, and I don't want to start without at-least getting a basic idea of Adapter or Factory pattern. As it is likly, that even a simple usage might help a lot in making my code, DRY, extendable and anyother OOP principles, that can be helpful for refractoring/optimizing/extending the script in the future, which I am sure I will need.

2
Contributors
1
Reply
15
Views
3 Years
Discussion Span
Last Post by pritaeas
0

how I can apply even a smallest portion of Adapter or Factory pattern

A Factory is a class that handles creation of (similar) objects.

An Adapter is a mediator between two classes, enabling communication between them.

I have the feeling you just heard about these two patterns and want to implement them, whether they are relevant to your code or not. Neither one of these patterns have any application in the code shown above IMO.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.