Git Product home page Git Product logo

php-sdk's Introduction

LeanCloud PHP SDK

Build Status Latest Version Coverage Status

LeanCloud 为应用提供了从数据存储,消息推送,实时通信到离线分析等全方位 的一站式云端服务,帮助应用开发者降低后端开发及维护成本,为应用开发加速。 PHP SDK 提供了对数据存储,用户管理等模块的 PHP 实现及接口,以方便 PHP 应用的开发。

安装

运行环境要求 PHP 5.6 及以上版本,以及 cURL

composer 安装

如果使用标准的包管理器 composer,你可以很容易的在项目中添加依赖并下载:

composer require leancloud/leancloud-sdk

手动下载安装

你也可以前往发布页面 手动下载安装包。假设你的应用位于 $APP_ROOT 目录下:

cd $APP_ROOT
wget https://github.com/leancloud/php-sdk/archive/vX.X.X.zip

# 解压并置于 vendor 目录
unzip vX.X.X.zip
mv php-sdk-X.X.X vendor/leancloud

初始化

完成上述安装后,需要对 SDK 初始化。如果已经创建应用,可以在 LeanCloud [控制台 > 应用设置]里找到应用的 ID 和 key。然后在项目中加载 SDK, 并初始化:

// 如果是 composer 安装
// require_once("vendor/autoload.php");

// 如果是手动安装
require_once("vendor/leancloud/src/autoload.php");

// 参数依次为 app-id, app-key, master-key
LeanCloud\Client::initialize("app_id", "app_key", "master_key");

使用示例

用户注册及管理

注册一个用户:

use LeanCloud\User;
use LeanCloud\CloudException;

$user = new User();
$user->setUsername("alice");
$user->setEmail("[email protected]");
$user->setPassword("passpass");
try {
    $user->signUp();
} catch (CloudException $ex) {
    // 如果 LeanCloud 返回错误,这里会抛出异常 CloudException
    // 如用户名已经被注册:202 Username has been taken
}

// 注册成功后,用户被自动登录。可以通过以下方法拿到当前登录用户和
// 授权码。
User::getCurrentUser();
User::getCurrentSessionToken();

登录一个用户:

User::logIn("alice", "passpass");
$user = User::getCurrentUser();
$token = User::getCurrentSessionToken();

// 给定一个 token 可以很容易的拿到用户
User::become($token);

// 我们还支持短信验证码,及第三方授权码登录
User::logInWithSmsCode("phone number", "sms code");
User::logInWith("weibo", array("openid" => "..."));

对象存储

use LeanCloud\LeanObject;
use LeanCloud\CloudException;

$obj = new LeanObject("TestObject");
$obj->set("name", "alice");
$obj->set("height", 60.0);
$obj->set("weight", 4.5);
$obj->set("birthdate", new \DateTime());
try {
    $obj->save();
} catch (CloudException $ex) {
    // CloudException 会被抛出,如果保存失败
}

// 获取字段值
$obj->get("name");
$obj->get("height");
$obj->get("birthdate");

// 原子增加一个数
$obj->increment("age", 1);

// 在数组字段中添加,添加唯一,删除
// 注意: 由于API限制,不同数组操作之间必须保存,否则会报错
$obj->addIn("colors", "blue");
$obj->save();
$obj->addUniqueIn("colors", "orange");
$obj->save();
$obj->removeIn("colors", "blue");
$obj->save();

// 在云存储上删除数据
$obj->destroy();

我们同样支持子类继承,子类中需要定义静态变量 $className ,并注册到存储类:

class TestObject extends LeanObject {
    protected static $className = "TestObject";
    public setName($name) {
        $this->set("name", $name);
        return $this;
    }
}
// register it as storage class
TestObject::registerClass();

$obj = new TestObject();
$obj->setName();
$obj->set("eyeColor", "blue");
...

对象查询

给定一个 objectId,可以如下获取对象。

use LeanCloud\Query;

$query = new Query("TestObject");
$obj = $query->get($objectId);

更为复杂的条件查询:

$query = new Query("TestObject");
$query->lessThan("height", 100.0);           // 小于
$query->greaterThanOrEqualTo("weight", 5.0); // 大于等于
$query->addAscend("birthdate");              // 递增排序
$query->addDescend("name");                  // 递减排序
$query->count();
$query->first(); // 返回第一个对象

$query->skip(100);
$query->limit(20);
$objects = $query->find(); // 返回查询到的对象

文件存储

直接创建文件:

use LeanCloud\File;
$file = File::createWithData("hello.txt", "Hello LeanCloud!");
try {
    $file->save();
} catch (CloudException $ex) {
    // 云存储返回错误,保存失败
}

