Kontakt - Datenschutz

Subversion

<?php
// Restrict access to specific properties with an accessor.

class Accessor {
    private $obj   = null;
    private $read  = [];
    private $write = [];


    public function __construct($obj, $read = [], $write = [], $readwrite = []) {
        $this->obj = $obj;

        foreach($read as $property) {
            $this->read[$property] = true;
        }

        foreach($write as $property) {
            $this->write[$property] = true;
        }

        foreach($readwrite as $property) {
            $this->read[$property] = true;
            $this->write[$property] = true;
        }
    }// __construct


    public function __get($name) {
        if(isset($this->read[$name])) {
            return $this->obj->$name;
        } else {
            $classname = get_class($this->obj);
            throw new Exception("No read access for '$classname::$name'.");
        }
    }// __get


    public function __set($name, $value) {
        if(isset($this->write[$name])) {
            return $this->obj->$name = $value;
        } else {
            $classname = get_class($this->obj);
            throw new Exception("No write access for '$classname::$name'.");
        }
    }// __set


    public function __call($name, $arguments) {
        call_user_func_array([$this->obj, $name], $arguments);
    }// __call
    // TODO __unset, __isset, ...
}// Accessor


class User {
    public $id   = 42;
    public $name = 'John';

    private $accessors = [];


    public function __construct() {
        $this->accessors['all']  = new Accessor($this, [], [], ['id', 'name']);
        $this->accessors['form'] = new Accessor($this, [], [], ['name']);
    }// __construct


    public function getAccessor($name) {
        // TODO Check error
        return $this->accessors[$name];
    }// getAccessor


    public function sayHello() {
        echo "say Hello\n";
    }// sayHello
}// User


echo "--------- form\n";
$user  = new User();
$model = $user->getAccessor('form');

echo $model->name, "\n";

try {
    echo $model->id, "\n";
} catch(Exception $e) {
    echo "Exception: {$e->getMessage()}\n";
}

$model->sayHello();


echo "--------- all\n";
$all = $user->getAccessor('all');
echo $all->name, "\n";
echo $all->id, "\n";
$all->sayHello();
?>