Example #1
0
 /**
  * @return UnitOfWork
  */
 public static function getInstance()
 {
     if (!is_object(self::$instance)) {
         self::$instance = new UnitOfWork();
     }
     return self::$instance;
 }
 /**
  * @param string $email_verification_token
  * @return Member|null
  */
 public function getByEmailVerificationToken($email_verification_token)
 {
     $member = Member::get()->filter('EmailVerifiedTokenHash', MemberDecorator::HashConfirmationToken($email_verification_token))->first();
     if (!is_null($member)) {
         UnitOfWork::getInstance()->scheduleForUpdate($member);
     }
     return $member;
 }
 /**
  * @param QueryObject $query
  * @param int $offset
  * @param int $limit
  * @return array
  */
 public function getAll(QueryObject $query, $offset = 0, $limit = 10)
 {
     $filter = (string) $query;
     $current_member = Member::currentUser();
     $do = null;
     if ($current_member && !$current_member->isMarketPlaceSuperAdmin()) {
         //if current user is super admin get all
         //if not , get just related companies
         $companies = $current_member->getManagedMarketPlaceCompaniesByType($this->getMarketPlaceTypeGroup());
         if (count($companies)) {
             $company_filter = ' CompanyID IN ( ';
             foreach ($companies as $company) {
                 $company_filter .= $company->getIdentifier() . ',';
             }
             $company_filter = trim($company_filter, ',');
             $company_filter .= ' ) ';
             if (!empty($filter)) {
                 $company_filter = ' AND ' . $company_filter;
             }
             $filter = $filter . $company_filter;
         }
     }
     $inner_joins = $query->getAlias(QueryAlias::INNER);
     $left_joins = $query->getAlias(QueryAlias::LEFT);
     //build query for data object
     $class = $this->entity_class;
     $do = $class::get()->where($filter)->sort($query->getOrder())->limit($limit, $offset);
     foreach ($inner_joins as $table => $on) {
         $do = $do->innerJoin($table, $on);
     }
     foreach ($left_joins as $table => $on) {
         $do = $do->leftJoin($table, $on);
     }
     if (is_null($do)) {
         return array(array(), 0);
     }
     $res = $do->toArray();
     foreach ($res as $entity) {
         UnitOfWork::getInstance()->scheduleForUpdate($entity);
     }
     return array($res, (int) $do->count());
 }
 /**
  * @param string $owner
  * @param RelationList $component_set
  * @param QueryObject $query
  * @param string $type
  * @param              $association_name
  */
 public function __construct($owner, RelationList $component_set, QueryObject $query, $type = '1-to-many', $association_name)
 {
     $this->owner = $owner;
     $this->type = $type;
     $this->association_name = $association_name;
     $this->component_set = $component_set;
     foreach ($this->component_set->toArray() as $item) {
         $class_name = get_class($item);
         $id = $item->getIdentifier();
         $item_from_cache = UnitOfWork::getInstance()->getFromCache($class_name, $id);
         if (!is_null($item_from_cache) && count($item_from_cache->toMap()) == count($item->toMap())) {
             $item = $item_from_cache;
         } else {
             UnitOfWork::getInstance()->setToCache($item);
         }
         $this->snapshot[spl_object_hash($item)] = $item;
     }
     foreach ($this->snapshot as $key => $item) {
         $this->items[$key] = $item;
     }
     $this->query = $query;
     UnitOfWork::getInstance()->loadCollection($this);
 }
 /**
  * @param DataObject $entity
  * @param             $association_name
  * @param null $inversed_by
  * @param QueryObject $target_query
  * @return bool|Many2OneAssociation
  * @throws Exception
  */
 public function getMany2OneAssociation(DataObject $entity, $association_name, $inversed_by = null, QueryObject $target_query = null)
 {
     $class_name = $entity->has_one($association_name);
     if (!$class_name) {
         throw new Exception(sprintf("entity %s has not an many-to-one association called %s", get_class($entity), $association_name));
     }
     $old = UnitOfWork::getInstance()->getMany2OneAssociation($entity, $association_name);
     if ($old) {
         return $old;
     }
     return new Many2OneAssociation($entity, $association_name, $inversed_by, $target_query);
 }
 /**
  * @param $entity
  * @throws Exception
  */
 protected function markEntity($entity)
 {
     if (!is_null($entity) && $entity instanceof IEntity) {
         UnitOfWork::getInstance()->setToCache($entity);
         UnitOfWork::getInstance()->scheduleForUpdate($entity);
     }
 }
