Hyperf 註解別用在模型上!

邢闖洋發表於2020-11-25

在 Hyperf 中,我們習慣將一些依賴的類以註解的方式引入進來,簡單易用,程式碼也更簡潔可讀。

我們應該避免將 Model 用註解的方式引入進來,因為這會使 Model 變成單例,使用不當的話在某些場景會造成意向不到的結果。

測試

測試模型中使用 this

新建一個 TestCommand,寫入如下執行程式碼

<?php

namespace App\Command;

...

/**
 * @Command
 */
class TestCommand extends HyperfCommand
{
    /**
     * @Inject()
     * @var HyperfTest
     */
    protected $hyperfTest;

    public function handle()
    {
        for ($i = 1; $i <= 2; $i++) {
            $this->hyperfTest->testInsert([
                'name' => "字串$i"
            ]);
        }

        $this->line('Test Success!', 'info');
    }
}

新建一個 Model,寫入如下模型程式碼

public function testSave($data)
{
    $this->name = $data['name'];
    $this->save();
}

檢視結果

Hyperf 註解別用在模型上!
表中只插入了最後一次迴圈的資料

測試使用 New

public function testSave($data)
{
    $test = new HyperfTest();
    $test->name = $data['name'];
    $test->save();
}

檢視結果

Hyperf 註解別用在模型上!

結論

如果用註解的方式引入 Model,並且在 Model 中用 this 插入資料,在迴圈插入場景下,模型會認為這是對一個模型反覆操作,就會導致只插入了最後一條資料,換成 New 就可以了,為了避免這種事情,我們在引用模型時不要用註解這種錯誤的方式引入了。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章