dongyan3562 2019-02-14 07:08
浏览 83

使用php和singleton只运行一次该进程

I am reading data from the sheet and want to implement singleton in my process so that I can run read function, one at a time.

I have written a code for the same which calls the class and set a static variable and then call the function to check if it has the class, so if the class is there then don't run the read function.

class DataParser extends config {

   private static $_instance = false;

   public static
   function getInstance() {
     if (self::$_instance == false) {
        print_r("expression");
        self::$_instance = true;
        return self::$_instance;

     }
     return false;
   }

   function __construct($params) {}
}

$dataParser = new DataParser($confData);
$p = DataParser::getInstance();
if ($p) {
 $res = $dataParser - > read();

}

I want to run the read function one at a time, if one read is running then the other read will not run.

  • 写回答

1条回答 默认 最新

  • dongwen7283 2019-02-14 08:55
    关注

    A singleton needs to prevent public constructing and cloning. This can simply be achieved by declaring these methods as protected.

    To check if read() is currently being executed, you can use a flag $isRunning.

    <?php
    
    class DataParser
    {
        protected static $instance;
    
        protected static $isRunning = false;
    
        protected function __construct()
        {
        }
    
        protected function __clone()
        {
        }
    
        public static function getInstance(): DataParser
        {
            if (null === self::$instance) {
                self::$instance = new self();
            }
    
            return self::$instance;
        }
    
        public function read(): void
        {
            if (static::$isRunning) {
                throw new RuntimeException('DataParse is already running');
            }
    
            static::$isRunning = true;
    
            // Do some reading
    
            static::$isRunning = false;
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)