Example #7
0
 public function __construct($object)
 {
     $this->object = $object;
     $this->unitOfWork = UnitOfWork::getInstance();
 }
 /**
  * @return DataObject
  */
 public function getTarget()
 {
     $target = $this->target;
     if ($target instanceof IEntity) {
         UnitOfWork::getInstance()->scheduleForUpdate($target);
     }
     return $target;
 }
Example #9
0
    public function run($configs)
    {/*{{{*/
        $result = array();
        $result['errno'] = -1;
        $result['data'] = array();
        try
        {
            BeanFinder::register('configs', new Configuration($configs));
            $this->initDebug();
            Logger::setUp($configs['system']);
            BeanFinder::get('debug')->begin('service', $this->service.'::'.$this->do, true);

            //是否需要进程间同步
            $synchronized = isset($this->options['synchronized'])?$this->options['synchronized']:false;
            if ($synchronized)
            {
                $cacher= DAL::get()->getCache(Cacher::CACHETYPE_LOCKER);
                $lockUtil  = LockUtil::factory(LockUtil::LOCK_TYPE_MEMCACHE, array('memcache' => $cacher));
                $lockName = $this->service.$this->do;

                //client来决定同步标志,同一个方法,可以根据不用的标志来实施不同的锁
                //同一个service,synchronizedKey 不能重复
                $synchronizedKey = isset($this->options['synchronizedKey'])?$this->options['synchronizedKey']:false;
                if ($synchronizedKey)
                {
                    $lockName = $this->service.':'.$synchronizedKey;
                }
                $lockName = strtolower($lockName);
                $lockUtil->getLock($lockName, 10);
            }

            $uw = new UnitOfWork();
            $service = new $this->service;
            $service->initialize($this->options);
            $this->checkMethod($service);
            

            //error_log("files: ".print_r($_FILES, true), 3, '/tmp/a');
            //error_log("args: ".print_r($this->args, true), 3, '/tmp/a');
            //error_log("service: ".print_r($service, true), 3, '/tmp/a');
            //error_log("do: ".print_r($this->do, true), 3, '/tmp/a');
            //error_log("options: ".print_r($this->options, true), 3, '/tmp/a');
            $result['data'] = call_user_func_array(array($service, $this->do), $this->args);

            $uw->commit();

            BeanFinder::get('debug')->end();
            $result = $this->terminateDebug($result);

            $service->terminate();

            if ($synchronized && $lockUtil)
			    $lockUtil->releaseLock($lockName);

            $uw = $service = null;
            $this->checkOutput($result['data']);
            $result['errno'] = 0;
        }
        catch (LockException $e)
        {
            $result['errmsg']  = 'LockTimeOut';
            $result['exception'] = get_class($e);
            $result['ex'] = $e;
            //do some log here
            error_log(date('Y-m-d H:i:s')." ".print_r(unserialize(serialize($e)), true), 3, '/tmp/exception_sys.log');

            BeanFinder::get('debug')->addParams($e)->autoCloseNode();
            $result = $this->terminateDebug($result);
        }
        catch (BizException $e)
        {
            $result['errmsg']  = $e->getMessage();
            $result['exception'] = get_class($e);
            $result['ex'] = $e;
            //do some log here
            //error_log(print_r($e, true), 3, '/tmp/exception_biz.log');

            if ($synchronized && $lockUtil)
			    $lockUtil->releaseLock($lockName);

            BeanFinder::get('debug')->addParams($e)->autoCloseNode();
            $result = $this->terminateDebug($result);
        }
        catch (SystemException $e)
        {
            $result['errmsg']  = '系统错误';
            $result['exception'] = get_class($e);
            $result['ex'] = $e;
            //do some log here
            error_log(date('Y-m-d H:i:s')." ".print_r(unserialize(serialize($e)), true), 3, '/tmp/exception_sys.log');

            if ($synchronized && $lockUtil)
			    $lockUtil->releaseLock($lockName);

            BeanFinder::get('debug')->addParams($e)->autoCloseNode();
            $result = $this->terminateDebug($result);
        }
        catch (CustomException $e)
        {
            $result['errmsg']  = '系统错误';
            $result['exception'] = get_class($e);
            $result['ex'] = $e;
            //do some log here
            error_log(date('Y-m-d H:i:s')." ".print_r($e->errorMessage(), true), 3, '/tmp/exception_sys.log');

            if ($synchronized && $lockUtil)
			    $lockUtil->releaseLock($lockName);

            BeanFinder::get('debug')->addParams($e)->autoCloseNode();
            $result = $this->terminateDebug($result);
        }
        catch (Exception $e)
        {
            $result['errmsg']  = '系统错误';
            $result['exception'] = get_class($e);
            $result['ex'] = $e;
            //do some log here
            error_log(date('Y-m-d H:i:s')." ".print_r(unserialize(serialize($e)), true), 3, '/tmp/exception_sys.log');

            if ($synchronized && $lockUtil)
			    $lockUtil->releaseLock($lockName);

            BeanFinder::get('debug')->addParams($e)->autoCloseNode();
            $result = $this->terminateDebug($result);
        }
        return $this->prepareOutput($result);
    }/*}}}*/
 /**
  * @return ICandidate|null
  */
 public function getCurrentCandidate()
 {
     $res = null;
     $election = ElectionSystem::get()->first();
     if ($election && $election->CurrentElectionID != 0) {
         $current_election = $election->CurrentElection();
         if (!is_null($current_election)) {
             $candidate = Candidate::get()->filter(array('MemberID' => $this->getIdentifier(), 'ElectionID' => $current_election->ID))->first();
             $res = $candidate;
             if (!is_null($candidate)) {
                 UnitOfWork::getInstance()->setToCache($candidate);
                 UnitOfWork::getInstance()->scheduleForUpdate($candidate);
             }
         }
     }
     return $res;
 }
 /**
  * @param Closure $callback
  * @return null
  * @throws EntityValidationException
  * @throws Exception
  */
 public function transaction(Closure $callback)
 {
     $result = null;
     try {
         $this->beginTransaction();
         $r = new ReflectionFunction($callback);
         // reload on UOW entities that could not being on the update context
         foreach ($r->getStaticVariables() as $var) {
             if ($var instanceof IEntity && $var->getIdentifier() > 0) {
                 UnitOfWork::getInstance()->scheduleForUpdate($var);
             }
         }
         $result = $callback($this);
         $this->commit();
     } catch (ValidationException $ex1) {
         $this->rollBack();
         throw new EntityValidationException($ex1->getMessage());
     } catch (Exception $ex) {
         $this->rollBack();
         throw $ex;
     }
     return $result;
 }
 public function getBy(QueryObject $query)
 {
     $class = $this->entity_class;
     $query->setBaseEntity(new $class());
     $filter = (string) $query;
     $do = $class::get()->where($filter);
     $joins = $query->getAlias();
     foreach ($joins as $table => $clause) {
         $do = $do->innerJoin($table, $clause);
     }
     if (count($query->getOrder())) {
         $do = $do->sort($query->getOrder());
     }
     if (is_null($do)) {
         return false;
     }
     $entity = $do->first();
     if (!is_null($entity) && $entity instanceof IEntity) {
         UnitOfWork::getInstance()->setToCache($entity);
         UnitOfWork::getInstance()->scheduleForUpdate($entity);
     }
     return $entity;
 }
 /**
  * Finds a single document by a set of criteria.
  *
  * @param array $criteria
  * @return object
  */
 public function findOneBy(array $criteria)
 {
     return $this->uow->getDocumentPersister($this->documentName)->load($criteria);
 }
 /**
  * @return IInteropProgramVersion
  */
 public function getProgramVersion()
 {
     $program_version = $this->ProgramVersion();
     UnitOfWork::getInstance()->scheduleForUpdate($program_version);
     return $program_version;
 }
