Yii2 examples of the use of transactions in the _php instance code

Source: Internet
Author: User

Objective

In general, we do business logic, will not only be associated with a data table, so we face a transaction problem.

A database transaction (DB Transaction) is a series of operations performed as a single logical unit of work, either fully executed or completely not executed. Transaction processing ensures that data-oriented resources are not permanently updated unless all operations within the transactional unit are completed successfully. By combining a set of related actions into a unit that is either fully successful or all failed, you can simplify error recovery and make your application more reliable. To be a transaction, a logical unit of work must satisfy the so-called acid (atomicity, consistency, isolation, and durability) attribute. A transaction is a logical unit of work in a database operation, which is handled by the transaction management subsystem in the DBMS.

Get ready

Database engine is InnoDB

The Yii version used in this article is 2.0.5, as long as it is over 2.0 there is no problem

The operating environment is php7.0.0,mysql5.6

Transactions in Yii

Handling Exceptions

/**
* Test Transaction
*
/Public Function actiontest () {
//create transaction
$TR = Yii:: $app->db->begintransaction ( );
try {for
($i =1; $i <=3; $i + +) {
$test = new Areas ();
$test->name = ' name '. $i;
$test->sort=1;
if ($test->save ()) {
echo ' save $i | ';
}
}
$test = new Areas ();
$test->name = ' ab '. $i;
$test->sorta=1; Write a field that does not exist if
(! $test->save ()) {"Save fail";////////
submit
$tr->commit () If there is no write;
} catch (Exception $e) {
//rollback
$tr->rollback ();
echo "rollback";
}

Run results

Save 1 | Save 2 | Save 3 | Rollback

Note that the data table has no new data generated because the last data was not successfully inserted, triggering a rollback of the transaction.

The trigger for a transaction rollback is a code exception (Exception).

Processing data failed

In general, this is not the obvious exception to our running code, which can be eliminated during the development test.

And the real cause of the data needs to be rolled back is one of our business problems, resulting in no written part of the data.

/**
* Test Transaction
*
/Public Function actiontest () {
//create transaction
$TR = Yii:: $app->db->begintransaction ( );
try {for
($i =1; $i <=3; $i + +) {
$test = new Areas ();
$test->name = ' name '. $i;
$test->sort=1;
if ($test->save ()) {
echo ' save $i | ';
}
}
$test = new Areas ();
$test->name = null; The database design name cannot be empty, causing a write failure.
$test->sort=1;//write nonexistent field if
(! $test->save ()) {
echo "save fail";///
Submit if no write
$tr->commit ();
} catch (Exception $e) {
//rollback
$tr->rollback ();
echo "rollback";
}

The results of the operation are as follows: The database inserts three data.

Save 1 | Save 2 | Save 3 | Save fail

That is, if a data table is not written to the data because of the business logic, the corresponding rollback is not present.

The improvement programme is as follows

/**
* Test Transaction
*
/Public Function actiontest () {
//create transaction
$TR = Yii:: $app->db->begintransaction ( );
try {for
($i =1; $i <=3; $i + +) {
$test = new Areas ();
$test->name = ' name '. $i;
$test->sort=1;
if ($test->save ()) {
echo ' save $i | ';
}
}
$test = new Areas ();
$test->name = null; The database design name cannot be empty, causing a write failure.
$test->sort=1;//write nonexistent field
if (! $test->save ()) {
throw new \yii\db\exception ();//Manually throw an exception, and then capture it below.
}
Submit
$tr->commit (),
catch (Exception $e) {
//rollback
$tr->rollback ();
echo "rollback";
}

The results of the operation are as follows: The database does not insert new data and the transaction is rolled back.

Save 1 | Save 2 | Save 3 | Rollback

Decentralized data-processing

Because of the complexity of the actual project, our database operations are dispersed in different model.

So, the actual code for the project is not what it looks like.

Simulation requirements

Receive parameters:

Name

Gender

Signature

Business Process Flow:

Receive parameters

By the sender of the user's UID, the number of corresponding data table add a digit

Write the name, gender, signature, and previous UID to the User information table

Initialize User Balance Table

Rollback Trigger Time:

Initialization balance table does not have incoming UID export write data

Actual code

Controller/** * Test Transaction-Registered user */Public Function Actionreg () {//Get request $request = Yii:: $app->request;//Set return format $response
= Yii:: $app->response; $response->format = \yii\web\response::format_json;
Returns the JSON//test code, removing the authentication step $name = $request->get ("name");
$gender = $request->get ("gender");
$sign = $request->get ("sign");
Test code, omit the parameter verification step $tr = Yii:: $app->db->begintransaction ();
try {//get UID $uid = App::getseno ();
Userprofile::add ($uid, $name, $gender, 1, $sign);
$user _balance = userbalance::inituserbalance ($uid); $tr->commit ();
Submit data} catch (Exception $e) {//Rollback $TR->rollback (); return $e->getmessage ();//back to custom exception info} returns $user _balance; //userprofile/** * Add user information * @param $user _id * @param $nikename * @param $gender * @param $user _type * @param string $in TRO * @return userprofile * @throws \exception/public static function Add ($user _id, $nikename, $gender, $user _type, $intr O= "") {$model = new userprofile (); $model->gender = $gender; $model->nikename = $nikename;
$model->user_id = $user _id;
$model->user_type= $user _type;
$model->intro= $intro;
$model->update_time = time ();
$insert = $model->insert ();
if (! $insert) {throw new Exception ("No user information written");} return $model; //userbalance/** * Initializes the user's available Balance * @param $user _id/public static function Inituserbalance ($user _id) {$info =self::find (
)->where ([' user_id ' => $user _id])->one (); if (! $info) {$model =new userbalance (); $model->user_id = $user _id; $model->price= "0"; $model->update_time=
Time ();
$insert = $model->insert ();
if (! $insert) {throw new Exception ("No user balances initialized");} $info = $model;
return $info->attributes; }

The normal results are as follows

{"id": 124, "user_id": 1473179883, "price": "0", "update_time": 1473179883}

If the user_id of the initialization user balance portion is not delivered successfully, the result returned is as follows

"No user balances initialized"

We can locate the wrong location for the specific situation and modify it in time.

Transaction (Transaction)

From the above actual code can be seen, create a transaction, as long as within the scope, even if the introduction of the other model can also be abnormal ng back, complete the rollback operation.

In general, the entire YII application uses the same database connection, or it uses a single example.

In Yii\db\connection, the transaction object is also cached:

Class Connection extends Component
{
//Save valid transaction object for current connection
private $_transaction;
A transaction object is already cached and the transaction object is valid, returns the transaction object
//Otherwise returns the null public
function gettransaction ()
{return
$this->_ Transaction && $this->_transaction->getisactive ()? $this->_transaction:null;
}
See how the Public function begintransaction ($isolationLevel = null) of the transaction object is used when the transaction is enabled
{
$this->open ();
The cached transaction object is valid, the transaction object in the cache is used
//otherwise a new transaction object is created
if (($transaction = $this->gettransaction ()) = = null) {
$ Transaction = $this->_transaction = new Transaction ([' DB ' => $this]);
}
$transaction->begin ($isolationLevel);
return $transaction;
}

Therefore, it can be considered that the whole YII application uses the same Transaction object, that is to say, the transaction::_level has continuity throughout the life cycle of the application. This is the key and prerequisite for implementing transaction nesting.

The above is a small set to introduce the YII2 in the transaction of the use of the example code detailed, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.