Tech Is Hard

Credibility = Talent x Years of experience + Proven hardcore accomplishment

PHP Property Manager: User and Model client classes


It will make things go faster to pack a lot of new things into this. User now looks like this:

require_once 'class.Model.php';

class User extends Model {

    public $id;

    /**
     * Distribution Center
     *
     * An object reference to $this User's distribution center object
     *
     * @pm
     * @var DistCenter
     */
    public $DistCenter;

    function __construct($id) {
        parent::__construct();
        $this->id = $id;
    }
}

Assuming that your class hierarchy might have a base class, I’ve added a base class of Model to User. (Remember, in my original implementation, the base class held all the property management, but I don’t want that restriction.) We’ve marked $DistCenter as a managed property with @pm and given it a type. Model should be doing most of the interfacing with __pm; it looks like:

require_once 'class.__pm.php';

class Model {

    function __construct() {
        __pm::init($this);
    }

    /**
     * Generic getter
     *
     * Called everytime a @pm property is referenced
     *
     * @param  string  $prop  Name of object property
     * @return mixed          Value of property.
     */
    public function __get($prop) {
    	try {
            return __pm::get($this, $prop);
    	}
        catch (Exception $e) {
            error_log($e);
            throw $e;
        }
    }

    /**
     * Generic setter
     *
     * Called everytime a @pm property of an object is set
     *
     * @param  string   $prop   Name of object property
     * @param  mixed    $value  Value to set object property to
     * @return mixed
     */
    function __set($prop, $value) {
        try {
            return __pm::set($this, $prop, $value);
    	}
    	catch (Exception $e) {
            error_log($e);
            throw $e;
    	}
    }
}

By supplying __get and __set interceptor functions, your class hierarchy can make use of __pm class. I’m adding logging of any Exception that’s thrown by __pm.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: