PHP Eval的替代方案包括一个文件


PHP Eval alternative to include a file

我目前正在运行一个使用beanstall+supervisor+PHP的队列系统。

我希望我的员工在新版本可用时自动死亡(基本上是代码更新)。

我当前的代码如下

class Job1Controller extends Controller
{
public $currentVersion = 5;
public function actionIndex()
{
    while (true) {
        // check if a new version of the worker is available
        $file = '/config/params.php';
        $paramsContent = file_get_contents($file);
        $params = eval('?>' . file_get_contents($file));
        if ($params['Job1Version'] != $this->currentVersion) {
            echo "not the same version, exit worker 'n";
            sleep(2);
            exit();
        } else {
            echo "same version, continue processing 'n";
        }
    }
}
} 

当我更新代码时,params文件将更改为新的版本号,这将迫使工作程序终止。我不能使用include,因为该文件将在while循环中加载到内存中。知道文件params.php在安全性方面并不重要,我想知道是否有其他方法可以做到这一点?

编辑:params.php如下所示:

<?php
return [
'Job1Version' => 5
];
$params = require($file);

由于您的文件有一个return语句,因此将传递返回的值。

经过几次测试,我终于找到了一个不再需要版本控制的解决方案。

$reflectionClass = new 'ReflectionClass($this);
$lastUpdatedTimeOnStart = filemtime($reflectionClass->getFileName());
while (true) {
    clearstatcache();
    $reflectionClass = new 'ReflectionClass($this);
    $lastUpdatedTime = filemtime($reflectionClass->getFileName());
    if ($lastUpdatedTime != $lastUpdatedTimeOnStart) {
        // An update has been made, exit
    } else {
       // worker hasn't been modified since running
    }
}

每当更新文件时,工作人员都会自动退出感谢@Rudie,他为我指明了正确的方向。