Created
March 31, 2023 23:50
-
-
Save furan917/adea53bd87bd6a4acc064e196b9b9a87 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
namespace Your\Module\Namespace\Listener; | |
use MySQLReplication\BinLog\BinLogSocketConnect; | |
use MySQLReplication\Config\ConfigBuilder; | |
use MySQLReplication\Event\DTO\UpdateRowsDTO; | |
use MySQLReplication\Event\EventSubscribers; | |
use MySQLReplication\MySQLReplicationFactory; | |
class ProductPriceUpdateListener extends EventSubscribers | |
{ | |
private $indexerFactory; | |
public function __construct( | |
IndexerFactory $indexerFactory | |
) { | |
$this->indexerFactory = $indexerFactory; | |
} | |
public function onUpdate(UpdateRowsDTO $event) | |
{ | |
if ($event->getTableMap()->getTable() === 'catalog_product_entity_decimal') { | |
foreach ($event->getValues() as $value) { | |
$oldData = $value->getBefore(); | |
$newData = $value->getAfter(); | |
$productId = $newData['entity_id']; | |
if ($oldData['value'] !== $newData['value']) { | |
$this->triggerPartialReindex($productId); | |
} | |
} | |
} | |
} | |
private function triggerPartialReindex($productId) | |
{ | |
//Leave as reindexer or build your own customised indexer | |
$indexer = $this->indexerFactory->create(); | |
$indexer->load('catalog_product_price'); | |
$indexer->reindexRow($productId); | |
} | |
} | |
//Im being Lazy replace with proper code | |
class BinLogListener | |
{ | |
public function run() | |
{ | |
//Im being lazy as its almost 1am, use $connection-getConfig or something more secure | |
$config = (new ConfigBuilder()) | |
->withHost('localhost') | |
->withUser('root') | |
->withPassword('your_password') | |
->withPort(3306) | |
->build(); | |
$binLogStream = new MySQLReplicationFactory($config); | |
$productPriceUpdateListener = new ProductPriceUpdateListener(); | |
$binLogStream->registerSubscriber($productPriceUpdateListener); | |
try { | |
$binLogStream->run(); | |
} catch (BinLogSocketConnectException $e) { | |
echo "Error: {$e->getMessage()}"; | |
} | |
} | |
} | |
//add where ever you please. | |
$listener = new BinLogListener(); | |
$listener->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment