【问题标题】:is a right way manage transactions using static transactionCounter with multiple classes?使用具有多个类的静态 transactionCounter 管理事务的正确方法是什么?
【发布时间】:2016-09-25 02:12:41
【问题描述】:

我有兴趣使用 http://php.net/manual/en/pdo.begintransaction.php 中描述的 Database 类

但是那个类有一个问题,它使用了一个非静态的$transactionCount 属性,这意味着如果我有多个类开始事务,它将导致多次提交,并使我的代码最终出错,看这个例子(不可运行,只是为了理解):

class Field extends Database {
    public function createFieldToForm( $fieldName, $formId )
    {
         // static transactionCount = 0
         // transactionCount = 0
         $this->beginTransaction();   
//           .... createFieldToForm code ....
         $last_id_new_fieldName = $this->insert( $fieldName );
         $formFields = new FormFields();
         $formFields->assignFieldToForm( $last_id_new_fieldName, $formId );
         $this->commit();
    }

    public function insert( $fieldName )
    {
         try {
              // static transactionCount = 1
              // transactionCount = 1
              $this->beginTransaction();
              $dbh = Database::getDatabaseConnection();
              $dbh->prepare( "INSERT INTO form(fieldname) VALUES (:fieldname)" );
            //   ... bind ...
              $dbh->execute();
              $this->commit();
              return $dbh->lastInsertId();
         }
         catch (PDOException $e) {
             $this->rollback();
         }
    }
}

class FormFields extends Database {
    public function assignFieldToForm( $idFieldName, $formId )
    {
       // static transactionCount = 1
              // transactionCount = 0
       $this->beginTransaction();
//              ...  assign the created field to the form ....
       $this->insert( $idFieldName, $formId );
       $this->commit();
    }

    public function insert( $idFieldName, $formId )
    {
         try {
 // static transactionCount = 2
              // transactionCount = 1
              $this->beginTransaction();
              $dbh = Database::getDatabaseConnection();
              $dbh->prepare( "INSERT INTO form_fields(idfield,formid) VALUES (:idfield,:formid)" );
            //   ... bind ...
              $dbh->execute();
              $this->commit();
         }
         catch (PDOException $e) {
             $this->rollback();
         }
    }
}

const FORM_USER_INFORMATION = 3;
$fieldPhone = new Field();
$fieldPhone->createFieldToForm( "phone_number", FORM_USER_INFORMATION  );

正如您在这段代码的 cmets 中看到的,$transactionCount 的值是否是静态的会有很大不同,但这个问题的重点是关于静态属性,如果它的值可能是在执行(例如)createFieldToForm 期间被另一个代码线程/函数或外部调用更改。您可以向我推荐什么?

【问题讨论】:

    标签: php mysql database pdo insert


    【解决方案1】:

    这个类不是来自 PHP 手册,而是来自 cmets 到手册页。这使得它故意不可靠的来源。

    要解决您的问题,只需摆脱所有这些“交易”。因为仅对单个查询使用事务是没有意义的。

    因此,很可能您根本不需要事务、计数器或此类。

    【讨论】:

    猜你喜欢
    • 2016-03-18
    • 2011-10-06
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2010-10-05
    • 2010-12-12
    相关资源
    最近更新 更多