Skip to content

Instantly share code, notes, and snippets.

@hiromi2424
Created April 16, 2011 01:20
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 hiromi2424/922748 to your computer and use it in GitHub Desktop.
Save hiromi2424/922748 to your computer and use it in GitHub Desktop.
simple transaction service
<?php
/*
* ###############
* # W A R N I N G
* ###############
*
* This implementation is thought of madness.
* So DO NOT use this for basic process of service at your applications.
*/
class BaseService {
public function __get($name) {
$class = Inflector::classify($name);
if ($name === 'Transaction') {
return $this->$class = ClassRegistry::init('TransactionService');
}
return $this->$class = ClassRegistry::init($class);
}
public function simpleTransaction($lambda) {
$this->Transaction->begin();
$result = $lambda($this);
if (!$result) {
$this->Transaction->rollback();
} else {
$this->Transaction->commit();
}
return $result;
}
public function transaction($datasources = null) {
return $this->Transaction->setDataSources($datasources);
}
}
<?php
/*
* ###############
* # W A R N I N G
* ###############
*
* This implementation is thought of madness.
* So DO NOT use this for basic process of service at your applications.
*/
App::import('Model', 'BaseService');
/*
* Service model class.
* This model provides interfaces for features that affects database with create, update and delete functionalities.
* Any controllers or shells(tasks) should use Service methods to make consistency.
*/
class Service extends BaseService {
/*
public function registerUser($data) {
$this->Transaction->begin();
$result = $this->User->signup($data);
if (!$result) {
$this->Transaction->rollback();
} else {
$this->Transaction->commit();
}
return $result;
}
*/
public function registerUser($data) {
return $this->simpleTransaction(function($self) {
return $self->User->signup($data);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment