ZVVQ代理分享网

在PHP开发中如何使用Google Cloud Firestore进行文档存

作者:zvvq博客网
导读在php开发中如何使用google cloud firestore进行文档存储和查询 随着云计算技术的不断发展,云服务已经成为了现代化应用程序开发的必要环节。Google Cloud Firestore是谷歌推出的一项基于文档

在php开发中怎么使用google cloud firestore开展文档存储和查询

随着云技术的不断进步,云服务已经成了智能化APP开发的重要阶段。Google Cloud Firestore是谷歌推出的一项根据文档的NoSQL数据库服务,带来了实时数据库、离线数据同歩、强一致性、自动化拓展、全球布署等优秀特点。本文将主要介绍怎样在PHP工程中应用Google Cloud Firestore开展文档存储和查询。

流程1:建立Google Cloud Firestore项目

最先需要登录你的Google Cloud账号,并在Google CloudConsole中创建一个新的项目。在项目中开启Firestore菜单栏,创建一个新的Cloud Firestore数据库,可以考虑测试模式或生产方式。测试模式容许所有人都可以浏览您的数据库,而生产方式要进行身份认证和授权才能进行浏览。记录下这时产生的项目ID。

流程2:安装Google Cloud FirestoreSDK

在PHP工程中应用Google Cloud Firestore必须安装Google Cloud FirestoreSDK。在终端中应用composer指令来进行施工:

composerrequiregoogle/cloud-firestore

流程3:配备Google Cloud FirestoreSDK

在编码中加入下列编码来配置Google Cloud FirestoreSDK,需要把下文中的“your_project_id”替换为流程1中产生的项目ID:

php

useGoogleCloudFirestoreFirestoreClient;

$firestore=newFirestoreClient([

projectId=>your_project_id,

]);

流程4:存放文档

下面就可以用FirestoreClient对象进行文档的存储和查询了。以下是在PHP工程中应用FirestoreClient对象存储一个文档的实例编码:

php

useGoogleCloudFirestoreFirestoreClient;

$firestore=newFirestoreClient([

projectId=>your_project_id,

]);

$docRef=$firestore->collection(users)->document(alovelace);

$docRef->set([

first=>Ada,

last=>Lovelace,

born=>1815

]);

在相关代码中,我们先创建了一个FirestoreClient目标,并指定了项目ID。随后创建了一个users结合,并在其中建立了一个名为“alovelace”的文档,并设置了其属性值。其中,“first”代表名称,“last”代表姓式,“born”代表出世日期。存放结束后,Firestore会自动生成一个唯一的文档ID。

流程5:查看文档

可以用get()方式查找文档。以下是在PHP工程中应用FirestoreClient目标查看一个文档的实例编码:

php

useGoogleCloudFirestoreFirestoreClient;

$firestore=newFirestoreClient([

projectId=>your_project_id,

]);

$docRef=$firestore->collection(users)->document(alovelace);

$snapshot=$docRef->snapshot();

if($snapshot->exists()){

printf(User%swasbornin%d,$snapshot[first],$snapshot[born]);

}else{

printf(Document%sdoesnotexist!,$docRef->name());

}

在相关代码中,我们先获得了名叫“alovelace”的文档,并通过snapshot()方式获得文档快照。假如文档存有,则导出“User”的名字和出世日期,不然导出文档不存在的消息提示。

流程6:更新和删除文档

可以用update()方式升级文档。以下是在PHP工程中应用FirestoreClient目标升级一个文档的实例编码:

php

useGoogleCloudFirestoreFirestoreClient;

$firestore=newFirestoreClient([

projectId=>your_project_id,

]);

$docRef=$firestore->collection(users)->document(alovelace);

$docRef->update([

[path=>first,value=>AdaKing],

[path=>born,value=>1816]

]);

在相关代码中,我们先获得了名叫“alovelace”的文档,并通过update()方式升级了名字和出世日期。

可以用delete()方式删除文档。以下是在PHP工程中应用FirestoreClient目标删掉一个文档的实例编码:

php

useGoogleCloudFirestoreFirestoreClient;

$firestore=newFirestoreClient([

projectId=>your_project_id,

]);

$docRef=$firestore->collection(users)->document(alovelace);

$docRef->delete();

在相关代码中,大家在名叫“alovelace”的文档上调用了delete()方式来删除文档。

结果

Google Cloud Firestore是谷歌推出的一项根据文档的NoSQL数据库服务,带来了实时数据库、离线数据同歩、强一致性、自动化拓展、全球布署等优秀特点。在PHP工程中应用FirestoreClient目标能够快速存储和查看文档,而且可以方便地更新和删除文档。把握Google Cloud Firestore的应用能提高PHP开发者的开发效率。

以上就是在PHP开发中怎么使用Google Cloud Firestore开展文档存储和查询的详细内容,大量请关注其他类似文章!