$file->getSize();
$file->getName();
$file->getUrl();

由本地文件创建:

$file = File::createWithLocalFile("/tmp/myfile.png");
try {
    $file->save();
} catch (CloudException $ex) {
    // 云存储返回错误,保存失败
}

// 获取文件缩略图的链接
$url = $file->getThumbUrl();

由已知的 URL 创建文件:

$file = File::createWithUrl("image.png", "http://example.net/image.png");
try {
    $file->save();
} catch (CloudException $ex) {
    // 云存储返回错误,保存失败
}

更多文档请参考 PHP 数据存储开发指南

贡献

See Hacking.md if you'd like to contribute.

php-sdk's People

Contributors

dependabot[bot] avatar juvenn avatar jwfing avatar jysperm avatar weakish avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-sdk's Issues

处理 Hook 请求时校验签名

需要校验的请求:

签名算法见 https://github.com/leancloud/uluru-platform/issues/2242
Node SDK 相关 PR leancloud/leanengine-node-sdk#73
请先等待命令行工具的支持发布(否则就无法在本地调试 Hook 了,预计这两天就发布) leancloud/avoscloud-code-command#150
需要等待实时通讯后端的修改上线 https://github.com/leancloud/avoscloud-push/issues/903

Undefined index: token

US 上传文件发生错误

PHP Notice 'yii\base\ErrorException' with message 'Undefined index: token'

in /Users/aaaaa/Sites/CC/vendor/leancloud/leancloud-sdk/src/LeanCloud/LeanFile.php:372

Stack trace:
#0 /Users/aaaaa/Sites/CC/vendor/leancloud/leancloud-sdk/src/LeanCloud/LeanFile.php(372): yii\base\ErrorHandler->handleError(8, 'Undefined index...', '/Users/aaaaa/S...', 372, Array)
#1 /Users/aaaaa/Sites/CC/console/controllers/UkRadioController.php(184): LeanCloud\LeanFile->save()
#2 [internal function]: console\controllers\UkRadioController->actionIntoCloud()
#3 /Users/aaaaa/Sites/CC/vendor/yiisoft/yii2/base/InlineAction.php(55): call_user_func_array(Array, Array)
#4 /Users/aaaaa/Sites/CC/vendor/yiisoft/yii2/base/Controller.php(154): yii\base\InlineAction->runWithParams(Array)
#5 /Users/aaaaa/Sites/CC/vendor/yiisoft/yii2/console/Controller.php(119): yii\base\Controller->runAction('into-cloud', Array)
#6 /Users/aaaaa/Sites/CC/vendor/yiisoft/yii2/base/Module.php(454): yii\console\Controller->runAction('into-cloud', Array)
#7 /Users/aaaaa/Sites/CC/vendor/yiisoft/yii2/console/Application.php(176): yii\base\Module->runAction('uk-radio/into-c...', Array)
#8 /Users/aaaaa/Sites/CC/vendor/yiisoft/yii2/console/Application.php(143): yii\console\Application->runAction('uk-radio/into-c...', Array)
#9 /Users/aaaaa/Sites/CC/vendor/yiisoft/yii2/base/Application.php(375): yii\console\Application->handleRequest(Object(yii\console\Request))
#10 /Users/aaaaa/Sites/CC/yii(27): yii\base\Application->run()

Details: error:14090086:SSL routines

Fatal error: Uncaught exception 'RuntimeException' with message 'CURL connection (https://us-api.leancloud.cn/1.1/date) error: 60 SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed' in C:\xampp\htdocs\aaa\vendor\leancloud\src\LeanCloud\LeanClient.php:362 Stack trace: #0 C:\xampp\htdocs\aaa\vendor\leancloud\src\LeanCloud\LeanClient.php(392): LeanCloud\LeanClient::request('GET', '/date', NULL, NULL, Array, NULL) #1 C:\D\xampp\htdocs\aaa\index.php(9): LeanCloud\LeanClient::get('/date') #2 {main} thrown in C:\xampp\htdocs\aaa\vendor\leancloud\src\LeanCloud\LeanClient.php on line 362

$obj->save(); 报错 batchSave

代码是这样的
$obj = new LeanObject("TestObject");
$obj->set("name", "alice4");
$obj->set("height", 60.0);
$obj->set("weight", 4.5);
$obj->set("birthdate", new \DateTime());
try {
$obj->save();
} catch (CloudException $ex) {
// CloudException 会被抛出,如果保存失败
print_r($ex);
}
错误信息
"code":401,"error":"Unauthorized."
LeanCloud\LeanObject.php
function: batchSave
line: 631
class: LeanCloud\LeanObject
请问这是神马情况?

