Skip to content
Advertisement

PHP: Is there a way to set up a Class so that you can modify properties of the class without reasigning it a value?

I am setting up a class called a DataMapper for an MVC framework that I am developing.

The DataMapper class will basically hold a bunch of Rules that map a data model structure to the database table/column structure – and it will list criteria for each Rule.

A simpler version of the Rule class would look like (keep in mind these code snippets are examples):

class DataMapRule {
    // required rule properties
    public $required = array("modelName", "columnName", "type");
    // optional values
    public $options = array("minVal", "nullOrempty", "maxCharLength");

    public $finalRule = array();

    // model property is the prop name in the model
    // column name is
    public function __construct($modelProperty = "", $columnName = "", $type = "") {
        $this->finalRule["modelName"] = $modelProperty;
        $this->finalRule["columnName"] = $columnName;
        $this->finalRule["type"] = $type;
    }


    public function addCriteria($option, $val) {
        if(in_array($option, $this->options)) {
            $this->finalRule[$option] = $val;
        }
    }
}

And a simpler version of the extended DataMapper class would look like:

class UserDataMapper extends DataMapper {
    public $map = array();
    public function __construct() {
        $rule = new DataMapRule("_age", "Age", "int");
        $rule->addCriteria("minVal", "1");
        $rule->addCriteria("nullOrEmpty", false);
        $this->map[] = $rule->finalRule;
        $rule = new DataMapRule("_firstName", "FirstName", "string");
        $rule->addCriteria("maxCharLength", 50);
        $rule->addCriteria("nullOrEmpty", false);
        $this->map[] = $rule->finalRule;
    }

}

And I am going to create these maps and rules for all my models/modules.

What I am trying to do is clean up the code / make it easier to code and follow. Is there any way to set up the class(es) so that in the DataMapper constructor I can do something like:

    public function __construct() {
        $this->map[] = new DataMapRule("_firstName", "FirstName", "string")
            ->addCriteria("maxCharLength", 50)
            ->addCriteria("nullOrEmpty", false)
            ->finalRule;
    }

Advertisement

Answer

This is usually called a ‘fluid’ interface, and to implement this, all you really have to do is return $this from your addCriteria() function.

public function addCriteria($option, $val) {
    if(in_array($option, $this->options)) {
        $this->finalRule[$option] = $val;
    }
    return $this;
}

Returning $this is means that you can call addCriteria again on the result of addCriteria

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement