aacassandra / mesosfer-php-sdk
Mesosfer PHP SDK
Requires
- php: >= 7.1
- ext-curl: *
- ext-json: *
Requires (Dev)
- jms/serializer: 1.7.1
- phpdocumentor/phpdocumentor: ~2.9
- phpunit/phpunit: ^7
- squizlabs/php_codesniffer: ^3.0.1
- dev-master
- 1.1.3
- 1.1.2
- 1.0.1
- 1.0.0
- dev-dependabot/npm_and_yarn/qs-6.5.3
- dev-dependabot/npm_and_yarn/moment-2.29.4
- dev-dependabot/npm_and_yarn/protobufjs-6.11.3
- dev-dependabot/npm_and_yarn/ajv-6.12.6
- dev-dependabot/npm_and_yarn/node-fetch-2.6.7
- dev-dependabot/npm_and_yarn/aws-sdk-2.1030.0
- dev-dependabot/npm_and_yarn/object-path-0.11.8
- dev-dependabot/npm_and_yarn/tar-4.4.19
- dev-dependabot/npm_and_yarn/lodash-4.17.21
- dev-dependabot/npm_and_yarn/bson-1.1.6
- dev-dependabot/npm_and_yarn/ini-1.3.7
- dev-dependabot/npm_and_yarn/decompress-4.2.1
- dev-dependabot/npm_and_yarn/https-proxy-agent-2.2.4
This package is auto-updated.
Last update: 2024-09-10 07:02:08 UTC
README
Parse PHP SDK
Parse PHP SDK 允许您从您的 PHP 应用程序或脚本中访问强大的 Parse Server 后端。
有关 Parse 及其功能的更多信息,请参阅网站、PHP 指南或API 参考。
请注意,本文档包含最新更改,这些更改可能尚未发布。要查看您发布版本的 README,请使用以下列表。
目录
安装
安装和使用此 SDK 有多种方法。我们将在下面详细介绍一些。请注意,Parse PHP SDK 需要 PHP 5.4 或更高版本。它还可以在 HHVM 上运行(建议 3.0 或更高版本)。
使用 Composer 安装
获取 Composer,PHP 软件包管理器。然后在您的项目根目录中创建一个 composer.json 文件,包含
{ "require": { "parse/php-sdk" : "1.5.*" } }
运行 "composer install",以下载 SDK 并设置自动加载器,然后从您的 PHP 脚本中引用它
require 'vendor/autoload.php';
使用 Git 安装
您可以使用您喜欢的 GitHub 客户端克隆此 SDK,或通过终端。
git clone https://github.com/parse-community/parse-php-sdk.git
然后,您可以将 autoload.php
文件包含在您的代码中,以自动加载 Parse SDK 类。
require 'autoload.php';
使用其他方法安装
如果您使用除 Git 方法之外的其他方式下载了此 SDK,您可以将其视为使用上面的 Git 方法。一旦安装,您只需引用 autoload.php
即可访问 SDK。
设置
一旦您有权访问 SDK,您需要将其设置好才能开始使用 parse-server。
初始化
在包含 SDK 中所需的文件之后,您需要使用您的 Parse API 密钥初始化 ParseClient
ParseClient::initialize( $app_id, $rest_key, $master_key );
如果您的服务器不使用或不需要 REST 密钥,您可以按如下方式初始化 ParseClient,安全地省略 REST 密钥
ParseClient::initialize( $app_id, null, $master_key );
服务器 URL
在初始化 SDK 之后,您应该设置服务器 URL。
// Users of Parse Server will need to point ParseClient at their remote URL and Mount Point: ParseClient::setServerURL('https://my-parse-server.com:port','parse');
注意,Parse 服务器默认端口为 1337
,第二个参数 parse
是您 parse 服务器的路由前缀。
例如,如果您的 parse 服务器的 URL 为 http://example.com:1337/parse
,则可以使用以下代码片段设置服务器 URL
ParseClient::setServerURL('https://example.com:1337','parse');
服务器健康检查
为了验证您提供的服务器 URL 和挂载路径是否正确,您可以在您的服务器上运行健康检查。
$health = ParseClient::getServerHealth(); if($health['status'] === 200) { // everything looks good! }
如果您想进一步分析,健康响应可能如下所示。
{ "status" : 200, "response" : { "status" : "ok" } }
“状态”指的是HTTP响应码,“响应”包含服务器返回的信息。回复中任何额外的详细信息都可以在“响应”部分找到,您可以在发送请求之前使用它们来检查和确定parse-server的可用性。
请注意,“响应”不一定是一个可解析的JSON数组。如果响应无法解码,它将作为字符串返回。
一些不良健康响应的例子可能包括错误的挂载路径、端口或域名。
// ParseClient::setServerURL('https://:1337', 'not-good'); { "status": 404, "response": "<!DOCTYPE html>...Cannot GET \/not-good\/health..." } // ParseClient::setServerURL('http://__uh__oh__.com', 'parse'); { "status": 0, "error": 6, "error_message": "Couldn't resolve host '__uh__oh__.com'" }
请注意,error
和 error_message
可能会根据您是否使用 curl(可能因curl版本而异)或 stream 客户端而变化。
HTTP 客户端
此SDK可以在您的方便之处更改底层的HTTP客户端。默认情况下,如果没有设置,将使用curl HTTP客户端,也可以使用stream HTTP客户端。
设置HTTP客户端可以这样做
// set curl http client (default if none set) ParseClient::setHttpClient(new ParseCurlHttpClient()); // set stream http client // ** requires 'allow_url_fopen' to be enabled in php.ini ** ParseClient::setHttpClient(new ParseStreamHttpClient());
如果您需要额外的HTTP客户端,您可以通过打开问题或提交PR来请求。
如果您想自己构建一个,请确保您的HTTP客户端实现了ParseHttpable
,以便与SDK兼容。一旦您有一个可以增强SDK功能的正常工作的HTTP客户端,请随时将其提交为PR,以便我们可以考虑将其添加进去。
备用CA文件
您的本地设置可能无法通过SSL/TLS与对等方进行验证。这种情况尤其可能发生在您无法控制本地安装的情况下,例如共享主机。
如果是这种情况,您可能需要指定一个证书颁发机构捆绑包。您可以从http://curl.haxx.se/ca/cacert.pem下载这样一个捆绑包用于此目的。这个捆绑包是一个Mozilla CA证书存储,您不一定要使用这个,但建议这样做。
一旦您有了您的捆绑包,您可以按照以下方式设置它
// ** Use an Absolute path for your file! ** // holds one or more certificates to verify the peer with ParseClient::setCAFile(__DIR__ . '/certs/cacert.pem');
入门
我们强烈建议您首先阅读指南。这将引导您了解使用此SDK的基本知识,以及如何最好地开发您的项目。
如果您想了解更多关于PHP SDK的工作原理,您可以阅读我们的API参考,并在github上查看代码。
查看Parse PHP指南以获取完整文档。
使用声明
将“use”声明放在您将使用类的地方。对于此文件中的所有示例代码
use Parse\ParseObject; use Parse\ParseQuery; use Parse\ParseACL; use Parse\ParsePush; use Parse\ParseUser; use Parse\ParseInstallation; use Parse\ParseException; use Parse\ParseAnalytics; use Parse\ParseFile; use Parse\ParseCloud; use Parse\ParseClient; use Parse\ParsePushStatus; use Parse\ParseServerInfo; use Parse\ParseLogs; use Parse\ParseAudience;
Parse 对象
Parse对象存储您的数据,可以保存、查询、序列化等!对象是此SDK的核心,它们允许您在不担心任何数据库代码的情况下从PHP中持久化数据。
$object = ParseObject::create("TestObject"); $objectId = $object->getObjectId(); $php = $object->get("elephant"); // Set values: $object->set("elephant", "php"); $object->set("today", new DateTime()); $object->setArray("mylist", [1, 2, 3]); $object->setAssociativeArray( "languageTypes", array("php" => "awesome", "ruby" => "wtf") ); // Save normally: $object->save(); // Or pass true to use the master key to override ACLs when saving: $object->save(true); // encode an object for later use $encoded = $object->encode(); // decode an object $decodedObject = ParseObject::decode($encoded);
用户
用户是一种特殊类型的对象。此类允许个人使用他们的独特信息访问您的应用程序,并允许您对他们进行明确区分。用户还可以与第三方账户(如facebook、twitter等)关联。
// Signup $user = new ParseUser(); $user->setUsername("foo"); $user->setPassword("Q2w#4!o)df"); try { $user->signUp(); } catch (ParseException $ex) { // error in $ex->getMessage(); } // Login try { $user = ParseUser::logIn("foo", "Q2w#4!o)df"); } catch(ParseException $ex) { // error in $ex->getMessage(); } // Current user $user = ParseUser::getCurrentUser();
会话 ID 和会话固定
为了防止会话固定漏洞,PHP SDK将在会话权限提升时调用session_regenerate_id()
(自1.5.0版以来)(这意味着当会话从无用户变为匿名用户或从无用户/匿名用户变为注册用户时,将调用session_regenerate_id()
)。
更改PHP会话ID不会对会话内容产生影响,并且匿名用户注册后状态应保持不变。
验证电子邮件
如果您在使用Parse服务器设置中启用了电子邮件验证,您可以手动请求发送验证电子邮件。
ParseUser::requestVerificationEmail('email@example.com');
请注意,只有当请求的电子邮件账户尚未经过验证时,才会发送。
访问控制列表(ACL)
访问控制列表(ACL)允许您精细控制对单个Parse对象的访问。ACL允许您配置对公众、角色和单个用户的访问。
// Access only by the ParseUser in $user $userACL = ParseACL::createACLWithUser($user); // Access only by master key $restrictedACL = new ParseACL(); // Set individual access rights $acl = new ParseACL(); $acl->setPublicReadAccess(true); $acl->setPublicWriteAccess(false); $acl->setUserWriteAccess($user, true); $acl->setRoleWriteAccessWithName("PHPFans", true);
查询
查询允许您回忆保存到parse-server中的对象。查询方法和参数允许您对对象进行不同程度的查询,从类中的所有对象到特定日期范围内的对象等。
$query = new ParseQuery("TestObject"); // Get a specific object: $object = $query->get("anObjectId"); $query->limit(10); // default 100, max 1000 // All results, normally: $results = $query->find(); // Or pass true to use the master key to override ACLs when querying: $results = $query->find(true); // Just the first result: $first = $query->first(); // Process ALL (without limit) results with "each". // Will throw if sort, skip, or limit is used. $query->each(function($obj) { echo $obj->getObjectId(); });
聚合
您可以使用聚合进行查询,以便从一组输入值中检索对象。请注意,在parse-server中不存在_id
。请将其替换为objectId
。需要MasterKey。
有关可用运算符的列表,请参阅Mongo聚合文档。
// group pipeline is similar to distinct, can apply $sum, $avg, $max, $min // accumulate sum and store in total field $pipeline = [ 'group' => [ 'objectId' => null, 'total' => [ '$sum' => '$score'] ] ]; $results = $query->aggregate($pipeline); // project pipeline is similar to keys, add or remove existing fields // includes name key $pipeline = [ 'project' => [ 'name' => 1 ] ]; $results = $query->aggregate($pipeline); // match pipeline is similar to equalTo // filter out objects with score greater than 15 $pipeline = [ 'match' => [ 'score' => [ '$gt' => 15 ] ] ]; $results = $query->aggregate($pipeline);
不同
您可以使用distinct进行查询,以便为指定字段找到唯一值。请注意,需要MasterKey。
// finds score that are unique $results = $query->distinct('score'); // can be used with equalTo $query = new ParseQuery('TestObject'); $query->equalTo('name', 'foo'); $results = $query->distinct('score');
相对时间
您可以使用相对时间进行查询,以便检索不同范围的相对日期的对象。请注意,所有相对查询都使用服务器的时间和时区执行。
// greater than 2 weeks ago $query->greaterThanRelativeTime('createdAt', '2 weeks ago'); // less than 1 day in the future $query->lessThanRelativeTime('updatedAt', 'in 1 day'); // can make queries to very specific points in time $query->greaterThanOrEqualToRelativeTime('createdAt', '1 year 2 weeks 30 days 2 hours 5 minutes 10 seconds ago'); // can make queries based on right now // gets everything updated up to this point in time $query->lessThanOrEqualToRelativeTime('updatedAt', 'now'); // shorthand keywords work as well $query->greaterThanRelativeTime('date', '1 yr 2 wks 30 d 2 hrs 5 mins 10 secs ago');
云函数
直接调用服务器端云函数并获取其结果。
$results = ParseCloud::run("aCloudFunction", array("from" => "php"));
云作业
与云函数类似,云作业允许您在服务器端异步运行代码。您不必等待执行完成,而是立即返回一个用于跟踪作业进度的ID。您可以使用此ID查看作业的当前信息以及它是否已完成。
// start job $jobStatusId = ParseCloud::startJob('MyCloudJob', array("startedBy" => "me!")); // get job status, a ParseObject! $jobStatus = ParseCloud::getJobStatus($jobStatusId); $status = $jobStatus->get('status'); // failed / succeeded when done
配置
ParseConfig 允许您访问Parse服务器设置的全球 Config 对象。您可以像在 ParseObject 实例上那样获取、设置和更新简单值。通过这种方式,所有您的SDK和应用程序都可以访问全局设置、选项等。您选择将什么放入配置完全取决于您。
$config = new ParseConfig(); // check a config value of yours $allowed = $config->get('feature_allowed'); // add a simple config value $config->set('feature_allowed', true); // save this global config $config->save();
分析
专门构建的Parse对象,旨在简化分析。
ParseAnalytics::track("logoReaction", array( "saw" => "elephant", "said" => "cute" ));
文件
将文件持久保存到parse-server,并在方便的时候检索它们。根据您的服务器设置,有多种存储选项,包括mongodb、Amazon S3和Google Cloud Storage。您可以在此处了解更多信息这里。
// Get from a Parse Object: $file = $aParseObject->get("aFileColumn"); $name = $file->getName(); $url = $file->getURL(); // Download the contents: $contents = $file->getData(); // Upload from a local file: $file = ParseFile::createFromFile( "/tmp/foo.bar", "Parse.txt", "text/plain" ); // Upload from variable contents (string, binary) $file = ParseFile::createFromData($contents, "Parse.txt", "text/plain");
推送
您可以使用此SDK构建和发送推送通知。您可以向预定义的设备频道发送推送,或使用 ParseQuery
的力量向自定义设备集发送。
为了使用推送,您必须首先在您的parse服务器实例中配置一个有效的推送配置。
推送到频道
您可以向为您的用户创建的任何频道发送推送通知。
$data = array("alert" => "Hi!"); // Parse Server has a few requirements: // - The master key is required for sending pushes, pass true as the second parameter // - You must set your recipients by using 'channels' or 'where', but you must not pass both // Push to Channels ParsePush::send(array( "channels" => ["PHPFans"], "data" => $data ), true);
使用查询推送
您还可以使用针对 ParseInstallation
类的查询来推送设备。
// Push to Query $query = ParseInstallation::query(); $query->equalTo("design", "rad"); ParsePush::send(array( "where" => $query, "data" => $data ), true);
使用受众推送
如果您想在使用查询时跟踪您的发送,可以使用 ParseAudience
类。您可以使用名称和查询创建和配置您的受众对象。当您表示它在推送中使用时,lastUsed
和 timesUsed
值会为您更新。
$iosQuery = ParseInstallation::getQuery(); $iosQuery->equalTo("deviceType", "ios"); // create & save your audience $audience = ParseAudience::createAudience( 'MyiOSAudience', $iosQuery ); $audience->save(true); // send a push using the query in this audience and it's id // The 'audience_id' is what allows parse to update 'lastUsed' and 'timesUsed' // You could use any audience_id with any query and it will still update that audience ParsePush::send([ 'data' => [ 'alert' => 'hello ios users!' ], 'where' => $audience->getQuery(), 'audience_id' => $audience->getObjectId() ], true); // fetch changes to this audience $audience->fetch(true); // get last & times used for tracking $timesUsed = $audience->getTimesUsed(); $lastUsed = $audience->getLastUsed();
受众为您提供了方便地分组查询和跟踪您向它们发送的频率和时间的途径。
推送状态
如果您的服务器支持,您可以提取和检查推送的当前状态。这允许您实时监控推送的成功。
// Get Push Status $response = ParsePush::send(array( "channels" => ["StatusFans"], "data" => $data ), true); if(ParsePush::hasStatus($response)) { // Retrieve PushStatus object $pushStatus = ParsePush::getStatus($response); // check push status if($pushStatus->isPending()) { // handle a pending push request } else if($pushStatus->isRunning()) { // handle a running push request } else if($pushStatus->hasSucceeded()) { // handle a successful push request } else if($pushStatus->hasFailed()) { // handle a failed request } // ...or get the push status string to check yourself $status = $pushStatus->getPushStatus(); // get # pushes sent $sent = $pushStatus->getPushesSent(); // get # pushes failed $failed = $pushStatus->getPushesFailed(); }
服务器信息
任何版本 2.1.4 或更高版本的服务器都支持访问有关自身及其功能的详细信息。您可以使用 ParseServerInfo
检查您服务器上的功能和版本。
版本
获取您连接的服务器的当前版本。
// get the current version of the server you are connected to (2.6.5, 2.5.4, etc.) $version = ParseServerInfo::getVersion();
功能
检查您的服务器具有哪些功能以及它们的配置方式。
// get the current version of the server you are connected to (2.6.5, 2.5.4, etc.) $version = ParseServerInfo::getVersion(); // get various features $globalConfigFeatures = ParseServerInfo::getGlobalConfigFeatures(); /** * Returns json of the related features * { * "create" : true, * "read" : true, * "update" : true, * "delete" : true * } */ // you can always get all feature data $data = ParseServerInfo::getFeatures();
您还可以获取以下功能的详细信息
ParseServerInfo::getHooksFeatures(); ParseServerInfo::getCloudCodeFeatures(); ParseServerInfo::getLogsFeatures(); ParseServerInfo::getPushFeatures(); ParseServerInfo::getSchemasFeatures(); // additional features can be obtained manually using 'get' $feature = ParseServerInfo::get('new-feature');
模式
通过 ParseSchema
可以直接操作您服务器上的类。尽管字段和类可以自动生成(假设启用了客户端类创建),但 ParseSchema
让您可以明确控制这些类及其字段。
// create an instance to manage your class $mySchema = new ParseSchema("MyClass"); // gets the current schema data as an associative array, for inspection $data = $mySchema->get(); // add any # of fields, without having to create any objects $mySchema->addString('string_field'); $mySchema->addNumber('num_field'); $mySchema->addBoolean('bool_field'); $mySchema->addDate('date_field'); $mySchema->addFile('file_field'); $mySchema->addGeoPoint('geopoint_field'); $mySchema->addPolygon('polygon_field'); $mySchema->addArray('array_field'); $mySchema->addObject('obj_field'); $mySchema->addPointer('pointer_field'); // you can even setup pointer/relation fields this way $mySchema->addPointer('pointer_field', 'TargetClass'); $mySchema->addRelation('relation_field', 'TargetClass'); // new types can be added as they are available $mySchema->addField('new_field', 'ANewDataType'); // save/update this schema to persist your field changes $mySchema->save(); // or $mySchema->update();
假设您想删除一个字段,可以简单地调用 deleteField
和 save/update
来清除它。
$mySchema->deleteField('string_field'); $mySchema->save(): // or for an existing schema... $mySchema->update():
可以通过 delete
删除架构,但必须先清空它。
$mySchema->delete();
索引
索引支持数据库查询的高效执行。需要 MasterKey。
// To add an index, the field must exist before you create an index $schema->addString('field'); $index = [ 'field' => 1 ]; $schema->addIndex('index_name', $index); $schema->save(); // Delete an index $schema->deleteIndex('index_name'); $schema->save(); // If indexes exist, you can retrieve them $result = $schema->get(); $indexes = $result['indexes'];
清除
可以通过 purge
从架构(类)中清除所有对象。但请注意!这可以被视为不可逆的操作。只有在您 真的 需要从类中删除所有对象时才这样做,例如在您需要删除类时(如上面的代码示例所示)。
// delete all objects in the schema $mySchema->purge();
日志
ParseLogs
允许以 JSON 格式从服务器检索信息和错误日志。使用与 仪表板 中使用的相同方法,您可以在特定的时间、类型和顺序范围内查看日志。请注意,这需要在初始化时设置正确的 masterKey 才能访问。
// get last 100 info logs, sorted in descending order $logs = ParseLogs::getInfoLogs(); // get last 100 info logs, sorted in descending order $logs = ParseLogs::getErrorLogs(); // logs can be retrieved with further specificity // get 10 logs from a date up to a date in ascending order $logs = ParseLogs::getInfoLogs(10, $fromDate, $untilDate, 'asc'); // above can be done for 'getErrorLogs' as well
贡献/测试
有关测试和为 Parse PHP SDK 贡献的信息,请参阅 CONTRIBUTING。我们欢迎修复和增强。
截至 2017 年 4 月 5 日,Parse, LLC 已将此代码转移到 parse-community 组织,并将不再为此代码做出贡献或分发。