PHP BaaS 后端云用法

wen PHP项目 2

本文目录导读:

PHP BaaS 后端云用法

  1. 国际主流:Supabase(PostgreSQL + 实时 + 认证)
  2. 国内常用:微信云开发(适合小程序/PHP对接)
  3. 轻量级:LeanCloud(国内稳定,支持PHP SDK)
  4. Firebase(PHP 通过 Admin SDK)
  5. 核心概念总结(重要)
  6. 实战建议(选型指南)
  7. 最简演示:用 Supabase 做一个“用户留言板”

PHP BaaS(后端即服务)的核心思想是不自己写服务器代码,直接调用云服务商提供的 SDK 或 API 来完成数据库、用户认证、文件存储等操作。

以下是主流的 PHP BaaS 用法,涵盖国际主流(Supabase/Firebase)国内常用(微信云开发/LeanCloud)


国际主流:Supabase(PostgreSQL + 实时 + 认证)

Supabase 是目前 PHP 开发者最常用的 BaaS,因为它底层是 PostgreSQL,对关系型数据友好,且自带 RESTful API。

安装 SDK:

composer require supabase/supabase-php

基础用法(初始化):

<?php
require 'vendor/autoload.php';
use Supabase\Client;
$client = new Client(
    'https://your-project.supabase.co', // Supabase URL
    'your-anon-public-key'              // 公开的 anon key
);

示例 1:查询数据(相当于 SELECT)

// 获取用户列表
$response = $client->from('users')->select('*')->execute();
$users = $response->getResult();
// 带条件查询
$response = $client->from('products')
    ->select('*')
    ->where('price', 'lt', 100) // 小于100
    ->order('created_at', 'desc')
    ->limit(10)
    ->execute();

示例 2:插入数据(相当于 INSERT)

$response = $client->from('posts')->insert([ => 'Hello BaaS',
    'content' => '这是通过PHP插入的数据',
    'user_id' => 123
])->execute();

示例 3:用户认证(Auth)

// 注册
$response = $client->auth()->signUp([
    'email' => 'user@example.com',
    'password' => 'secure_password'
]);
// 登录
$response = $client->auth()->signIn([
    'email' => 'user@example.com',
    'password' => 'secure_password'
]);
// 获取JWT Token
$token = $response->getAccessToken();

示例 4:文件上传(Storage)

use Supabase\Storage\StorageClient;
$storage = new StorageClient('https://your-project.supabase.co', 'your-anon-key');
$bucket = $storage->bucket('avatars');
$bucket->upload('path/to/file.png', file_get_contents('local.png'), [
    'contentType' => 'image/png'
]);

国内常用:微信云开发(适合小程序/PHP对接)

如果做微信小程序,PHP 后端通过 云调用HTTP API 访问云数据库。

基础用法(调用云函数): 由于 PHP 无法直接运行在小程序里,通常用 PHP 调用微信云函数的 HTTPS 接口。

示例:PHP 调用云函数

<?php
// 1. 获取 access_token
$appid = '你的AppID';
$secret = '你的AppSecret';
$token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$token_data = json_decode(file_get_contents($token_url), true);
$access_token = $token_data['access_token'];
// 2. 调用云函数
$cloud_func_url = "https://api.weixin.qq.com/tcb/invokecloudfunction?access_token={$access_token}&env=你的环境ID&name=login";
$params = json_encode([
    'action' => 'getUserInfo',
    'user_id' => 123
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cloud_func_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;

轻量级:LeanCloud(国内稳定,支持PHP SDK)

安装:

composer require leancloud/leancloud-sdk

初始化:

use LeanCloud\Client;
use LeanCloud\Object;
Client::initialize("appId", "appKey", "masterKey");

CRUD 操作:

// 创建对象(相当于INSERT)
$todo = new Object("Todo");
$todo->set("title", "买牛奶");
$todo->save();
// 查询(相当于SELECT)
$query = new Query("Todo");
$query->equalTo("status", "active");
$todos = $query->find();
// 更新
$todo->set("status", "completed");
$todo->save();

用户管理(注册登录):

use LeanCloud\User;
// 注册
$user = new User();
$user->setUsername("bob");
$user->setPassword("secret");
$user->setEmail("bob@example.com");
$user->signUp();
// 登录
$user = User::logIn("bob", "secret");

Firebase(PHP 通过 Admin SDK)

安装:

composer require kreait/firebase-php

初始化(Admin SDK,用于服务端):

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
$serviceAccount = ServiceAccount::fromJsonFile('firebase-credentials.json');
$firebase = (new Factory)
    ->withServiceAccount($serviceAccount)
    ->withDatabaseUri('https://your-db.firebaseio.com');
$database = $firebase->createDatabase();
$auth = $firebase->createAuth();

数据库操作:

// 写入数据
$reference = $database->getReference('users/001');
$reference->set([
    'name' => 'John Doe',
    'email' => 'john@example.com'
]);
// 读取数据
$snapshot = $reference->getChild('name')->getValue();
echo $snapshot; // John Doe

核心概念总结(重要)

概念 作用 对比传统后端
Database 云数据库(如PostgreSQL,MongoDB) 代替自建MySQL
Auth 用户注册/登录/权限 代替自建Session/JWT
Storage 文件上传/图片存储(带CDN) 代替自建文件服务器
Realtime 实时推送(如聊天) 代替WebSocket服务端
Cloud Functions 在云端运行一段代码 代替自写API接口

实战建议(选型指南)

  1. 如果做国内小程序:优先用 微信云开发,免备案、免部署,直接 PHP 请求接口。
  2. 如果做海外项目:选 Supabase,开源可控,Postgres 熟悉关系型,PHP 的 supabase-php 库很完善。
  3. 如果是纯 PHP 老项目:用 LeanCloud,PHP 的 leancloud-sdk 最成熟,性能稳定。
  4. 如果需要实时聊天/多人协作:选 Firebase,实时推送技术最强。

最简演示:用 Supabase 做一个“用户留言板”

<?php
// 1. 初始化
require 'vendor/autoload.php';
use Supabase\Client;
$client = new Client('PROJECT_URL', 'ANON_KEY');
// 2. 提交留言
if ($_POST['submit']) {
    $client->from('messages')->insert([
        'name' => $_POST['name'],
        'content' => $_POST['content'],
        'created_at' => date('Y-m-d H:i:s')
    ])->execute();
}
// 3. 读取留言并显示
$response = $client->from('messages')
    ->select('*')
    ->order('created_at', 'desc')
    ->execute();
?>
<!DOCTYPE html>
<html>
<body>
    <form method="POST">
        <input name="name" placeholder="名字">
        <textarea name="content" placeholder="内容"></textarea>
        <button name="submit">留言</button>
    </form>
    <?php foreach ($response->getResult() as $msg): ?>
        <p><b><?= $msg['name'] ?>:</b> <?= $msg['content'] ?></p>
    <?php endforeach; ?>
</body>
</html>

注意: 在 PHP 中,绝对不要Service KeyMaster Key 暴露给前端,如果你是前后端分离,PHP 应该作为中间层,负责验证身份后调用 BaaS,把敏感操作放在 PHP 服务端执行。

抱歉,评论功能暂时关闭!