Skip to content

Instantly share code, notes, and snippets.

@dnaber-de
Created September 29, 2014 08:42
Show Gist options
  • Save dnaber-de/4d6a3ac8e8a80f4cd971 to your computer and use it in GitHub Desktop.
Save dnaber-de/4d6a3ac8e8a80f4cd971 to your computer and use it in GitHub Desktop.
Quick notes about some OOP structure
<?php
interface EntityAttributeInterface {
public function getName();
public function setValue( AttributeValueInterface $value );
public function setUnit( AttributeUnitInterface $unit );
// getters dito
}
class PostAttribute implements EntityAttributeInterface {
/**
* the identifier of the attribute
* @type string
*/
private $name;
private $post;
private $value;
private $unit;
private $storage;
public function __construct( $name, \WP_Post $post, AttributeStorageInterface $storage ) {
$this->post = $post
}
public function update() {
$data = array(
'value' => $this->value->getValue(),
'unit' => $this->unit->getUnit()
);
$this->storage->update( $this->name, $data );
}
// implementing setter/getter from interface
}
/**
* define a storage for attributes
*/
interface AttributeStorageInterface {
public function update( $name, $data );
public function get( $name );
public function delete( $name );
}
class PostMetaAttributeStorage implements AttributeStorageInterface {
private $post;
public function __construct( \WP_Post ) {
$this->post = $post;
}
public function update( $name, $data ) {
update_post_meta( $this->post->ID, $name, $data );
}
//get(), delete() dito
}
/**
* the value interface
*/
interface AttributeValueInterface {
public function setValue( $value );
public function getValue();
}
class NumericAttributeValue implements AttributeValueInterface {
private $value = 0;
public function setValue( $value ) {
if ( is_numeric( $value ) )
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
/**
* the unit interface
*/
interface AttributeUnitInterface {
public function setUnit( $unit );
public function getUnit();
}
class WPTermAttributeUnit {
private $unit_id = 0;
/**
* @param \stdClass $unit (WPTerm)
*/
public function setUnit( $unit ) {
$this->unit_id = $unit->term_id;
}
pubic function getUnit() {
return $this->unit;
}
}
<?php
// update a post attribute 'size' from a request
$post = get_post( $request[ 'post_ID' ] );
$size = new PostAttribute(
'size',
$post,
new PostMetaAttributeStorage( $post )
);
$size_value = new NumericAttributeValue;
$size_value->setValue( $request[ 'size' ] );
$unit_term = get_term( /*...*/ );
$size_unit = new WPTermAttributeUnit( $unit_term );
$size->setValue( $size_value );
$size->setUnit( $size_unit );
$size->update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment