
メソッド内でトランザクションが処理されている場合、データの整合性を担保するために、try~catch を利用することになると思います。
以下、Cake2からCake4への移行する際の参考例です。
Cakephp2: トランザクション例
try {
$this->begin();
// なんか保存系の処理とか
$this->commit();
} catch (Exception $e) {
$this->rollback();
throw $e;
}
トランザクションの処理の書き方は大体決まっているので、おおよそCake2で実装されているのは、例に示したような感じになると思います。
Cake4に移行する際は、モデルの場合、$this->getConnection() すればよく、コントローラの場合は ConnectionManager::get() を利用すればよいでしょう。
Cakephp4: トランザクション例: モデル
// メソッド内に記述
$dataSource = $this->getConnection();
try {
$entity = $this->newEntity($this->getRequest()->getData(), ['validate' => false]);
if (!$this->save($entity)) {
throw new \Exception('処理に失敗しました');
}
if (!$this->Logs->save($entity)) {
throw new \Exception('ログ追加に失敗しました');
}
$dataSourse->commit();
} catch (\Exception $e) {
$dataSourse->rollback();
return $e->getMessage();
}
Cakephp4: トランザクション例: コントローラー
use Cake\Datasource\ConnectionManager;
// クラスメソッド内などで
$dataSource = ConnectionManager::get('default');
$dataSource->begin();
try {
$entity = $this->Hoges->newEntity($this->getRequest()->getData(), ['validate' => false]);
if (!$this->save($entity)) {
throw new \Exception('処理に失敗しました');
} if (!$this->Logs->save($entity)) {
throw new \Exception('ログ追加に失敗しました');
}
$dataSource->commit();
return $this->redirect('成功時の遷移先');
} catch (\Exception $e) {
$dataSource->rollback();
$this->Flash->error($e->getMessage());
return $this->redirect('失敗時の遷移先');
}