SlideShare a Scribd company logo
Wiktor Jarka
Creatuity
Synchronizacja - sekcje krytyczne
na przykładzie integracji z
systemem lojalnościowym
Definicje
Sekcja krytyczna

“W programowaniu
współbieżnym fragment kodu, w którym
korzysta się z zasobu
współdzielonego, a co
za tym idzie - w danej
chwili może być
wykorzystywany przez
co najwyżej jeden
wątek.”

Semafor

“Chroniona zmienna lub
abstrakcyjny typ danych,
który stanowi klasyczną
metodę kontroli dostępu
przez wiele procesów do
wspólnego zasobu w
środowisku
programowania
równoległego.”
Opis problemu
● Projekt: system zakupów grupowych
wyspecjalizowany w polach golfowych,
● Opticard: system punktów lojalnościowych
posiadający API,
● typy transakcji: inicjacja karty, dodawanie punktów,
zapisanie danych użytkownika,
● sequence number: część specyfikacji Opticard API,
● pula numerów kart: część specyfikacji modułu
integrującego Opticard z Magento.
Zachowanie spójności danych
Jak?
Sequence Number
● służy do zachowania spójności Opticard
i systemu,
● zwiększany po poprawnej transakcji,
● pozostaje taki sam po błędzie,
● nie mogą istnieć dwie poprawne transakcje
z tym samym numerem sekwencji.
Pula kart
● administrator Magento definiuje jakie karty mogą być
przypisane do klientów,
● dowolna, wolna karta jest przypisywana do
użytkownika w momencie, kiedy pierwszy raz coś
kupi,
● jedna karta może być przypisana tylko do jednego
użytkownika (przez cały “cykl życia” karty).
Podstawowe informacje o
systemie
Wersja wyjściowa
class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object {
(...)
public function assignAnyFreeCardToCustomer($customerOrId) {
$customerId = $this->_helper()->asCustomerId($customerOrId);
$freeCards = $this->getFreeCardNumbersCollection()
->addFieldToSelect('card_id')
->addFieldToSelect('card_number');
if ($freeCards->count() == 0) {
Mage::throwException('There is no Opticard card numbers available to assign');
}
/** @var Creatuitycorp_Opticard_Model_Card $card */
$card = $freeCards->getFirstItem();
$card->assignToCustomer($customerId);
$card->save();
return $card;
}
}
Synchronizacja w PHP
Jest kilka możliwości:
● poprzez plik: flock(),
● poprzez wbudowany semafor: sem_acquire(),
● poprzez mysql: GET_LOCK().
Rozwiązanie: krok 1
class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object {
public function assignAnyFreeCardToCustomer($customerOrId) {
$customerId = $this->_helper()try {
>asCustomerId($customerOrId);
$row = $this->_db()->query("SELECT GET_LOCK('" . self::$_lockName . "', 15) AS
locked")->fetch();
$freeCards = $this$isTimeout = $row['locked'] == 0;
>getFreeCardNumbersCollection()
if ($isTimeout) {
->addFieldToSelect('card_id')
$this->_debugLog("Couldn't lock. Timeout exceeded.");
->addFieldToSelect('card_number');
Mage::throwException("I was unable to create lock within 15 seconds.");
}
if ($freeCards->count() == 0) {
$this->_db()->beginTransaction();
Mage::throwException('There is no
Opticard card numbers available to
// LOGIC GOES HERE
assign');
}
$this->_db()->commit();
/** @var
$this->_db()->query("DO RELEASE_LOCK('" . self::$_lockName . "')");
Creatuitycorp_Opticard_Model_Card $card
return $card;
*/
$card = $freeCards->getFirstItem();
} catch (Exception $e) {
$this->_db()->rollback();
$card->assignToCustomer($customerId);
$this->_db()->query("DO RELEASE_LOCK('" . self::$_lockName . "')");
throw $e;
$card->save();
}
}
(...)
Lepiej, ale…?
• Ciężko to pokazać na slajdzie (serio!),
• duplikacja kodu dla każdej funkcji, która wymaga
działania w sekcji krytycznej,
• kiedy sekcje nachodzą do siebie - RELEASE_LOCK
może być wykonane zbyt wcześnie.
Nachodzące na siebie sekcje

Wymagana transakcyjność!
Rozwiązanie: krok 2.1
class Creatuitycorp_Opticard_Model_Mysql_Transactional_Critical_Section
extends Creatuitycorp_Opticard_Model_Mysql_Abstract {
public function begin() {
$this->_semaphore()->lock();
$this->_transaction()->begin();
}
public function end() {
$this->_transaction()->commit();
$this->_semaphore()->release();
}
public function revert() {
$this->_transaction()->rollback();
$this->_semaphore()->release();
}
/** @return Creatuitycorp_Opticard_Model_Mysql_Transactions */
protected function _transaction() {
return Mage::getSingleton('opticard/mysql_transactions');
}
/** @return Creatuitycorp_Opticard_Model_Mysql_Semaphore */
protected function _semaphore() {
return Mage::getSingleton('opticard/mysql_semaphore');
}
(...)
Rozwiązanie: krok 2.2
class Creatuitycorp_Opticard_Model_Mysql_Semaphore
extends Creatuitycorp_Opticard_Model_Mysql_Abstract {
private static $_count = 0;
private static $_lockName = 'opticard_semaphore';
public function lock($timeout = 300) {
if (self::$_count++ === 0) {
$row = $this->_db()->query("SELECT GET_LOCK('" . self::$_lockName . "', " . $timeout
. ") AS locked")->fetch();
$isTimeout = $row['locked'] == 0;
if ($isTimeout) {
Mage::throwException("Unable to lock. Timeout exceeded.");
}
}
}
public function release() {
if (self::$_count === 0) {
Mage::throwException("Cannot unlock what's not locked. Neither can Chuck Norris.");
}
if (--self::$_count === 0) {
$this->_db()->query("DO RELEASE_LOCK('" . self::$_lockName . "')");
}
}
(...)
Rozwiązanie: krok 2.3
class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object {
public function assignAnyFreeCardToCustomer($customerOrId) {
try {
$this->_criticalSection()->begin();
$customerId = $this->_helper()->asCustomerId($customerOrId);
$freeCards = $this->getFreeCardNumbersCollection()
->addFieldToSelect('card_id')
->addFieldToSelect('card_number');
if ($freeCards->count() == 0) {
Mage::throwException('There is no Opticard card numbers available to assign');
}
/** @var Creatuitycorp_Opticard_Model_Card $card */
$card = $freeCards->getFirstItem();
$card->assignToCustomer($customerId);
$card->save();
$this->_criticalSection()->end();
return $card;
} catch (Exception $e) {
$this->_criticalSection()->rollback();
throw $e;
}
}
(...)
Krok 2 - podsumowanie
Minusy
•

konieczność dodawania
dodatkowego kodu do
każdej funkcji
używającej sekcji
krytycznej

Plusy
•

•

obsługa nachodzących
na siebie sekcji
krytycznych
lepsza organizacja
i czytelność kodu
Rozwiązanie: krok 3.1
class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object {
public function assignAnyFreeCardToCustomer__CRITICAL_SECTION($customerOrId) {
$customerId = $this->_helper()->asCustomerId($customerOrId);
$freeCards = $this->getFreeCardNumbersCollection()
->addFieldToSelect('card_id')
->addFieldToSelect('card_number');
if ($freeCards->count() == 0) {
Mage::throwException('There is no Opticard card numbers available to assign');
}
/** @var Creatuitycorp_Opticard_Model_Card $card */
$card = $freeCards->getFirstItem();
$card->assignToCustomer($customerId);
$card->save();
return $card;
}
public function __call($method, $args) {
if ($this->_criticalSection()->shouldRunInCriticalSection($this, $method)) {
return $this->_criticalSection()->runMethodInCriticalSection($this, $method, $args);
}
return parent::__call($method, $args);
}
(...)
Rozwiązanie: krok 3.2
class Creatuitycorp_Opticard_Model_Mysql_Transactional_Critical_Section
extends Creatuitycorp_Opticard_Model_Mysql_Abstract {
const METHOD_SUFFIX = '__CRITICAL_SECTION';
public function shouldRunInCriticalSection($object, $methodName) {
return method_exists($object, $this->_csMethodName($methodName));
}
public function runMethodInCriticalSection($object, $methodName, $args) {
return $this->run($object, $this->_csMethodName($methodName), $args);
}
protected function _csMethodName($methodName) {
return $methodName . self::METHOD_SUFFIX;
}
public function run($object, $methodName, array $args = array()) {
try {
$this->begin();
$result = call_user_func_array(array($object, $methodName), $args);
$this->end();
return $result;
} catch (Exception $e) {
$this->revert();
throw $e;
}
}
(...)
Krok 3 - podsumowanie
Minusy
•

konieczność nadpisania
funkcji __call dla każdej
klasy używającej sekcji
krytycznej

Plusy
•

funkcja robi tylko
i wyłącznie to za co jest
odpowiedzialna
Pytania?
A jak Ty byś to zrobił?
Dziękuję za uwagę
@wiktorjarka
wiktor@jarka.pl

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
MindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Synchronizacja w PHP - Meet Magento

  • 1. Wiktor Jarka Creatuity Synchronizacja - sekcje krytyczne na przykładzie integracji z systemem lojalnościowym
  • 2. Definicje Sekcja krytyczna “W programowaniu współbieżnym fragment kodu, w którym korzysta się z zasobu współdzielonego, a co za tym idzie - w danej chwili może być wykorzystywany przez co najwyżej jeden wątek.” Semafor “Chroniona zmienna lub abstrakcyjny typ danych, który stanowi klasyczną metodę kontroli dostępu przez wiele procesów do wspólnego zasobu w środowisku programowania równoległego.”
  • 3. Opis problemu ● Projekt: system zakupów grupowych wyspecjalizowany w polach golfowych, ● Opticard: system punktów lojalnościowych posiadający API, ● typy transakcji: inicjacja karty, dodawanie punktów, zapisanie danych użytkownika, ● sequence number: część specyfikacji Opticard API, ● pula numerów kart: część specyfikacji modułu integrującego Opticard z Magento.
  • 5. Sequence Number ● służy do zachowania spójności Opticard i systemu, ● zwiększany po poprawnej transakcji, ● pozostaje taki sam po błędzie, ● nie mogą istnieć dwie poprawne transakcje z tym samym numerem sekwencji.
  • 6. Pula kart ● administrator Magento definiuje jakie karty mogą być przypisane do klientów, ● dowolna, wolna karta jest przypisywana do użytkownika w momencie, kiedy pierwszy raz coś kupi, ● jedna karta może być przypisana tylko do jednego użytkownika (przez cały “cykl życia” karty).
  • 8. Wersja wyjściowa class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object { (...) public function assignAnyFreeCardToCustomer($customerOrId) { $customerId = $this->_helper()->asCustomerId($customerOrId); $freeCards = $this->getFreeCardNumbersCollection() ->addFieldToSelect('card_id') ->addFieldToSelect('card_number'); if ($freeCards->count() == 0) { Mage::throwException('There is no Opticard card numbers available to assign'); } /** @var Creatuitycorp_Opticard_Model_Card $card */ $card = $freeCards->getFirstItem(); $card->assignToCustomer($customerId); $card->save(); return $card; } }
  • 9. Synchronizacja w PHP Jest kilka możliwości: ● poprzez plik: flock(), ● poprzez wbudowany semafor: sem_acquire(), ● poprzez mysql: GET_LOCK().
  • 10. Rozwiązanie: krok 1 class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object { public function assignAnyFreeCardToCustomer($customerOrId) { $customerId = $this->_helper()try { >asCustomerId($customerOrId); $row = $this->_db()->query("SELECT GET_LOCK('" . self::$_lockName . "', 15) AS locked")->fetch(); $freeCards = $this$isTimeout = $row['locked'] == 0; >getFreeCardNumbersCollection() if ($isTimeout) { ->addFieldToSelect('card_id') $this->_debugLog("Couldn't lock. Timeout exceeded."); ->addFieldToSelect('card_number'); Mage::throwException("I was unable to create lock within 15 seconds."); } if ($freeCards->count() == 0) { $this->_db()->beginTransaction(); Mage::throwException('There is no Opticard card numbers available to // LOGIC GOES HERE assign'); } $this->_db()->commit(); /** @var $this->_db()->query("DO RELEASE_LOCK('" . self::$_lockName . "')"); Creatuitycorp_Opticard_Model_Card $card return $card; */ $card = $freeCards->getFirstItem(); } catch (Exception $e) { $this->_db()->rollback(); $card->assignToCustomer($customerId); $this->_db()->query("DO RELEASE_LOCK('" . self::$_lockName . "')"); throw $e; $card->save(); } } (...)
  • 11. Lepiej, ale…? • Ciężko to pokazać na slajdzie (serio!), • duplikacja kodu dla każdej funkcji, która wymaga działania w sekcji krytycznej, • kiedy sekcje nachodzą do siebie - RELEASE_LOCK może być wykonane zbyt wcześnie.
  • 12. Nachodzące na siebie sekcje Wymagana transakcyjność!
  • 13. Rozwiązanie: krok 2.1 class Creatuitycorp_Opticard_Model_Mysql_Transactional_Critical_Section extends Creatuitycorp_Opticard_Model_Mysql_Abstract { public function begin() { $this->_semaphore()->lock(); $this->_transaction()->begin(); } public function end() { $this->_transaction()->commit(); $this->_semaphore()->release(); } public function revert() { $this->_transaction()->rollback(); $this->_semaphore()->release(); } /** @return Creatuitycorp_Opticard_Model_Mysql_Transactions */ protected function _transaction() { return Mage::getSingleton('opticard/mysql_transactions'); } /** @return Creatuitycorp_Opticard_Model_Mysql_Semaphore */ protected function _semaphore() { return Mage::getSingleton('opticard/mysql_semaphore'); } (...)
  • 14. Rozwiązanie: krok 2.2 class Creatuitycorp_Opticard_Model_Mysql_Semaphore extends Creatuitycorp_Opticard_Model_Mysql_Abstract { private static $_count = 0; private static $_lockName = 'opticard_semaphore'; public function lock($timeout = 300) { if (self::$_count++ === 0) { $row = $this->_db()->query("SELECT GET_LOCK('" . self::$_lockName . "', " . $timeout . ") AS locked")->fetch(); $isTimeout = $row['locked'] == 0; if ($isTimeout) { Mage::throwException("Unable to lock. Timeout exceeded."); } } } public function release() { if (self::$_count === 0) { Mage::throwException("Cannot unlock what's not locked. Neither can Chuck Norris."); } if (--self::$_count === 0) { $this->_db()->query("DO RELEASE_LOCK('" . self::$_lockName . "')"); } } (...)
  • 15. Rozwiązanie: krok 2.3 class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object { public function assignAnyFreeCardToCustomer($customerOrId) { try { $this->_criticalSection()->begin(); $customerId = $this->_helper()->asCustomerId($customerOrId); $freeCards = $this->getFreeCardNumbersCollection() ->addFieldToSelect('card_id') ->addFieldToSelect('card_number'); if ($freeCards->count() == 0) { Mage::throwException('There is no Opticard card numbers available to assign'); } /** @var Creatuitycorp_Opticard_Model_Card $card */ $card = $freeCards->getFirstItem(); $card->assignToCustomer($customerId); $card->save(); $this->_criticalSection()->end(); return $card; } catch (Exception $e) { $this->_criticalSection()->rollback(); throw $e; } } (...)
  • 16. Krok 2 - podsumowanie Minusy • konieczność dodawania dodatkowego kodu do każdej funkcji używającej sekcji krytycznej Plusy • • obsługa nachodzących na siebie sekcji krytycznych lepsza organizacja i czytelność kodu
  • 17. Rozwiązanie: krok 3.1 class Creatuitycorp_Opticard_Model_Card_Pool extends Varien_Object { public function assignAnyFreeCardToCustomer__CRITICAL_SECTION($customerOrId) { $customerId = $this->_helper()->asCustomerId($customerOrId); $freeCards = $this->getFreeCardNumbersCollection() ->addFieldToSelect('card_id') ->addFieldToSelect('card_number'); if ($freeCards->count() == 0) { Mage::throwException('There is no Opticard card numbers available to assign'); } /** @var Creatuitycorp_Opticard_Model_Card $card */ $card = $freeCards->getFirstItem(); $card->assignToCustomer($customerId); $card->save(); return $card; } public function __call($method, $args) { if ($this->_criticalSection()->shouldRunInCriticalSection($this, $method)) { return $this->_criticalSection()->runMethodInCriticalSection($this, $method, $args); } return parent::__call($method, $args); } (...)
  • 18. Rozwiązanie: krok 3.2 class Creatuitycorp_Opticard_Model_Mysql_Transactional_Critical_Section extends Creatuitycorp_Opticard_Model_Mysql_Abstract { const METHOD_SUFFIX = '__CRITICAL_SECTION'; public function shouldRunInCriticalSection($object, $methodName) { return method_exists($object, $this->_csMethodName($methodName)); } public function runMethodInCriticalSection($object, $methodName, $args) { return $this->run($object, $this->_csMethodName($methodName), $args); } protected function _csMethodName($methodName) { return $methodName . self::METHOD_SUFFIX; } public function run($object, $methodName, array $args = array()) { try { $this->begin(); $result = call_user_func_array(array($object, $methodName), $args); $this->end(); return $result; } catch (Exception $e) { $this->revert(); throw $e; } } (...)
  • 19. Krok 3 - podsumowanie Minusy • konieczność nadpisania funkcji __call dla każdej klasy używającej sekcji krytycznej Plusy • funkcja robi tylko i wyłącznie to za co jest odpowiedzialna
  • 21. A jak Ty byś to zrobił?