Example #15
0
 /**
  * Mark this entity as dirty. Dirty means that it has been altered during our request.
  */
 public function markAsDirty()
 {
     if ($this->hasUnitOfWork()) {
         $this->unitOfWork->registerDirty($this);
     }
 }
Example #16
0
// Mocks, just placeholders
class DAO
{
}
// Require all files
require 'MapperRegistry.php';
require 'DomainObject.php';
require 'CustomerMapper.php';
require 'Customer.php';
require 'UnitOfWork.php';
// Initiate the mapper registry, with DAO so that injection into the mappers becomes easy.
$mapperRegistry = new MapperRegistry();
$mapperRegistry->setDao(new DAO());
// Initiating the unit of work object
$unitOfWork = new UnitOfWork($mapperRegistry);
// Fire up our mapper, this will take care of the fetching and storing logic
$mapper = $mapperRegistry->getMapperForClassName('Customer');
// Retrieve a customer, with ID 42.
$customer = $mapper->findById(42);
// -- At this point, the customer is marked "clean" in the Unit of Work object.
// Change the e-mail to something different
//
// Once PHP get's field getters and setters, this can be done by using public fields instead of getters and setters.
// @see https://wiki.php.net/rfc/propertygetsetsyntax
$customer->email = '*****@*****.**';
// We changed the customer, let's mark it as dirty.
// Because we are using "called registration", we have to manually do all the thinking for registering objects. This
// is explicit and is fine when the code allows for a natural flow. However if the code is more complex. This
// approach might be too error prone and the "object registration" approach is a much safer choice.
$unitOfWork->registerDirty($customer);