parse / php-sdk
Parse PHP SDK
资助包维护!
parse-community
Open Collective
Requires
- php: >=8.1 <8.4
- ext-curl: *
- ext-json: *
Requires (Dev)
- jms/serializer: 1.7.1
- nikic/php-parser: 4.15
- phpdocumentor/phpdocumentor: 3.0.0
- phpunit/phpunit: 10.1.1
- squizlabs/php_codesniffer: 3.7.2
This package is auto-updated.
Last update: 2024-08-27 23:29:21 UTC
README
一个库,让您可以从PHP应用程序访问强大的Parse Server后端。有关Parse及其功能的更多信息,请参阅网站、PHP指南、Cloud Code指南或API参考。
目录
兼容性
Parse PHP SDK会不断使用最新的PHP版本进行测试,以确保兼容性。我们遵循PHP长期支持计划,并且只针对官方支持且未达到生命终结日期的版本进行测试。
安装
有各种安装和使用此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('http://localhost: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'" }
请注意,根据您是否使用curl
(版本可能不同)或stream
客户端,error
和error_message
可能会变化。
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兼容。一旦您有一个可工作的HTTP客户端,增强了SDK,您可以自由地将其提交为PR,以便我们考虑将其添加进来。
备用CA文件
您的本地设置可能无法通过SSL/TLS与对等方进行验证。这可能是如果您没有控制您的本地安装,例如对于共享主机的情况。
如果是这种情况,您可能需要指定证书颁发机构捆绑包。您可以从这里下载这样的捆绑包用于此目的。这个捆绑包恰好是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 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();
索引
索引支持数据库查询的高效执行。需要主密钥。
// 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。使用与在 仪表板 中使用的方法相同的策略,您可以查看具有特定时间范围、类型和顺序的日志。请注意,这需要在初始化时设置正确的主密钥才能访问。
// 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 组织,并将不再为此代码做出贡献或进行分发。