Created
March 6, 2024 21:23
-
-
Save barryhughes/ce542d7b09af993b095d4767d43fc2c9 to your computer and use it in GitHub Desktop.
WooCommerce/dynamic properties: associating arbitrary values with individual entity instances.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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