【问题标题】:PHP: How to make this "wrapper" methods properly?PHP:如何正确地制作这个“包装器”方法?
【发布时间】:2020-04-05 00:26:21
【问题描述】:

我需要这样做,但要避免重复调用 startTransactionstopTransaction

<?php 
//parent: let's supply transactions!
class MegaParent {

    public $__started;
    //code inside this method must be executed only once - at first call
    public function startTransaction()
    {
        if (!$this->__started) {
            echo "Transaction Started\n";
            $this->__started = true;
        }
    }
    //code inside this method must be executed only once - at last call
    public function stopTransaction()
    {
        if ($this->__started) {
            echo "Transaction Stopped\n";
            $this->__started = null;
        }
    }
}
//Child 1: I do something wrapped in transaction 
class ChildOne extends MegaParent {

    public function doer()
    {
        $this->startTransaction();
        echo "Doing ChildOne\n";
        $this->stopTransaction();
    }
}
//Child 2: I do something in transaction too but I need no nested transactions
class ChildTwo extends ChildOne {

    public function doer()
    {
        $this->startTransaction();
        parent::doer();
        parent::doer();
        echo "Doing ChildTwo\n";
        $this->stopTransaction();
    }
}

(new ChildTwo)->doer();

结果:

Transaction Started
Doing ChildOne
Transaction Stopped
Transaction Started
Doing ChildOne
Transaction Stopped
Doing ChildTwo

如何得到这样的结果:

Transaction Started
Doing ChildOne
Doing ChildOne
Doing ChildTwo
Transaction Stopped

?

【问题讨论】:

  • 抱歉,我看到了这个问题。将static 内存用于$__started
  • 我无法解决静态调用的问题,但似乎我使用你关于堆栈的想法得到了结果。
  • 由于 static 和 $this 之间的上下文差异,public static $__started; 将使用 static::$__started 而不是 $this-&gt;$__started 解决您的问题。
  • @AlexBarker,请展示您可以正常工作的整个代码

标签: php architecture transactions


【解决方案1】:

如果您想嵌套事务以仅使用二进制标志来了解有多少已开始和已停止,这很困难。此代码将其替换为 $transactionLevel,在每次调用时递增和递减。

class MegaParent {
    protected $transactionLevel = 0;
    //code inside this method must be executed only once - at first call
    public function startTransaction()
    {
        if ( $this->transactionLevel == 0 ) {
            echo "Transaction Started\n";
        }
        $this->transactionLevel++;
    }
    //code inside this method must be executed only once - at last call
    public function stopTransaction()
    {
        if ( $this->transactionLevel > 0 )  {
            $this->transactionLevel--;
            if ( $this->transactionLevel == 0 ) {
                echo "Transaction Stopped\n";
            }
        }
    }
}

【讨论】:

  • 是的,我应用了类似的方法,现在代码可以根据需要运行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 2018-03-21
  • 1970-01-01
  • 2011-05-08
相关资源
最近更新 更多