傳統 Web 開發以關聯式資料庫 + SQL 為核心,CRUD(Create/Read/Update/Delete)操作透過結構化查詢語言完成。隨著資料互聯需求增長,語義化 Web(Semantic Web) 技術棧——RDF(資源描述框架) 與 SPARQL(查詢語言)——提供了去中心化、自我描述、可推理的資料模型,適合知識圖譜、開放資料、跨機構整合等場景。本文示範如何用 PHP + SPARQL 對 RDF 資料執行 CRUD,並對比 SQL 思維差異。
| 術語 | 全稱 | 角色 |
|---|---|---|
| RDF | Resource Description Framework | 資料模型:主詞-謂詞-受詞 三元組 |
| SPARQL | Simple Protocol and RDF Query Language | 查詢/更新語言,類 SQL 但針對圖結構 |
| URI/IRI | Uniform Resource Identifier | 全域唯一識別符,取代資料庫主鍵 |
| Prefix | 命名空間前綴 | 縮寫冗長 URI,如 foaf: = https://xmlns.com/foaf/0.1/ |
| Triple Store | 三元組存儲 | RDF 資料庫(如 Apache Jena/Fuseki, GraphDB, Virtuoso) |
easyrdf/easyrdf(RDF 操作)、php-http/guzzle7-adapter(HTTP 客戶端)https://localhost:3030/ds/sparql(Fuseki 範例)composer require easyrdf/easyrdf php-http/guzzle7-adapter
SQL
SELECT realname, dob, location
FROM UserTable
WHERE realname = 'John Smith';
SPARQL
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX schema: <https://schema.org/>
SELECT ?realname ?dob ?location
FROM <https://example.org/data/users>
WHERE {
?person a foaf:Person ;
foaf:name ?realname ;
schema:birthDate ?dob ;
schema:location ?location .
FILTER(?realname = "John Smith")
}
關鍵差異:
? 開頭,支援模式比對FROM 指定具名圖(Named Graph),而非資料表SQL
INSERT INTO UserTable (realname, dob, location)
VALUES ('John Smith', '1985-01-01', 'Bristol, UK');
SPARQL (SPARQL 1.1 Update)
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX schema: <https://schema.org/>
PREFIX ex: <https://example.org/>
INSERT DATA {
GRAPH <https://example.org/data/users> {
ex:user_123 a foaf:Person ;
foaf:name "John Smith" ;
schema:birthDate "1985-01-01"^^xsd:date ;
schema:location "Bristol, UK" .
}
}
注意: 主體 ex:user_123 為完整 URI,非自增 ID。資料類型明確標註(^^xsd:date)。
SQL
UPDATE UserTable
SET location = 'London, UK'
WHERE realname = 'John Smith';
SPARQL
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX schema: <https://schema.org/>
PREFIX ex: <https://example.org/>
WITH <https://example.org/data/users>
DELETE {
?person schema:location ?oldLoc .
}
INSERT {
?person schema:location "London, UK" .
}
WHERE {
?person a foaf:Person ;
foaf:name "John Smith" ;
schema:location ?oldLoc .
}
DELETE/INSERT 模式 精確控制移除與新增的三元組,避免誤刪無關屬性。
SQL
DELETE FROM UserTable WHERE realname = 'John Smith';
SPARQL
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX ex: <https://example.org/>
WITH <https://example.org/data/users>
DELETE {
?person ?p ?o .
}
WHERE {
?person a foaf:Person ;
foaf:name "John Smith" ;
?p ?o .
}
刪除該主體的所有三元組(級聯刪除),對應 SQL 的級聯外鍵或應用層邏輯。
<?php
require 'vendor/autoload.php';
use EasyRdf\Graph;
use EasyRdf\Sparql\Client;
use EasyRdf\NamespaceMapper;
class SemanticUserRepository
{
private Client $sparql;
private string $graphUri;
private string $baseUri;
public function __construct(string $sparqlEndpoint, string $graphUri, string $baseUri = 'https://example.org/')
{
$this->sparql = new Client($sparqlEndpoint);
$this->graphUri = $graphUri;
$this->baseUri = $baseUri;
NamespaceMapper::set('foaf', 'https://xmlns.com/foaf/0.1/');
NamespaceMapper::set('schema', 'https://schema.org/');
NamespaceMapper::set('ex', $baseUri);
}
/** 產生唯一 URI */
private function newUserUri(): string
{
return $this->baseUri . 'user_' . bin2hex(random_bytes(8));
}
/** CREATE */
public function create(array $data): string
{
$uri = $this->newUserUri();
$graph = new Graph($this->graphUri);
$resource = $graph->resource($uri);
$resource->addType('foaf:Person');
$resource->set('foaf:name', $data['name']);
$resource->set('schema:birthDate', $data['dob']);
$resource->set('schema:location', $data['location']);
$update = "INSERT DATA { GRAPH <{$this->graphUri}> { " . $graph->serialise('turtle') . " } }";
$this->sparql->update($update);
return $uri;
}
/** READ by name */
public function findByName(string $name): ?array
{
$query = "
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX schema: <https://schema.org/>
SELECT ?uri ?dob ?location
FROM <{$this->graphUri}>
WHERE {
?uri a foaf:Person ;
foaf:name ?name ;
schema:birthDate ?dob ;
schema:location ?location .
FILTER(?name = \"$name\")
}
LIMIT 1
";
$result = $this->sparql->query($query);
foreach ($result as $row) {
return [
'uri' => (string)$row->uri,
'name' => $name,
'dob' => (string)$row->dob,
'location' => (string)$row->location,
];
}
return null;
}
/** UPDATE location */
public function updateLocation(string $name, string $newLocation): bool
{
$update = "
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
PREFIX schema: <https://schema.org/>
WITH <{$this->graphUri}>
DELETE { ?person schema:location ?old . }
INSERT { ?person schema:location \"$newLocation\" . }
WHERE {
?person a foaf:Person ;
foaf:name \"$name\" ;
schema:location ?old .
}
";
$result = $this->sparql->update($update);
return $result !== false;
}
/** DELETE */
public function deleteByName(string $name): bool
{
$update = "
PREFIX foaf: <https://xmlns.com/foaf/0.1/>
WITH <{$this->graphUri}>
DELETE { ?person ?p ?o . }
WHERE {
?person a foaf:Person ;
foaf:name \"$name\" ;
?p ?o .
}
";
$result = $this->sparql->update($update);
return $result !== false;
}
}
// 使用範例
$repo = new SemanticUserRepository(
'https://localhost:3030/ds/update', // SPARQL Update 端點
'https://example.org/data/users'
);
// Create
$userUri = $repo->create([
'name' => 'Alice Chen',
'dob' => '1990-05-20',
'location' => 'Taipei, Taiwan'
]);
echo "Created: $userUri\n";
// Read
$user = $repo->findByName('Alice Chen');
print_r($user);
// Update
$repo->updateLocation('Alice Chen', 'Tokyo, Japan');
// Delete
$repo->deleteByName('Alice Chen');
+----------------+ +----------------+ +------------------+
| Controller |---->| Repository |---->| SPARQL Endpoint |
| (PHP Class) | | (Semantic*) | | (Fuseki/GraphDB)|
+----------------+ +----------------+ +------------------+
| |
v v
+----------------+ +----------------+
| View | | Vocabulary |
| (Twig/Blade) | | (FOAF/Schema) |
+----------------+ +----------------+
| 面向 | SQL / 關聯式 | SPARQL / RDF |
|---|---|---|
| 識別符 | 主鍵(整數/UUID) | URI(全域唯一、可解析) |
| 結構定義 | Schema(DDL、嚴格) | Ontology/RDFS/OWL(動態、可擴充) |
| 關聯表示 | 外鍵 + JOIN | 謂詞連結(圖遍歷) |
| 查詢邏輯 | 關聯代數(集合運算) | 圖模式比對(子圖同構) |
| 資料整合 | ETL、資料倉儲 | 聯邦查詢、Linked Data 原生整合 |
| 推理 | 應用層實作 | 理由器(Reasoner)自動推導 |
| 版本/來源 | 額外欄位/表 | Named Graph / Provenance 內建 |
適用語義化 Web 的場景:
繼續用 SQL 的場景:
從 SQL 到 SPARQL 不只是語法換裝,是資料觀的範式轉移:從「表格儲存」到「知識圖譜」。PHP 配合 EasyRdf、SPARQL Client 可輕鬆接入語義化 Web 生態。關鍵在於:設計良好的本體、選擇穩定的 Triple Store、封裝 Repository 隔離 SPARQL 複雜度。若專案具備「互聯、推理、演進」三大特質,語義化 Web 將帶來 SQL 難以企及的彈性與互通性。