wp-pay-core icon indicating copy to clipboard operation
wp-pay-core copied to clipboard

Make dealing with singletons easier

Open remcotolsma opened this issue 1 year ago • 0 comments

Within a WordPress environment it is sometimes important that instances of classes are only created once, for example to prevent double filter and action hooks. For example, there are several iDEAL Basic providers, but it is not necessary to register several pronamic-pay/ideal-basic/v1/notification REST API endpoints.

  • https://github.com/pronamic/wp-pronamic-pay-ideal-basic/blob/b9b95a9cd02d10dd398a39e44340599a695b2996/src/NotificationController.php

Within the Pronamic Pay plugins only 1 \Pronamic\WordPress\Pay\Gateways\IDealBasic\NotificationController instance needs to exist. The Pronamic\WordPress\Pay\Plugin is already a singleton class, we could use this object to keep track of other singletons (container).

https://github.com/pronamic/wp-pay-core/blob/d2f591e9482272b62eda0dd1df9cfc669e7faec1/src/Plugin.php#L78-L91

  • https://laravel.com/docs/10.x/container#binding-a-singleton
  • https://darkghosthunter.medium.com/php-a-noob-explanation-for-dependency-injection-and-di-container-a7179390b26c
  • https://github.com/woocommerce/woocommerce/blob/a77e4abffeb4677d911f76a2a60ff4f7a35b59c2/plugins/woocommerce/woocommerce.php#L57

remcotolsma avatar Mar 29 '23 11:03 remcotolsma