开发者

MySQL transactions with PHP - queue statements?

开发者 https://www.devze.com 2023-04-12 14:03 出处:网络
This thought just occurred to me, and I have no idea if it\'s crazy or not.No examples I\'ve found online are set up this way.I\'m building a wrapper around MySQLi (or maybe PDO) and I\'m just in the

This thought just occurred to me, and I have no idea if it's crazy or not. No examples I've found online are set up this way. I'm building a wrapper around MySQLi (or maybe PDO) and I'm just in the designing stages. This is for a personal project to learn more about OO design, so while I appreciate the thoughts of using Doctrine or Propel or something, no thanks. This question is to help me learn some better design principles; I know the code will work, but from a design perspective, am I running wild?

This will be my first time working with transactions in PHP with MySQL. I understand the basics - use a try/catch statement, commit at the end, rollba开发者_开发技巧ck if there's an exception. But in the middle, here is a list of the statements to execute:

(pseudo-code)

try
{
  $db->startTransaction();
  $db->query('...');
  $db->query('...');
  $db->query('...');
  $db->commit();
} catch (Exception $exc)
{
  $db->rollback();
}

What if the query method adds the queries to an internal array? Then the commit method does this type of try/catch internally and tosses out another exception. Like this (again, pseudo-code):

$db = new AwesomeDBWrapper('...');
$db->query('...');
$db->query('...');

try
{
  $db->commit();
} catch (AwesomeDBWrapperCommitException $exc)
{
  echo $exc;
}

The commit method could start the transaction, query, commit or rollback. It can work, but my question is really about design - is that too much?

There are pitfalls with my pseudo-code - it doesn't take into account a read vs. a write to the database, so there should really be a query, update, insert, delete, etc. methods.

Does this make any sense from OO design perspective? It seems nice from a coding perspective - you can write your statements outside the try/catch in the normal code, and then execute later. It also seems a little annoying in that regard too ...


Does it make sense from an OO design perspective? Kinda. Does it make sense from a database usage perspective? Definitely not.

As pointed out by Marc B in a comment, the database already queues the operations anyway, as they are blocking calls*. They will happen in that order. Just let it do it's thing.

*: although you CAN make non-blocking calls, it isn't usually the case.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号