不支持创建无数据的新对象

背景

先获取 objectId,以后再指定 objectId 保存数据的场景,需要先创建出空对象

问题

但目前如下操作都无法成功

$lcObject = new LeanObject("className");
$lcObject->save();

或者

$lcObject = LeanObject:: create("className");
$lcObject->save();

原因

    public function save() {
        if (!$this->isDirty()) {return;}
        return self::saveAll(array($this));
    }

    public function isDirty() {
        // TODO: check children too?
        return !empty($this->_operationSet);
    }

而以上场景 _operationSet 为空

期待

支持创建无数据的新对象,否则用户只能增加一个无意义的占位字段进行新对象的创建

LeanPush 同时向 ios/andorid 推送消息

根据 Rest API 文档,data 应使用以下结构

    "data":{
      "ios": {
        "alert":             "消息内容",
        "badge":             "未读消息数目,应用图标边上的小红点数字,可以是数字,也可以设置为 Increment 这个字符串(大小写敏感)",
        "sound":             "声音文件名,前提在应用里存在",
        "content-available": "如果你在使用 Newsstand, 设置为 1 来开始一次后台下载"
      },
      "android": {
        "alert":             "消息内容",
        "title":             "显示在通知栏的标题",
        "action":            "com.your_company.push",
        "fromUserId":        "自定义属性"
      },
      "wp":{
        "alert":             "消息内容",
        "title":             "显示在通知栏的标题",
        "wp-param":          "/chat.xaml?NavigatedFrom=Toast Notification"
      }
    }

但是代码中检测 data 下必须存在 alert,无法使用以上结构

    public function encode() {
        // ★这里★
        if (!isset($this->data["alert"])) {
            throw new \RuntimeException("No `alert' message specified " .
                                        "in notification data");
        }

        $out = $this->options;
        $out["data"] = $this->data;
        if (isset($this->options["where"])) {
            $query = $this->options["where"]->encode();
            $out["where"] = json_decode($query["where"], true);
        }
        return $out;
    }

    public function send() {
        $out  = $this->encode();
        $resp = LeanClient::post("/push", $out);
        return $resp;
    }

请问使用 sdk 如何同时向 ios/android 推送消息?

Windows curl 没有证书无法发送 https 请求

Fatal error: Uncaught exception 'RuntimeException' with message 'CURL connection (https://api.leancloud.cn/1.1/classes/G3Data) error: 60 60'
in C:\xampp\htdocs\crowdsensing\vendor\leancloud\leancloud-sdk\src\LeanCloud\LeanClient.php:315
Stack trace: 
#0 C:\xampp\htdocs\crowdsensing\vendor\leancloud\leancloud-sdk\src\LeanCloud\LeanClient.php(345): LeanCloud\LeanClient::request('GET', '/classes/G3Data', Array, NULL, Array, false)
#1 C:\xampp\htdocs\crowdsensing\vendor\leancloud\leancloud-sdk\src\LeanCloud\LeanQuery.php(687): LeanCloud\LeanClient::get('/classes/G3Data', Array) 
#2 C:\xampp\htdocs\crowdsensing\index.php(9): LeanCloud\LeanQuery->count()
#3 {main} thrown in C:\xampp\htdocs\crowdsensing\vendor\leancloud\leancloud-sdk\src\LeanCloud\LeanClient.php on line 315

你好 这里是什么问题?

first 取不到数据报错!

https://github.com/leancloud/php-sdk/blob/master/src/LeanCloud/LeanQuery.php#L713
可能是没有 use CloudException
场景代码

        $query = new LeanQuery('_Conversation');
        $query->equalTo('name', 'SystemMessages');
        $data = $query->first();

        if(empty($data[0])){
            //当不存在系统对话,添加一条对话
            $obj = new LeanObject('_Conversation');
            $obj->set('name', 'SystemMessages');
            $obj->set('sys', true);

            try {
                $obj->save();
                return $obj->getObjectId();
            } catch (CloudException $ex) {
                return $ex;
            }
        }

        return $data->getObjectId();

User 对象如果含有文件属性 则 getCurrentUser 会导致循环调用

而且我的apache 的端口一直在变,这是神马情况
如果设置set_time_limit(0); 的话,就一直在转也不返回信息,貌似进入了死循环似得

登录的时候用LeanUser::logIn($name, $pass);,没有报错
获取当前用户 LeanCloud\LeanUser::getCurrentUser();这个的时候,
老是出现下面的错误,有没有办法处理
Fatal error: Maximum execution time of 30 seconds exceeded in LeanCloud\LeanClient.php on line 349

