PHP 上的文档编号

Numeration of documents on PHP

PHP、Laravel 6.0:我无法编写一个有效的静态函数或一个变量来获取我的文档的递增编号。每次我创建文档时,它都应该设置它的编号(文档 #1、#2、#3...等)

我已经在 Whosebug 上查看并尝试过类似的问题,但没有成功。

我有一个 Observer Class,它应该处理 "creating" 事件并使用该函数设置新号码。 这是我的尝试:

class DocumentObserver
{
    /**
     * Found this one on Whosebug but it didn't work
     */
    public function currentNum()
    {
        static $num = 6;
        $num++;
        return $num;
    }

    /**
     * Tried to use a property but it didn't work as well
     */
    public static $currentNumber = 0;

    /**
     * Set number to the document
     */
    public function setNumber(Document $document)
    {
        //set format of document number (XX00000001)
        $document->number = "IQR" . sprintf('%06d', self::currentNum());
    }

    /**
     * Handle the rent "creating" event.
     *
     * @param  \App\Models\Document $document
     * @return void
     */
    public function creating(Document $document)
    {
        $this->setNumber($document);
    }
  }

如果你能帮我解决这个问题,我会很高兴。在这种情况下,任何额外的建议将不胜感激,因为我是 PHP & Laravel.

的新手

"Two requests mean two executions of the script, and two distinct memory spaces. At the end of the first request, the first script ends, and all the changes it made in memory are forgotten. The second script starts from scratch, with all the variables having their default value." 来自 Whosebug。

谢谢 Jeto 和 Elias Soares 的解释。

到目前为止,这是我的解决方案:

public function setNumber(Document $document)
  {
    //Get the highest "id" in the table + 1
    $max_id= Document::max('id') + 1;

    //set format of document number (XX00000001)
    $document->number = 'SQ' . sprintf('%07d', $max_id);
  }