我在該領域相對較新,所以請多多包涵。我有一個內部功能很少的課程。它使用 workerman 來啟動服務器。我正在嘗試在服務器啟動(function load())上加載一些資料,然后在請求時使用該資料顯示在頁面上$key。類似于 API 呼叫。
csv中的資料是
doctor,31234-32223
police officer,342-341
firefighter,543-3345
worker,12223
developer,120045
class App
{
public $getPair = null;
public $dataToLoad= [];
protected $dispatcher = null;
/**
* start
*/
public function start()
{
$this->dispatcher = \FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $r) {
foreach ($this->routeInfo as $method => $callbacks) {
foreach ($callbacks as $info) {
$r->addRoute($method, $info[0], $info[1]);
}
}
});
\Workerman\Worker::runAll();
}
function load()
{
$files = "load.csv";
foreach($files as $file) {
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 4096, ",")) !== FALSE) {
$dataToLoad[$data[1]] = $data[0];
}
fclose($handle);
}
}
return $this->dataToLoad;
}
function getData($getPair) {
foreach ($this->dataToLoad as $key => $value){
if($getPair === $key){
return array($key.','.$value);
} else {
echo "missing";
}
}
}
/**
* @param TcpConnection $connection
* @param Request $request
* @return null
*/
public function onMessage($connection, $request)
{
static $callbacks = [];
try {
$path = $request->path();
$method = $request->method();
$key = $method . $path;
$callback = $callbacks[$key] ?? null;
if ($callback) {
$connection->send($callback($request));
return null;
}
$ret = $this->dispatcher->dispatch($method, $path);
if ($ret[0] === Dispatcher::FOUND) {
$callback = $ret[1];
if (!empty($ret[2])) {
$args = array_values($ret[2]);
$callback = function ($request) use ($args, $callback) {
return $callback($request, ... $args);
};
}
$callbacks[$key] = $callback;
$connection->send($callback($request));
return true;
} else {
$connection->send(new Response(404, [], '<h1>404 Not Found</h1>'));
}
} catch (\Throwable $e) {
$connection->send(new Response(500, [], (string)$e));
}
}
然后我有index.php以下
use Mark\App;
$api = new App('http://0.0.0.0:3000');
$api->count = 4; // process count
$api->load(); //load data
$api->get('/key/{key}', function ($request, $key) {
return $api->getData("doctor");
});
$api->start();
錯誤在index.php檔案中就行return $api->getData("key");
錯誤:在 null 上呼叫成員函式 getData()
PHP 警告:未定義的變數 $api
為什么getData()在這種情況下為空,為什么是未定義的,因為我在分配它時已經對其進行了初始化new App()...上面分配它時已經對其進行了初始化?
附言。服務器已正確啟動且沒有錯誤。
uj5u.com熱心網友回復:
匿名/閉包函式沒有作用域到$api,所以可以用 傳遞use。
$api->get('/key/{key}', function ($request, $key) use ($api) {
return $api->getData("doctor");
});
旁注:getData缺少該功能public。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/532797.html
標籤:php