First release roadmap (Oct. 2015)

Features to implement (in this release)
  • LeanObject: 对象存储
  • LeanQuery: 对象的查询,包括 $and, $or
  • LeanUser: 支持用户管理,包括第三方登录,邮箱,短信验证
  • LeanFile: 支持外部 URL 及上传到 Qiniu
  • LeanBytes: 支持二进制数据存储
  • IOperation: 支持 Set, Increment, Add, AddUnique, Remove 操作
  • LeanRelation: 支持对象关系的管理,包括添加与删除
  • CookieStorage and SessionStorage: 支持当前用户会话等临时信息的存储
  • LeanRelation: 支持建立关系的查询
Features for future release:
  • Exception needs to be carefully categorized and refactored
  • Cloud function invoke
  • GeoPoint and geo location query
  • Role and ACL
  • CQL query
  • LeanEngine deployment

快速入门的那几个例子都用不了,

LeanCloud\LeanClient::get("/date"); // 获取服务器时间 第一个就报错。

Fatal error: Uncaught exception 'RuntimeException' with message 'CURL connection (https://api.leancloud.cn/1.1/date) error: 60 60' in D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanClient.php:324 Stack trace: #0 D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanClient.php(354): LeanCloud\LeanClient::request('GET', '/date', NULL, NULL, Array, NULL) #1 D:\phpStudy\WWW\phpproject\index.php(6): LeanCloud\LeanClient::get('/date') #2 {main} thrown in D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanClient.php on line 324

然后下面的那些也报错
Fatal error: Uncaught exception 'RuntimeException' with message 'CURL connection (https://api.leancloud.cn/1.1/batch) error: 60 60' in D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanClient.php:324 Stack trace: #0 D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanClient.php(371): LeanCloud\LeanClient::request('POST', '/batch', Array, NULL, Array, NULL) #1 D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanClient.php(423): LeanCloud\LeanClient::post('/batch', Array, NULL, Array, NULL) #2 D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanObject.php(644): LeanCloud\LeanClient::batch(Array, NULL) #3 D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanObject.php(595): LeanCloud\LeanObject::batchSave(Array) #4 D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanObject.php(357): LeanCloud\LeanObject::saveAll(Array) #5 D:\phpStudy\WWW\phpproject\list.php(17): LeanCloud\LeanObject->save() #6 {main} thrown in D:\phpStudy\WWW\phpproject\Vendor\src\LeanCloud\LeanClient.php on line 324

要怎么才能读取时间呢?

判断LeanClient是否已经初始化

需要多次调用LeanClient的方法,调用前需要确保LeanClient已经初始化:LeanClient->initialize()
希望增加一个方法,判断是否已经初始化:比如: LeanClient->isInit().

另外多说一句:LeanClient更像一个实例对象,而不是一个工具类,所以static的方式不太合适;当然,重构的工作量较大 :)

类型前缀由 Lean 调整为 LC

考虑到与其它 SDK 的一致性,我们将对类型名称做以下调整:

LeanObject => LCObject

同时,发布到 packagist 的包名称由 leancloud/leancloud-sdk 调整为 leancloud/php-sdk 。

时间怎么设置时区?

$v->get('birthdate');//这个字段是日期格式的
网页显示
birthdate :object(DateTime)#6 (3) { ["date"]=> string(19) "2015-12-25 08:11:09" ["timezone_type"]=> int(2) ["timezone"]=> string(1) "Z" }

怎么查询对应时区的时间?

CURL connection (https://api.leancloud.cn/1.1/date) error: 28 28

按照你们官方提示,
运行一个简单的程序
/
public function actionLean()
{
// 参数依次为 appId, appKey, masterKey
LeanClient::initialize("VR6qospcccxxxxxxxxxxxxx6GhnJ-gzGzoHsz", "qQLD81bxxxxxxxxxU1CNflkSJgP3fG", "IeuoNdKJHhCkHCxU46PcAUnY");

// 我们目前支持 CN 和 US 区域,默认使用 CN 区域,可以切换为 US 区域
// LeanClient::useRegion("US");

     LeanClient::get("/date"); // 获取服务器时间
}

起来后提示
RuntimeException
CURL connection (https://api.leancloud.cn/1.1/date) error: 28 28
看到后面官方文档说
1.如果遇到类似「Fatal error: Uncaught exception 'RuntimeException'...CURL connection...」的系统报错,请参考 修复 CURL connection 错误。
但是也没有看到解决方法;
2.说是CRT文件处理方法,我系统是MAC,而且这个CRT文件是怎么获取的?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.