Search code examples
phpclassooparchitectureconstruct

Best way to connect classes


So, I'm not using any framework, developing a system on MVC architecture using PHP and have several components. One of them is Sanitize, for filtering vars.

The problem that I came into is, how to better sanitize the vars?

Easier to show in an example:

class Sanitize {
    public function sanitizeString($string) {
        return filter_var($string, FILTER_SANITIZE_STRING);
    }
}

Then I want this class to be executed on models and controllers and well, almost all files. To don't write everytime $sanitize = new Sanitize; I'm used to add a public __construct function that will create a sanitize var.

private $sanitize;
public function __construct() {
    $sanitize = new Sanitize();
}

Then I just call it in my function using

$string = $this->sanitize->sanitizeString($string);

The problem is that I'm a lil bit paranoid, so I connect a sanitize class automatically in every single class, specially models, to sanitize data when it goes into DB. So here happens something like a recursion and there are a var that is created over and over. For example a controller will create a sanitize class using construct. Then in a method I will create new class in model User, and User class also creates a sanitize in it, as well as some data from Cookies and Access classes, both from which creates sanitize in it.

So I called 1 method, but it created 4 duplicates of sanitize, some even without a need...

What's the best practise? Am I doing it right?

Thanks in advance!


Solution

  • Just fast scratch of one solution:

    <?php
    interface ISanitizedValue {
        public function value();
    }
    
    class CSanitizedLogin implements ISanitizedValue {
        private $_rawValue;
    
        public function __construct($value){
            $this->_rawValue = $value;
        }
    
        public function value(){
            // sanitizing
        }
    }
    
    class CSomeClass {
        // force to use ISanitizedValue
        public function __construct(ISanitizedValue $login){}
    }
    
    $login = new CSanitizedLogin($_GET['login']);
    $example1 = new CSomeClass($login);
    $example2 = new CSomeClass($login);
    ?>