簡體   English   中英

PHP:使用未實例化的類生成唯一ID

[英]PHP: Generating Unique ID with Uninstantiated Class

假設我要擁有一組對象,每個對象應具有自己的唯一ID。 不需要花哨的東西,只需一個字母表示它是什么類型的對象,以及一個數字表示已經創建了多少個對象。 因此,例如,a0,a1,b0,c0,c1,c2,c3等。

與其設置全局變量來跟蹤每個對象已經存在的數量,不如使用類。 像這樣:

class uniqueIDGenerator
{
  private $numberAObjs;
  private $numberBObjs;
  private $numberCObjs;

  public function generateID ($type) {
    if($type === "A") {
      return 'a' . (int) $this->$numberAObjs++;
    } else if($type === "B") {
      return 'b' . (int) $this->$numberBObjs++;
    } else if($type === "C") {
        return 'c' . (int) $this->$numberCObjs++;
    }
  }
}

class obj
{
  private $id;

  function __construct($type) {
    $this->id = uniqueIDGenerator::generateID($type);
  }
}

這樣做的問題在於,如果未實例化uniqueIDGenerator,則其generateID函數對於每種類型(例如a0,b0,c0等)將始終返回相同的值,因為實際上尚未在內存中創建其私有變量。 同時,使其成為obj的屬性將不起作用,因為隨后每次創建obj時,它都會擁有自己的uniqueIDGenerator實例,因此也總是返回a0,b0,c0(假設它僅被稱為一次在該對象的方法中)等等。

唯一的選擇似乎是使uniqueIDGenerator成為其自己的全局實例,以便obj的構造函數可以引用它,但這似乎是不良的編碼實踐。 有什么好的OOP方法可以使所有對象分離並井井有條?

首先,您可以修改對象構造函數:

class obj
{
  private $id;

  function __construct($type, $id) {
    $this->id = $id;
  }
}

...

$id_generator = new uniqueIDGenerator(); // instanciation of the generator

$obj1 = new obj(type, $id_generator->generateID($type));
$obj2 = new obj(type, $id_generator->generateID($type));
$obj3 = new obj(type, $id_generator->generateID($type));
...

在我的項目中,我將創建一個名為ObjectFactory的類:

    class ObjectFactory {
       private $id_generator;

       public function __construct($id_generator) {
          $this->id_generator = $id_generator;
       }

       public function create_object($type) {
          return new obj($this->id_generator->generateID($type));
       }
    }

...

$id_generator = new uniqueIDGenerator(); // instanciation of the generator
$obj_factory = new ObjectFactory($id_generator); 

$obj1 = obj_factory->create_object($type);
$obj2 = obj_factory->create_object($type);
$obj3 = obj_factory->create_object($type);

最后,為避免使用此類的全局實例,可以執行Singleton(根據您的情況):

class uniqueIDGenerator
{
  private $numberAObjs;
  private $numberBObjs;
  private $numberCObjs;

  public static $instance = null;

  public function __construct() {
    $numberAObjs = 0;
    $numberBObjs = 0;
    $numberCObjs = 0;
  }

  public static function generateID($type) {
     if(!self::$instance)
        self::$instance = new uniqueIDGenerator();

     return self::$instance->generateID2($type);
  }

  private function generateID2 ($type) {
    if($type === "A") {
      return 'a' . (int) $this->numberAObjs++;
    } else if($type === "B") {
      return 'b' . (int) $this->numberBObjs++;
    } else if($type === "C") {
        return 'c' . (int) $this->numberCObjs++;
    }
  }
}

uniqueIDGenerator::generateID("A");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM