Skip to content

Instantly share code, notes, and snippets.

@barryhughes
Created March 6, 2024 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barryhughes/ce542d7b09af993b095d4767d43fc2c9 to your computer and use it in GitHub Desktop.
Save barryhughes/ce542d7b09af993b095d4767d43fc2c9 to your computer and use it in GitHub Desktop.
WooCommerce/dynamic properties: associating arbitrary values with individual entity instances.
<?php
/**
* Simple approach showing a structured approach to associating arbitrary, ephemeral
* (non-persisted) data with individual product objects and other entities.
*
* Benefits include avoidance of collisions between two plugins using the same key,
* the range of checks that can be applied to stored values, etc.
*
* @link https://github.com/woocommerce/woocommerce/issues/45286
*/
namespace My_Plugin {
use WeakMap;
use SplObjectStorage;
function internal_costs() {
static $map;
if ( empty( $map ) ) {
$map = class_exists( WeakMap::class ) ? new WeakMap : new SplObjectStorage;
}
return $map;
}
}
namespace {
$product = wc_get_product( 12345 );
$internal_costs = My_Plugin\internal_costs();
$internal_costs[ $product ] = 123;
print $internal_costs[ $product ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment