PHP跨平台桌面应用开发实践

PHP通常用于Web开发,但也可以用来开发桌面应用。结合PHP Desktop或Electron + PHP后端,可以构建跨平台桌面应用。今天说说PHP桌面应用开发的方案。

PHP Desktop是一个将PHP应用打包成桌面应用的解决方案。它内嵌了一个Web服务器和浏览器窗口。

```php
// PHP Desktop应用的入口文件
$app = new \PHPDesktop\Application([
'name' => 'My Desktop App',
'width' => 1024,
'height' => 768,
'resizable' => true,
'fullscreen' => false,
'console' => false,
]);

// 注册路由
$app->get('/', function () {
return <<


桌面应用

 

PHP桌面应用


点击

 


HTML;
});

$app->get('/api/data', function () {
header('Content-Type: application/json');
return json_encode(['status' => 'ok', 'data' => [1, 2, 3]]);
});

$app->run();
?>
```

用PHP做桌面应用的API后端,前端用HTML/JS渲染:

```php
// 本地文件操作API
class LocalFileAPI
{
public function readFile(string $path): array
{
if (!file_exists($path)) {
return ['error' => '文件不存在'];
}

return [
'content' => file_get_contents($path),
'size' => filesize($path),
'modified' => date('Y-m-d H:i:s', filemtime($path)),
];
}

public function writeFile(string $path, string $content): array
{
$result = file_put_contents($path, $content);
if ($result === false) {
return ['error' => '写入失败'];
}
return ['success' => true, 'bytes' => $result];
}

public function listDirectory(string $path): array
{
if (!is_dir($path)) {
return ['error' => '目录不存在'];
}

$items = scandir($path);
$files = [];

foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$fullPath = $path . '/' . $item;
$files[] = [
'name' => $item,
'type' => is_dir($fullPath) ? 'dir' : 'file',
'size' => is_file($fullPath) ? filesize($fullPath) : 0,
'modified' => date('Y-m-d H:i:s', filemtime($fullPath)),
];
}

return $files;
}

public function createDirectory(string $path): array
{
if (is_dir($path)) {
return ['error' => '目录已存在'];
}

$result = mkdir($path, 0755, true);
return ['success' => $result];
}

public function deleteFile(string $path): array
{
if (!file_exists($path)) {
return ['error' => '文件不存在'];
}

$result = is_dir($path) ? rmdir($path) : unlink($path);
return ['success' => $result];
}
}
?>
```

Electron + PHP的桌面应用:

```javascript
// main.js (Electron主进程)
const { app, BrowserWindow, ipcMain } = require('electron');
const { spawn } = require('child_process');
const path = require('path');

let phpProcess;
let mainWindow;

function startPHPServer() {
phpProcess = spawn('php', [
'-S', '127.0.0.1:8080',
'-t', path.join(__dirname, 'public'),
path.join(__dirname, 'server.php')
]);

phpProcess.stdout.on('data', (data) => {
console.log(`PHP: ${data}`);
});
}

function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
});

mainWindow.loadURL('http://127.0.0.1:8080');
}

app.whenReady().then(() => {
startPHPServer();
setTimeout(createWindow, 1000);
});

app.on('window-all-closed', () => {
if (phpProcess) phpProcess.kill();
app.quit();
});
```

PHP桌面应用的API层:

```php
// server.php
$route = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Content-Type: application/json; charset=utf-8');

// 获取系统信息
if ($route === '/api/system/info') {
echo json_encode([
'os' => PHP_OS,
'php_version' => PHP_VERSION,
'hostname' => gethostname(),
'memory' => [
'usage' => round(memory_get_usage(true) / 1024 / 1024, 2) . 'MB',
'peak' => round(memory_get_peak_usage(true) / 1024 / 1024, 2) . 'MB',
],
]);
exit;
}

// 数据库管理
if (str_starts_with($route, '/api/database')) {
$action = $_GET['action'] ?? '';
if ($action === 'tables') {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$tables = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);
echo json_encode(['tables' => $tables]);
exit;
}
}

echo json_encode(['error' => 'Route not found']);
exit;
?>
```

虽然PHP不是桌面应用的主流语言,但在一些工具类的桌面应用中,PHP结合内嵌浏览器或Electron可以实现快速开发。PHP负责后端逻辑和数据处理,前端负责界面展示,各司其职。

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