summerblue / laravel-shop

Laravel 电商实战教程的项目代码

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

self static 不同

maxlcoder opened this issue · comments

在model,order中

 public static function findAvailableNo()
    {
        // 订单流水号前缀
        $prefix = date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $no = $prefix.str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('no', $no)->exists()) {
                return $no;
            }
            usleep(100);
        }
        \Log::warning(sprintf('find order no failed'));
        return false;
    }
    public static function getAvailableRefundNo()
    {
        do {
            // Uuid类可以用来生成大概率不重复的字符串
            $no = Uuid::uuid4()->getHex();
            // 为了避免重复我们在生成之后在数据库中查询看看是否已经存在相同的退款订单号
        } while (self::query()->where('refund_no', $no)->exists());
        return $no;
    }

看到一个使用self::query 一个 使用 static::query 这两处为什么不保持统一,是说注意到了self和static的区别,还是忽略

在本项目中没有区别。

static 和 self 在有继承关系时会有区别,比如有另外的类继承了 Order 这个类并且重写(Override)了 query() 这个静态方法,这时候 static::query() 调用的是子类的 query()self::query() 则调用的是 Orderquery()。具体可以搜索『静态延迟绑定』。

static::query() 会更严谨一些。