experimenter
experimenter

Reputation: 778

How to create a PHP singleton class to handle request vars?

was thinking about creating a Single class called 'Request' to handle and clean POST and GET variables but being new to the singleton pattern I'm not sure how to implement it. Ideally I'd like to have 2 functions post($name,$clean) and get($name,$clean) - $clean being a boolean to determine whether to trim/ escape the value

Upvotes: 0

Views: 493

Answers (2)

Chuck Burgess
Chuck Burgess

Reputation: 11574

I think using a singleton would be great even if for practice. Just because someone doesn't think it's the right approach does not make it wrong. By using and implementing ideas, not matter how small or large, you will learn and expand your knowledge of said implementations. You will soon know if it works for your particular situation or not. Then you do not have to take the opinions of others.

That being said, I say go for it. I can see why you would want to. The thought being, "I want everything to be cleaned for injections (etc.) and this way I can make sure it will happen on every input."

Allow me to shed a little light. Why not implement a single method using $_REQUEST that will process both $_GET and $_POST? While this may be a simple approach, it will get you started.

$cleanser = Cleanser::singleton();
$new_request_array = $cleanser->clean($_REQUEST);

class Cleanser
{
    private static $instance;
    private function __construct() { }

    public static function singleton() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    public function clean($request) {
        foreach($request as $key => $value) {
            // perform any cleansing here
            $cleansed[$key] = trim($value);
        }

        return $cleansed;
    }

    public function __clone() {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }
}

Have fun and remember, there is nothing "wrong" or "incorrect" when it comes to learning. I think that is the approach StackOverflow is trying to make. We are here to learn how to do something, not be judged on our implementation of it. So have fun!

Upvotes: 1

John Parker
John Parker

Reputation: 54445

I'm not sure why you think this is a good candidate for a singleton - I've have thought a simple static class would make much more sense. (Incidentally, I presume you're using the built in filter functions?)

Whilst a gross simplification, singleton's are good at limiting/controlling access to a finite resource which isn't really the case in this instance.

Upvotes: 0

Related Questions