first commit

This commit is contained in:
编码猿
2024-09-27 01:06:04 +08:00
commit cbed24c40d
205 changed files with 8732 additions and 0 deletions

23
.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

1
.pydio Normal file
View File

@@ -0,0 +1 @@
48428cf7-5da5-4be3-8e54-df20de02e214

21
Swoft_BackEndApi/.editorconfig Executable file
View File

@@ -0,0 +1,21 @@
root = true
# 对所有文件生效
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
# 对后缀名为 md 的文件生效
[*.md]
trim_trailing_whitespace = false
[*.php]
indent_size = 4
[resource/views/*.php]
indent_size = 2

15
Swoft_BackEndApi/.gitignore vendored Executable file
View File

@@ -0,0 +1,15 @@
.buildpath
.settings/
.project
*.patch
.idea/
.git/
runtime/
vendor/
temp/
*.lock
.phpintel/
.env
.phpstorm.meta.php
.DS_Store
public/devtool/

1
Swoft_BackEndApi/.pydio Normal file
View File

@@ -0,0 +1 @@
5ebfb249-f9f1-4ce6-b5ff-69383bfdded7

20
Swoft_BackEndApi/.travis.yml Executable file
View File

@@ -0,0 +1,20 @@
language: php
php:
- 7.1
- 7.2
- 7.3
services:
- redis
install:
- echo 'no' | pecl install -f redis
- wget https://github.com/swoole/swoole-src/archive/v4.3.3.tar.gz -O swoole.tar.gz && mkdir -p swoole && tar -xf swoole.tar.gz -C swoole --strip-components=1 && rm swoole.tar.gz && cd swoole && phpize && ./configure && make -j$(nproc) && make install && cd -
- echo "extension = swoole.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
before_script:
- composer config -g process-timeout 900 && composer update
- phpenv config-rm xdebug.ini
script:
- composer test

201
Swoft_BackEndApi/LICENSE Executable file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

91
Swoft_BackEndApi/README.md Executable file
View File

@@ -0,0 +1,91 @@
<p align="center">
<a href="https://github.com/swoft-cloud/swoft" target="_blank">
<img src="http://qiniu.daydaygo.top/swoft-logo.png?imageView2/2/w/300" alt="swoft"/>
</a>
</p>
[![Latest Version](https://img.shields.io/badge/version-v2.0.1-green.svg?maxAge=2592000)](https://github.com/swoft-cloud/swoft/releases)
[![Build Status](https://travis-ci.org/swoft-cloud/swoft.svg?branch=master)](https://travis-ci.org/swoft-cloud/swoft)
[![Docker Build Status](https://img.shields.io/docker/build/swoft/alphp.svg)](https://hub.docker.com/r/swoft/alphp/)
[![Php Version](https://img.shields.io/badge/php-%3E=7.1-brightgreen.svg?maxAge=2592000)](https://secure.php.net/)
[![Swoole Version](https://img.shields.io/badge/swoole-%3E=4.3.3-brightgreen.svg?maxAge=2592000)](https://github.com/swoole/swoole-src)
[![Swoft Doc](https://img.shields.io/badge/docs-passing-green.svg?maxAge=2592000)](https://www.swoft.org/docs)
[![Swoft License](https://img.shields.io/hexpm/l/plug.svg?maxAge=2592000)](https://github.com/swoft-cloud/swoft/blob/master/LICENSE)
⚡️ Modern High performance AOP and Coroutine PHP Framework, base on Swoole
## Feature
- Built-in high performance network server(Http/Websocket/RPC)
- Flexible componentization
- Flexible annotation function
- Diversified command terminal(Console)
- Powerful Aspect Oriented ProgrammingAOP
- Perfect Container management、Dependency Injection (DI)
- Flexible event mechanism
- Implementation of HTTP message based on PSR-7
- Event Manager Based on PSR-14
- Middleware based on PSR-15
- Internationalization(i18n) support
- Simple and efficient parameter validator
- High performance connection pool(Mysql/Redis/RPC)Automatic reconnection
- Database is highly compatible Laravel
- Cache Redis highly compatible Laravel
- Efficient task processing
- Flexible exception handling
- Powerful log system
## Document
- [中文](https://www.swoft.org/docs/2.x/zh-CN/README.html)
- [English](https://www.swoft.org/docs/2.x/en)
QQ Group1: 548173319
QQ Group2: 778656850
## Requirement
- [PHP 7.1 +](https://github.com/php/php-src/releases)
- [Swoole 4.3.4 + ](https://github.com/swoole/swoole-src/releases)
- [Composer](https://getcomposer.org/)
## Install
### Composer
* `composer create-project swoft/swoft swoft`
## Start
```text
[root@swoft swoft]# php bin/swoft http:start
2019/06/02-11:18:06 [INFO] Swoole\Runtime::enableCoroutine
2019/06/02-11:18:06 [INFO] Swoft\SwoftApplication:__construct(14) Set alias @base=/data/www/swoft
2019/06/02-11:18:06 [INFO] Swoft\SwoftApplication:__construct(14) Set alias @app=@base/app
2019/06/02-11:18:06 [INFO] Swoft\SwoftApplication:__construct(14) Set alias @config=@base/config
2019/06/02-11:18:06 [INFO] Swoft\SwoftApplication:__construct(14) Set alias @runtime=@base/runtime
2019/06/02-11:18:06 [INFO] Project path is /data/www/swoft
2019/06/02-11:18:06 [INFO] Swoft\Processor\ApplicationProcessor:handle(221) Env file(/data/www/swoft/.env) is loaded
2019/06/02-11:18:11 [INFO] Swoft\Processor\ApplicationProcessor:handle(221) Annotations is scanned(autoloader 23, annotation 226, parser 57)
2019/06/02-11:18:11 [INFO] Swoft\Processor\ApplicationProcessor:handle(221) config path=/data/www/swoft/config
2019/06/02-11:18:11 [INFO] Swoft\Processor\ApplicationProcessor:handle(221) config env=
2019/06/02-11:18:11 [INFO] Swoft\Processor\ApplicationProcessor:handle(221) Bean is initialized(singleton 144, prototype 41, definition 30)
2019/06/02-11:18:11 [INFO] Swoft\Processor\ApplicationProcessor:handle(221) Event manager initialized(30 listener, 3 subscriber)
2019/06/02-11:18:11 [INFO] Swoft\Event\Manager\EventManager:triggerListeners(324) WebSocket server route registered(module 2, message command 3)
2019/06/02-11:18:11 [INFO] Swoft\Event\Manager\EventManager:triggerListeners(324) Error manager init completed(2 type, 3 handler, 3 exception)
2019/06/02-11:18:11 [INFO] Swoft\Processor\ApplicationProcessor:handle(221) Console command route registered (group 14, command 5)
Information Panel
***********************************************************************
* HTTP | Listen: 0.0.0.0:18306, type: TCP, mode: Process, worker: 1
* rpc | Listen: 0.0.0.0:18307, type: TCP
***********************************************************************
HTTP server start success !
2019/06/02-11:18:11 [INFO] Swoft\Event\Manager\EventManager:triggerListeners(324) Registered swoole events:
start, shutdown, managerStart, managerStop, workerStart, workerStop, workerError, request, task, finish
Server start success (Master PID: 249, Manager PID: 250)
```
## License
Swoft is an open-source software licensed under the [LICENSE](LICENSE)

View File

@@ -0,0 +1 @@
e0bdcd01-4bab-4f2f-ab35-b7147bb52aed

View File

@@ -0,0 +1,17 @@
<?php declare(strict_types=1);
namespace App;
use Swoft\SwoftApplication;
/**
* Class Application
*
* @since 2.0
*/
class Application extends SwoftApplication
{
}

View File

@@ -0,0 +1 @@
375adeb4-4191-4d9e-858f-42da9b876834

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Aspect;
use Swoft\Aop\Annotation\Mapping\AfterThrowing;
use Swoft\Aop\Annotation\Mapping\Aspect;
use Swoft\Aop\Annotation\Mapping\PointAnnotation;
use Swoft\Bean\Annotation\Mapping\Inject;
use App\Bean\ResponseBean;
/**
* @Aspect(order=1)
* @PointAnnotation(
* include={
* Swoft\Http\Server\Annotation\Mapping\RequestMapping::class
* }
* )
*/
class FailAspect {
/**
* @Inject("ResponseBean")
*/
protected $response;
/**
* @param \Throwable $throwable
* @return array
* @AfterThrowing()
*/
public function FailError(\Throwable $throwable) {
return $this->response->fail($throwable);
}
}

View File

@@ -0,0 +1,33 @@
<?php declare(strict_types=1);
namespace App;
use Swoft\SwoftComponent;
/**
* Class AutoLoader
*
* @since 2.0
*/
class AutoLoader extends SwoftComponent
{
/**
* @return array
*/
public function getPrefixDirs(): array
{
return [
__NAMESPACE__ => __DIR__,
];
}
/**
* @return array
*/
public function metadata(): array
{
return [];
}
}

View File

@@ -0,0 +1 @@
3ea41287-a390-4560-b6bc-0c9784e318da

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Bean;
use Exception;
use Swoft\Bean\Annotation\Mapping\Bean;
/**
* @Bean("ResponseBean")
* @package App\Bean
*/
class ResponseBean {
public function success($data = [], string $message = "") {
$response = context()->getResponse();
return $response->withData([
'code' => 200,
'result' => $data,
'message' => $message
]);
}
public function fail($e) {
$response = context()->getResponse();
return $response->withData([
'code' => $e->getCode(),
'result' => null,
'message' => $e->getMessage(),
]);
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Bean;
use Swoft\Bean\Annotation\Mapping\Bean;
/**
* @Bean("test")
* @package App\Bean
*/
class TestBean {
public function hello () {
return "ddcdcdefefe";
}
}

View File

@@ -0,0 +1 @@
62358ba4-92bf-44d5-8edf-ed2af2dc8c2d

View File

@@ -0,0 +1 @@
9b3da84a-ca48-45d1-a1cf-2f4787f943c2

View File

@@ -0,0 +1 @@
d83e73ef-1861-42a2-b617-46fb98373d97

View File

@@ -0,0 +1,28 @@
<?php declare(strict_types=1);
namespace App\Console\Command;
use Swoft\Console\Annotation\Mapping\Command;
use Swoft\Console\Annotation\Mapping\CommandMapping;
use Swoft\Console\Helper\Show;
use Swoft\Console\Input\Input;
/**
* Class DemoCommand
*
* @Command()
*/
class DemoCommand
{
/**
* @CommandMapping()
* @param Input $input
*/
public function test(Input $input): void
{
Show::prettyJSON([
'args' => $input->getArgs(),
'opts' => $input->getOptions(),
]);
}
}

View File

@@ -0,0 +1,107 @@
<?php declare(strict_types=1);
namespace App\Console\Command;
use Swoft\Console\Annotation\Mapping\Command;
use Swoft\Console\Annotation\Mapping\CommandMapping;
use function input;
use function output;
use function sprintf;
/**
* Class TestCommand
*
* @since 2.0
*
* @Command(name="test",coroutine=false)
*/
class TestCommand
{
/**
* @CommandMapping(name="ab")
*/
public function ab()
{
$type = input()->get('type', '');
$uris = $this->uris();
// Format data
if (empty($type)) {
$exeUris = [];
foreach ($uris as $name => $uriAry) {
$exeUris = array_merge($exeUris, $uriAry);
}
} else {
$exeUris = $uris[$type] ?? [];
}
foreach ($exeUris as $uri) {
$curlResult = null;
$abShell = sprintf('ab -k -n 10000 -c 2000 127.0.0.1:18306%s', $uri);
$curlShell = sprintf('curl 127.0.0.1:18306%s', $uri);
exec($curlShell, $curlResult);
output()->writeln('执行结果:' . json_encode($curlResult));
output()->writeln('执行URL:' . $abShell . PHP_EOL);
exec($abShell, $abResult);
}
}
/**
* @return array
*/
private function uris(): array
{
return [
'redis' => [
'/redis/str',
'/redis/et',
'/redis/ep',
'/redis/release',
'/redis/poolSet',
],
'log' => [
'/log/test'
],
'db' => [
'/dbTransaction/ts',
'/dbTransaction/cm',
'/dbTransaction/rl',
'/dbTransaction/ts2',
'/dbTransaction/cm2',
'/dbTransaction/rl2',
'/dbTransaction/multiPool',
'/dbModel/find',
'/dbModel/update',
'/dbModel/delete',
'/dbModel/save',
'/selectDb/modelNotExistDb',
'/selectDb/queryNotExistDb',
'/selectDb/dbNotExistDb',
'/selectDb/modelDb',
'/selectDb/queryDb',
'/selectDb/dbDb',
'/selectDb/select'
],
'task' => [
'/task/getListByCo',
'/task/deleteByCo',
'/task/getListByAsync',
'/task/deleteByAsync',
],
'rpc' => [
'/rpc/getList',
'/rpc/returnBool',
'/rpc/bigString',
],
'co' => [
'/co/multi'
],
'bean' => [
'/bean/request'
]
];
}
}

View File

@@ -0,0 +1 @@
2b50acd1-0aa8-447e-8c7d-b456aca47f0c

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Exception;
/**
* Class ApiException
*
* @since 2.0
*/
class ApiException extends \Exception
{
}

View File

@@ -0,0 +1 @@
988cd99e-1f40-4960-a441-70636b490308

View File

@@ -0,0 +1,37 @@
<?php declare(strict_types=1);
namespace App\Exception\Handler;
use App\Exception\ApiException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
use Throwable;
/**
* Class ApiExceptionHandler
*
* @since 2.0
*
* @ExceptionHandler(ApiException::class)
*/
class ApiExceptionHandler extends AbstractHttpErrorHandler
{
/**
* @param Throwable $except
* @param Response $response
*
* @return Response
*/
public function handle(Throwable $except, Response $response): Response
{
$data = [
'code' => $except->getCode(),
'error' => sprintf('(%s) %s', get_class($except), $except->getMessage()),
'file' => sprintf('At %s line %d', $except->getFile(), $except->getLine())
];
return $response->withData($data);
}
}

View File

@@ -0,0 +1,49 @@
<?php declare(strict_types=1);
namespace App\Exception\Handler;
use const APP_DEBUG;
use function get_class;
use ReflectionException;
use function sprintf;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Exception\Handler\AbstractHttpErrorHandler;
use Throwable;
/**
* Class HttpExceptionHandler
*
* @ExceptionHandler(\Throwable::class)
*/
class HttpExceptionHandler extends AbstractHttpErrorHandler
{
/**
* @param Throwable $e
* @param Response $response
*
* @return Response
* @throws ReflectionException
* @throws ContainerException
*/
public function handle(Throwable $e, Response $response): Response
{
// Debug is false
if (!APP_DEBUG) {
return $response->withStatus(500)->withContent(
sprintf(' %s At %s line %d', $e->getMessage(), $e->getFile(), $e->getLine())
);
}
$data = [
'code' => $e->getCode(),
'error' => sprintf('(%s) %s', get_class($e), $e->getMessage()),
'file' => sprintf('At %s line %d', $e->getFile(), $e->getLine()),
'trace' => $e->getTraceAsString(),
];
// Debug is true
return $response->withData($data);
}
}

View File

@@ -0,0 +1,51 @@
<?php declare(strict_types=1);
namespace App\Exception\Handler;
use ReflectionException;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Error\Annotation\Mapping\ExceptionHandler;
use Swoft\Log\Debug;
use Swoft\Rpc\Error;
use Swoft\Rpc\Server\Exception\Handler\RpcErrorHandler;
use Swoft\Rpc\Server\Response;
use Throwable;
/**
* Class RpcExceptionHandler
*
* @since 2.0
*
* @ExceptionHandler(\Throwable::class)
*/
class RpcExceptionHandler extends RpcErrorHandler
{
/**
* @param Throwable $e
* @param Response $response
*
* @return Response
* @throws ReflectionException
* @throws ContainerException
*/
public function handle(Throwable $e, Response $response): Response
{
// Debug is false
if (!APP_DEBUG) {
$message = sprintf(' %s At %s line %d', $e->getMessage(), $e->getFile(), $e->getLine());
$error = Error::new($e->getCode(), $message, null);
} else {
$error = Error::new($e->getCode(), $e->getMessage(), null);
}
Debug::log('Rpc server error(%s)', $e->getMessage());
$response->setError($error);
// Debug is true
return $response;
}
}

View File

@@ -0,0 +1 @@
b7421c70-f5c0-419b-805c-5f8a40c85943

View File

@@ -0,0 +1,9 @@
<?php
/**
* Custom global functions
*/
function user_func(): string
{
return 'hello';
}

View File

@@ -0,0 +1 @@
54ffec2f-e094-4f86-a8b4-002b1a42fe22

View File

@@ -0,0 +1 @@
675329f0-6a31-4094-9bea-19e67e56a8d0

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Http\Controller;
use BmobObject;
use Swoft\Bean\Annotation\Mapping\Inject;
use App\Bean\ResponseBean;
abstract class BaseController {
/**
* @Inject("ResponseBean")
*/
protected $response;
protected function newBmobObject(string $tabeName = '') {
return new BmobObject($tabeName);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Http\Controller;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
use BmobObject;
/**
* @Controller("admin")
* @package App\Http\Controller
*/
class CourseController extends BaseController {
/**
* @Inject("CourseService")
*/
private $CourseService;
/**
* @RequestMapping("newCourse", method=RequestMethod::POST)
* @param Request $request
* @return array|mixed|string
*/
public function newCourse (Request $request) {
$status = $this->CourseService->addNewCourse($request->post());
return $this->response->success($status,'发布课程成功');
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controller;
use App\Exception\ApiException;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
/**
* @Controller(prefix="ex")
*/
class ExceptionController
{
/**
* @RequestMapping(route="api")
*
* @throws ApiException
*/
public function api(){
throw new ApiException("api of ExceptionController");
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controller;
use BmobObject;
use App\Exception\ApiException;
use Exception;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Message\Request;
/**
* @Controller("/order")
* @package App\Http\Controller
*/
class OrderController extends BaseController {
/**
* @RequestMapping("list")
*/
// 通过AOP切面自动捕获代码的 AfterThrowing 错误,并统一序列化返回错误信息
public function getOrderList(Request $request) {
$bmobObj = $this->newBmobObject("coures");
$data = $bmobObj->get($request->get("id"));
return $this->response->success($data);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controller;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
/**
* @Controller("admin")
* @package App\Http\Controller
*/
class QiniuTokenController extends BaseController {
/**
* @RequestMapping("token")
*/
public function getToken () {
$accessKey = '0MGmT_rkMiaOeXY09B4EhBnXuDcIYyKlGumQ-zUt';
$secretKey = '59dfmEi9Q50rMlz9sxTBCvYDhM7biERAjflBXALb';
$auth = new Auth($accessKey, $secretKey);
return $this->response->success([
"token" => $auth->uploadToken("guaikevideo")
]);
}
}

View File

@@ -0,0 +1 @@
26db9c32-5ae1-4dd0-9745-212d914d58e8

View File

@@ -0,0 +1,10 @@
<?php declare(strict_types=1);
namespace App\Http\Middleware;
class ControllerMiddleware
{
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Http\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Http\Server\Contract\MiddlewareInterface;
/**
* @Bean()
*/
class CorsMiddleware implements MiddlewareInterface {
/**
* Process an incoming server request.
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
* @inheritdoc
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ('OPTIONS' === $request->getMethod()) {
$response = Context::mustGet()->getResponse();
return $this->configResponse($response);
}
$response = $handler->handle($request);
return $this->configResponse($response);
}
private function configResponse(ResponseInterface $response)
{
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
}
}

View File

@@ -0,0 +1 @@
62bda268-f190-4e44-8b1d-b8b46d220567

View File

@@ -0,0 +1 @@
856beba3-b65b-411b-acd6-af8cce29940b

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Model\Dao;
use BmobObject;
class BmobDao {
protected $bmobObj;
/**
* 向数据库添加一条数据
* @param array $params
* @return mixed
*/
protected function addNewObject (array $params) {
$this->newBmob($params['tableName']);
return $this->bmobObj->create($params['data']);
}
protected function newBmob($tableName = ""): void {
$this->bmobObj = new BmobObject($tableName);
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Model\Dao;
use Swoft\Bean\Annotation\Mapping\Bean;
/**
* @Bean("CourseDao")
* @package App\Model\Dao
*/
class CourseDao extends BmobDao {
public function addNewCourseDao (array $params) {
return $this->addNewObject($params);
}
}

View File

@@ -0,0 +1 @@
5b1fd486-d467-4fb0-a89d-859fa4aa855f

View File

@@ -0,0 +1,9 @@
<?php
namespace App\Model\Service;
interface CourseInterface {
public function addNewCourse(array $info);
}

View File

@@ -0,0 +1 @@
691c4bfc-2484-4c05-aed5-e2aad8d6115c

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Model\Service\impl;
use App\Model\Service\CourseInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
/**
* @Bean("CourseService")
*/
class CourseService implements CourseInterface {
/**
* @Inject("CourseDao")
*/
private $CourseDao;
public function addNewCourse(array $info) {
$data = [
"tableName" => "coures",
"data" => $info
];
return $this->CourseDao->addNewCourseDao($data);
}
}

View File

@@ -0,0 +1 @@
d26f8272-068c-4024-bc8b-35b60c886f52

View File

@@ -0,0 +1,2 @@
lib/BmobConfig.class.php

View File

@@ -0,0 +1 @@
5f3a3b92-b470-4020-a47c-93c42b409516

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,131 @@
Bmob PHP SDK开发文档
===============
本文档是Bmob官方提供的PHP SDK方便PHP开发人员快速使用Bmob进行后端开发。
【注】运行PHP需要相关运行环境推荐在5.*以上环境上使用。PHP官方下载地址为[http://php.net/](http://php.net/) 。
## 准备工作
### SDK下载
请到以下的Github地址clone我们的SDK最新代码[https://github.com/bmob/bmob-php-sdk](https://github.com/bmob/bmob-php-sdk)
### 目录结构
```
doc_faststart快速入门文档
doc_develop详细开发文档
libphp的类库
pay支付的demo
test.php: 一些demo
```
### 安装和配置
=========================
打开`lib/BmobConfig.class.php`,填写`APPID`后台获取“应用密钥”中的Application ID`RESTKEY`后台获取“应用密钥”中的REST API Key相应的值。如下所示
```
class BmobConfig{
const APPID = ''; //替换后台"应用密钥"中的Application ID
const RESTKEY = ''; //后台"应用密钥"中的REST API Key
const BMOBURL = 'https://api.bmob.cn/1/'; //保持不变
}
```
## 运行效果
打开项目中的`test.php`文件可以看到如何使用PHP SDK相关的方法。
```
<?php
include_once 'lib/BmobObject.class.php';
include_once 'lib/BmobUser.class.php';
try {
/*
* BmobObject 的例子
*/
$bmobObj = new BmobObject("GameScore");
$res=$bmobObj->create(array("score"=>80,"playerName"=>"game")); //添加对象
$res=$bmobObj->get("bd89c6bce9"); // 获取id为bd89c6bce9的对象
$res=$bmobObj->get(); //获取所有对象
//更新对象bd89c6bce9, 任何您未指定的key都不会更改,所以您可以只更新对象数据的一个子集
$res=$bmobObj->update("bd89c6bce9", array("score"=>60,"playerName"=>"game"));
$res=$bmobObj->delete("bd89c6bce9"); //删除对象bd89c6bce9
//对象的查询,这里是表示查找playerName为"game"的对象,只返回2个结果
$res=$bmobObj->get("",array('where={"playerName":"game"}','limit=2'));
//id为bd89c6bce9的field score数值减2
$res=$bmobObj->increment("bd89c6bce9","score",array(-2));
//id为bd89c6bce9的field score数值加2
$res=$bmobObj->increment("bd89c6bce9","score",array(2));
/*
* BmobUser 的例子
*/
$bmobUser = new BmobUser();
//用户注册, 其中username和password为必填字段
$res = $bmobUser->register(array("username"=>"cooldude117", "password"=>"p_n7!-e8", "phone"=>"415-392-0202", "email"=>"bmobtest111@126.com"));
//用户登录, 第一个参数为用户名,第二个参数为密码
$res = $bmobUser->login("cooldude117","p_n7!-e8");
// 获取id为415b8fe99a用户的信息
$res = $bmobUser->get("415b8fe99a");
$res = $bmobUser->get(); // 获取所有用户的信息
$res = $bmobUser->update("415b8fe99a", "050391db407114d9801c8f2788c6b25a", array("phone"=>"02011111")); // 更新用户的信息
// 请求重设密码,前提是用户将email与他们的账户关联起来
$res = $bmobUser->requestPasswordReset("bmobtest111@126.com");
// 删除id为415b8fe99a的用户, 第一参数是用户id, 第二个参数为sessiontoken,在用户登录或注册后获取, 必填
$res = $bmobUser->delete("415b8fe99a", "050391db407114d9801c8f2788c6b25a");
/*
* BmobCloudCode 的例子
*/
//调用名字为getMsgCode的云端代码
$cloudCode = new BmobCloudCode('getMsgCode');
//传入参数name其值为bmob
$res = $cloudCode->get(array("name"=>"bmob"));
var_dump($res);
} catch (Exception $e) {
echo $e;
}
```
## 类库说明
1. BmobConfig
Bmob配置类使用的时候需要修改里面的配置信息
2. BmobUser
Bmob用户表处理类负责处理与_User表相关的事情
3. BmobObject
Bmob对象处理类负责处理云端各种表的数据操作
4. BmobRestClient
Bmob基础类用于完成REST API请求
5. BmobException
Bmob异常处理类
6. BmobCloudCode
Bmob云端代码调用类
# Bmob官方信息
官方网址:[http://www.bmob.cn](http://www.bmob.cn)
问答社区:[http://wenda.bmob.cn](http://wenda.bmob.cn)
技术邮箱support@bmob.cn

View File

@@ -0,0 +1 @@
c19a74f2-c9dd-44fd-ae5d-9d4ce7fb780d

View File

@@ -0,0 +1,10 @@
TESTS = test/*.js
REPORTER = spec
TIMEOUT = 5000
MOCHA = ./node_modules/mocha/bin/mocha
test:
@npm install
@$(MOCHA) --reporter $(REPORTER) --timeout $(TIMEOUT) $(MOCHA_OPTS) $(TESTS)
.PHONY: test

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
46d94b12-2686-44c9-8a09-9991ff9a7448

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 215 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

View File

@@ -0,0 +1,46 @@
{
"name": "bmob开发文档",
"version": "0.2.6",
"description": "简单介绍Bmob以及如何注册、下载、嵌入使用SDK的方法等等",
"main": "index.js",
"scripts": {
"test": "make test"
},
"bin": {
"doxmate": "bin/doxmate",
"doxmate-build": "bin/doxmate-build",
"doxmate-theme": "bin/doxmate-theme"
},
"keywords": [
"documentation",
"dox"
],
"dependencies": {
"dox": "*",
"commander": "*",
"marked": "*",
"ejs": "*",
"ncp": "*"
},
"devDependencies": {
"should": "*",
"mocha": "*"
},
"author": "Jackson Tian",
"contributors": [
"JacksonTian <shyvo1987@gmail.com> (https://github.com/JacksonTian)",
"youxiachai <youxiachai@gmail.com> (https://github.com/youxiachai)"
],
"license": "MIT",
"directories": {
"doc": "doc",
"test": "test"
},
"repository": {
"type": "git",
"url": "git://github.com/JacksonTian/doxmate.git"
},
"bugs": {
"url": "https://github.com/JacksonTian/doxmate/issues"
}
}

View File

@@ -0,0 +1 @@
2361b437-6e8d-4b57-b485-f1795f4120d6

View File

@@ -0,0 +1,93 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobApp extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 获取app的信息, 指定appId则获取某个app的信息
* @param $email 登录的用户名
* @param $password 登录的密码
* @param $appId
*/
public function getApp($email, $password, $appId = 0)
{
if (!empty($email) && !empty($password)) {
if ($appId != 0) {
$requestUrl = 'apps/' . $appId;
} else {
$requestUrl = 'apps';
}
$sendRequest = $this->sendRequest(array(
'X-Bmob-Email' => $email,
'X-Bmob-Password' => $password,
'method' => 'GET',
'sendRequestUrl' => $requestUrl,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 创建app
* @param $email 登录的用户名
* @param $password 登录的密码
* @param $data
*/
public function createApp($email, $password, $data)
{
if (!empty($email) && !empty($password) && !empty($data)) {
$sendRequest = $this->sendRequest(array(
'X-Bmob-Email' => $email,
'X-Bmob-Password' => $password,
'method' => 'POST',
'data' => $data,
'sendRequestUrl' => "apps",
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 修改app的信息
* @param $email 登录的用户名
* @param $password 登录的密码
* @param $data
*/
public function updateApp($email, $password, $id, $data)
{
if (!empty($email) && !empty($password) && !empty($id) && !empty($data)) {
$sendRequest = $this->sendRequest(array(
'X-Bmob-Email' => $email,
'X-Bmob-Password' => $password,
'method' => 'PUT',
'data' => $data,
'sendRequestUrl' => "apps/" . $id,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
}
?>

View File

@@ -0,0 +1,43 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobBatch extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 批量操作
* @param array $data 批量操作的数据
*/
public function batch($data)
{
if (!empty($data)) {
//重设对象的属性
$this->cleanData();
$this->data["requests"] = $data;
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'batch',
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('批量操作时请指定操作的数据');
}
}
}
?>

View File

@@ -0,0 +1,42 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobBql extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 批量操作
* @param array $data 查询条件
*/
public function query($data)
{
if (!empty($data)) {
$this->data["requests"] = $data;
$sendRequest = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => 'cloudQuery',
'urlParams' => $data,
));
return $sendRequest;
} else {
$this->throwError('查询条件不能为空');
}
}
}
?>

View File

@@ -0,0 +1,46 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobObject object对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobCloudCode extends BmobRestClient
{
private $_cloudCodeName = '';
public function __construct($codeName = '')
{
if ($codeName != '') {
$this->_cloudCodeName = $codeName;
} else {
$this->throwError('创建对象时请包含对象id');
}
parent::__construct();
}
/**
* 获取对象
* @param array $condition ,查询条件
*/
public function get($data = array())
{
if ($this->_cloudCodeName != '') {
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'functions/' . $this->_cloudCodeName,
'data' => $data,
));
return $sendRequest;
} else {
$this->throwError('获取对象时请指定对象id');
}
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* BmobException 异常类
* @author jeff
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobException extends Exception
{
public function __construct($message="", $code = 0) {
//codes are only set by a bmob.com error
if($code != 0){
$message = "bmob.cn error: ".$message;
}
parent::__construct($message, $code);
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}

View File

@@ -0,0 +1,101 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobFile extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 删除文件
* @param array $data 删除文件的数据
*/
public function delete($url)
{
if (!empty($url) ) {
//重设对象的属性
$this->cleanData();
$sendRequest = $this->sendRequest(array(
'method' => 'DELETE',
'sendRequestUrl' => 'files/' . $url,
));
return $sendRequest;
} else {
$this->throwError('请输入url');
}
}
/**
* 用CDN上传文件
如果需要上传大文件,请在代码中调整php的配置:
ini_set('max_execution_time', 30); //每个PHP页面运行的最大时间值(秒)默认30秒
ini_set('max_input_time', 60); //每个PHP页面接收数据所需的最大时间默认60秒
ini_set('memory_limit', '8m'); //每个PHP页面所吃掉的最大内存默认8M
ini_set('upload_max_filesize', '2m'); //即允许上传文件大小的最大值。默认为2M
ini_set('post_max_size', '8m'); //指通过表单POST给PHP的所能接收的最大值包括表单里的所有值。默认为8M
* @param array $data 批量操作的数据
*/
public function uploadFile2($fileName, $filePath)
{
if (!empty($fileName) && !empty($filePath)) {
//重设对象的属性
$this->cleanData();
$this->data = file_get_contents($filePath);
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'files/' . $fileName,
'data' => $this->data,
), 2);
return $sendRequest;
} else {
$this->throwError('请输入文件名和文件路径');
}
}
/**
* 用uploadFile2接口上传的文件只能用这个接口删除文件
* @param array $url
*/
public function delete2($cdn, $url)
{
if (!empty($url) && !empty($cdn) ) {
//重设对象的属性
$this->cleanData();
// $path = pathinfo($url);
// if( !$path ){
// $this->throwError('解析url错误, 正确的url是类似于:http://bmob-cdn-10.b0.upaiyun.com/2017/02/08/f39178e3409990ca80e0d9d60ecef768.png');
// }
if(strpos($url, "http://")>=0) {
$url = trim($url, "http://");
} else {
$url = trim($url, "https://");
}
$url = substr($url, strpos($url, "/") + 1);
$sendRequest = $this->sendRequest(array(
'method' => 'DELETE',
'sendRequestUrl' => 'files/' .$cdn."/". $url,
), 2 );
return $sendRequest;
} else {
$this->throwError('请输入url');
}
}
}
?>

View File

@@ -0,0 +1,65 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobImage extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 生成缩微图
* @param array $data 参数
*/
public function imageThumbnail($data)
{
if (!empty($data)) {
//重设对象的属性
$this->cleanData();
$this->data = $data;
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'images/thumbnail',
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 生成水印
* @param array $data 参数
*/
public function imagesWatermark($data)
{
if (!empty($data)) {
$this->data = $data;
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'images/watermark',
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
}
?>

View File

@@ -0,0 +1,429 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobObject object对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobObject extends BmobRestClient
{
public $_includes = array();
private $_className = '';
public function __construct($class = '', $sessionToken = '')
{
if ($class != '') {
$this->_className = $class;
} else {
$this->throwError('创建对象时请包含对象id');
}
if ($sessionToken != '') {
$this->bmobSessionToken = $sessionToken;
}
parent::__construct();
}
public function getRequestUrl($id=""){
$className = $this->_className;
if( "_User" == $className ){
$className = "users";
} elseif ( "_Installation" == $className ) {
$className = "installations";
}
if( $id ){
if ( $this->_className!="_User" && $this->_className!="_Installation") {
return 'classes/' . $className . '/' . $id;
}else{
return $className . '/' . $id;
}
} else {
if ( $this->_className!="_User" && $this->_className!="_Installation") {
return 'classes/' . $className ;
}else{
return $className ;
}
}
}
/**
* 添加对象
* @param array $data 对象的属性数组
*
*/
public function create($data = array())
{
//重设对象的属性
$this->setData($data);
if (count($this->data) > 0 && $this->_className != '') {
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => $this->getRequestUrl(""),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('创建对象时请添加对象数据或指定对象id');
}
}
/**
* 获取对象
* @param string $id 对象id, 当为空时表示获取所有对象
* @param array $condition ,查询条件
*/
public function get($id = "", $condition = array())
{
if ($this->_className != '') {
if ($id) {
$sendRequest = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => $this->getRequestUrl($id),
'condition' => $condition,
));
} else {
$sendRequest = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => $this->getRequestUrl(""),
'condition' => $condition,
));
}
return $sendRequest;
} else {
$this->throwError('获取对象时请指定对象id');
}
}
/**
* 更新对象的属性
* @param string $id 对象id
* @param array $data 对象的属性数组
*/
public function update($id, $data = array())
{
if ($this->_className != '' || !empty($id)) {
if ($data) {
//添加对象的属性
$this->setData($data);
} else {
$this->throwError('请指定要更新的属性');
}
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('修改对象时请指定对象id');
}
}
/**
* 删除对象
* @param string $id 对象id
*/
public function delete($id)
{
if ($this->_className != '' || !empty($id)) {
$sendRequest = $this->sendRequest(array(
'method' => 'DELETE',
'sendRequestUrl' => $this->getRequestUrl($id),
));
return $sendRequest;
} else {
$this->throwError('删除对象时请指定对象id');
}
}
/**
* 任何数字字段进行原子增加或减少的功能
* @param string $id 对象id
* @param string $field 需要修改的数字字段
* @param int $amount 不加负号表示增加, 加负号表示减少
*/
public function increment($id, $field, $amount)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' || !empty($id)) {
$this->data[$field] = $this->dataType('increment', $amount);
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('修改对象时请指定对象id');
}
}
/**
* 在一个对象中删除一个字段
* @param string $id 对象id
* @param string $field 需要删除的字段
*/
public function deleteField($id, $field)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($id) && !empty($field)) {
$this->data[$field] = $this->dataType('deleteField', $field);
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('修改对象时请指定对象id');
}
}
/**
* 添加数组数据
* @param string $field 需要修改的字段
* @param string $data 添加的数组
*/
public function addArray($field, $data)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($field) && !empty($data)) {
$this->data[$field] = $this->dataType('addArray', $data);
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => $this->getRequestUrl(""),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('添加对象时请指定对象field或数据');
}
}
/**
* 修改数组数据
* @param string $id id
* @param string $field 需要修改的字段
* @param string $data 修改的数组
*/
public function updateArray($id, $field, $data)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($id) && !empty($field) && !empty($data)) {
$this->data[$field] = $this->dataType('addArray', $data);
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('修改对象时请指定对象id和field和数据');
}
}
/**
* 删除数组数据
* @param string $id id
* @param string $field 需要修改的字段
* @param string $data 删除的数组
*/
public function deleteArray($id, $field, $data)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($id) && !empty($field) && !empty($data)) {
$this->data[$field] = $this->dataType('delArray', $data);
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('删除时请指定对象id和field和数据');
}
}
/**
* 添加关联对象(1对1)
* @param string $field 需要添加关联的字段
* @param string $otherObject 需要修改的字段
* @param string $otherObjectId 删除的数组
*/
public function addRelPointer($data)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($data) ) {
$this->data = $this->dataType('addRelPointer', $data);
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => $this->getRequestUrl(""),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('添加关联对象时请指定对象id和field和数据');
}
}
/**
* 添加关联对象(1对多)
* @param string $field 需要添加关联的字段
* @param array $data 关联的数据
*/
public function addRelRelation($field, $data)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($field) && !empty($data)) {
$this->data[$field] = $this->dataType('addRelRelation', $data);
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => $this->getRequestUrl(""),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('添加关联对象时请指定对象id和data');
}
}
/**
* 修改关联对象(1对1)
* @param string $id id
* @param string $field 需要添加关联的字段
* @param string $otherObject 需要修改的字段
* @param string $otherObjectId 删除的数组
*/
public function updateRelPointer($id, $field, $otherObject, $otherObjectId)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($field) && !empty($otherObject) && !empty($otherObjectId)) {
$this->data[$field] = $this->dataType('updateRelPointer', array($field, $otherObject, $otherObjectId));
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('修改关联对象时请指定对象id和field和数据');
}
}
/**
* 修改关联对象(1对多)
* @param string $id
* @param string $field 需要添加关联的字段
* @param array $data 关联的数据
*/
public function updateRelRelation($id, $field, $data)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($id) && !empty($field) && !empty($data)) {
$this->data[$field] = $this->dataType('addRelRelation', $data);
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('修改关联对象时请指定对象id和field和data');
}
}
/**
* 删除关联对象
* @param string $id
* @param string $field 需要添加关联的字段
* @param array $data 关联的数据
*/
public function deleteRelation($id, $field, $data)
{
//重设对象的属性
$this->cleanData();
if ($this->_className != '' && !empty($id) && !empty($field) && !empty($data)) {
$this->data[$field] = $this->dataType('removeRelation', $data);
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => $this->getRequestUrl($id),
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('删除关联对象时请指定对象id和field和data');
}
}
}
?>

View File

@@ -0,0 +1,61 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobPay 支付类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobPay extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 查询订单
* @param $id
*/
public function getOrder($id)
{
if (!empty($id)) {
$sendRequest = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => 'pay/' . $id,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 支付扫码接口
* @param $orderPrice 价格
* @param $productName 商品名称
* @param $body 商品描述
* @param $payment 2:微信 3.qq
*/
public function webPay($orderPrice, $productName, $body, $payment)
{
if (!empty($orderPrice) && !empty($productName) && !empty($body) ) {
$this->cleanData();
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'pay' ,
'data' => array("order_price"=>$orderPrice, "product_name"=>$productName, "body"=>$body, "payment"=>$payment),
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
}
?>

View File

@@ -0,0 +1,80 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobPush extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 保存设备信息
* @param $data data
*/
public function addInstallations($data)
{
if (!empty($data)) {
//重设对象的属性
$this->cleanData();
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'data' => $data,
'sendRequestUrl' => 'installations',
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 更新设备信息
* @param $data data
*/
public function updateInstallations($id, $data)
{
if (!empty($data)) {
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'data' => $data,
'sendRequestUrl' => 'installations/' . $id,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 推送
* @param $data data
*/
public function push($data)
{
if (!empty($data)) {
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'data' => $data,
'sendRequestUrl' => 'push',
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
}
?>

View File

@@ -0,0 +1,371 @@
<?php
include_once 'BmobConfig.class.php';
include_once 'BmobException.class.php';
/**
* BmobRestClient 主类所有的api请求都需要使用这个类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobRestClient
{
private $_bmobAppid = '';
private $_bmobRestkey = '';
private $_bmobUrl = '';
private $_bmobUrlTwo = '';
public $data;
public $sendRequestUrl = '';
public $responseData = '';
public $masterKey = '';
public $bmobSessionToken = '';
protected function __construct()
{
$this->_bmobAppid = BmobConfig::APPID;
$this->_bmobRestkey = BmobConfig::RESTKEY;
$this->_bmobUrl = BmobConfig::BMOBURL;
$this->_bmobUrlTwo = BmobConfig::BMOBURLTWO;
if (empty($this->_bmobAppid) || empty($this->_bmobRestkey)) {
$this->throwError('必须要设置Application ID 和 REST API Key');
}
if (!$this->_bmobUrlTwo) {
$this->throwError('必须要在BmobConfig.class.php中设置BMOBURLTWO的值, 请参考github上的设置');
}
$version = curl_version();
if (!$version['features'] & CURL_VERSION_SSL) {
$this->throwError('不支持ssl的链接');
}
}
/**
* 重设对象的属性
* @param array $data
*/
public function setData($data = array())
{
//每次使用前先清空对象属性数组
$this->data = array();
if ($data) {
foreach ($data as $name => $value) {
if ($name != '_className') {
$this->data[$name] = $value;
}
}
}
}
/**
* 设置master key
* @param string $masterKey
*/
public function setMasterkey($masterKey){
$this->masterKey = $masterKey;
}
/**
* 重设对象的属性
* @param array $data
*/
public function cleanData()
{
//每次使用前先清空对象属性数组
$this->data = array();
}
/**
* 所有的请求都通过这个方法发送
* @param $args
*/
protected function sendRequest($args, $apiVersion = 1)
{
$c = curl_init();
curl_setopt($c, CURLOPT_TIMEOUT, 30);
curl_setopt($c, CURLOPT_USERAGENT, 'bmob-php-library/1.0');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLINFO_HEADER_OUT, true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, $args['method']);
//支持SSL
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);
if( 2 == $apiVersion ){
$url = $this->_bmobUrlTwo . $args['sendRequestUrl'];
} else {
$url = $this->_bmobUrl . $args['sendRequestUrl'];
}
//Users的方法
$header = array(
'Content-Type: application/json',
'X-Bmob-SDK-Type: php',
'X-bmob-Application-Id: ' . $this->_bmobAppid,
'X-bmob-REST-API-Key: ' . $this->_bmobRestkey,
);
if (substr($args['sendRequestUrl'], 0, 5) == 'users') {
if (isset($args['sessionToken'])) {
//需要传入token, 用于更新删除的操作
array_push($header, 'X-Bmob-Session-Token:'.$args['sessionToken']);
} elseif (isset($args['masterKey'])) {
//需要传入X-Bmob-Master-Key
array_push($header, 'X-Bmob-Master-Key:'.$args['masterKey']);
} else {
}
} elseif (substr($args['sendRequestUrl'], 0, 7) == 'classes') {
} elseif (strpos($args['sendRequestUrl'], "updateUserPassword") !== false) {
//对象的方法
array_push($header, 'X-Bmob-Session-Token:'.$args['sessionToken']);
} elseif (strpos($args['sendRequestUrl'], "roles") !== false && $args['method'] == "DELETE") {
//对象的方法
array_push($header, 'X-Bmob-Session-Token:'.$args['sessionToken']);
} elseif (strpos($args['sendRequestUrl'], "apps") !== false) {
//对象的方法
} elseif (strpos($args['sendRequestUrl'], "schemas") !== false) {
//对象的方法
} else {
}
if( $this->bmobSessionToken ){
array_push($header, 'X-Bmob-Session-Token:'.$this->bmobSessionToken);
}
if( $this->masterKey ){
array_push($header, 'X-Bmob-Master-Key:'.$this->masterKey);
}
curl_setopt($c, CURLOPT_HTTPHEADER, $header);
// var_dump($url);
// print_r($header);
//生成post data
if ($args['method'] == 'PUT' || $args['method'] == 'POST') {
$postData = $args['data'];
if (strpos($args['sendRequestUrl'], "files") === false || strpos($args['sendRequestUrl'], "files")>0) { //非上传文件的操作把body内容变为json
$postData = json_encode($args['data']);
}
// echo "postdata:".$postData;
curl_setopt($c, CURLOPT_POSTFIELDS, $postData);
}
//生成查询的条件
if ($args['method'] == 'GET' && isset($args['condition']) && $args['condition']) {
foreach ($args['condition'] as $con) {
list($key, $value) = explode("=", $con);
$args['urlParams'][$key] = $value;
}
}
if ($args['sendRequestUrl'] == 'login') {
$urlParams = http_build_query($args['data'], '', '&');
$url = $url . '?' . $urlParams;
}
if (array_key_exists('urlParams', $args)) {
if( $args['sendRequestUrl'] == "cloudQuery" ) {
$url = $url . '?bql=' .urlencode($args['urlParams']['bql']);
if( isset($args['urlParams']['values']) ) {
$url = $url . '&values=' .urlencode($args['urlParams']['values']);
}
}else {
$urlParams = http_build_query($args['urlParams'], '', '&');
$url = $url . '?' . $urlParams;
}
}
curl_setopt($c, CURLOPT_URL, $url);
$response = curl_exec($c);
// echo "response_code:".$response;
if (!$response) {
trigger_error(curl_error($c));
}
$responseCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
$expectedCode = array('200', '201');
return $this->checkResponse($args,$response, $responseCode, $expectedCode);
}
/**
* 生成特殊的数据类型
* @param string $type
* @param array $params
*/
protected function dataType($type, $params)
{
if ($type != '') {
switch ($type) {
case 'date':
$return = array(
"__type" => "Date",
"iso" => date("c", strtotime($params))
);
break;
case 'geopoint':
$return = array(
"__type" => "GeoPoint",
"latitude" => floatval($params[0]),
"longitude" => floatval($params[1])
);
break;
case 'increment':
$return = array(
"__op" => "Increment",
"amount" => $params[0]
);
break;
case 'deleteField':
$return = array(
"__op" => "Delete",
);
break;
case 'addArray':
$return = array(
"__op" => "Add",
"objects" => $params,
);
break;
case 'updateArray':
$return = array(
"__op" => "AddUnique",
"objects" => $params,
);
break;
case 'delArray':
$return = array(
"__op" => "Remove",
"objects" => $params,
);
break;
case 'addRelPointer':
$data = array();
foreach ($params as $param) {
$key = $param[0];
$data[$key] = array(
"__type" => "Pointer",
"className" => $param[1],
"objectId" => $param[2],
);
}
return $data;
break;
case 'updateRelPointer':
return array(
"__type" => "Pointer",
"className" => $params[1],
"objectId" => $params[2],
);
break;
case 'addRelRelation':
$data = array();
foreach ($params as $param) {
$data[] = array(
"__type" => "Pointer",
"className" => $param[0],
"objectId" => $param[1],
);
}
$return = array(
"__op" => "AddRelation",
"objects" => $data,
);
break;
case 'removeRelation':
$data = array();
foreach ($params as $param) {
$data[] = array(
"__type" => "Pointer",
"className" => $param[0],
"objectId" => $param[1],
);
}
$return = array(
"__op" => "RemoveRelation",
"objects" => $data,
);
break;
default:
$return = false;
break;
}
return $return;
}
}
/**
* 抛出异常
* @param $msg
* @param $code
*/
protected function throwError($msg, $code = 0)
{
throw new BmobException($msg, $code);
}
/**
* 检查返回值
* @param string $response
* @param array $responseCode
* @param array $expectedCode
*/
private function checkResponse($args, $response, $responseCode, $expectedCode)
{
if (!in_array($responseCode, $expectedCode)) {
$error = json_decode($response, true);
$msg = isset($error['error']) ? $error['error'] : "";
$code = isset($error['code']) ? $error['code'] : 0;
$this->throwError($msg, $code);
} else {
//check for empty return
if ($response == '{}') {
return true;
} else {
$decodeResponse = json_decode($response);
//把云端代码返回值从result中剥离出来
if (isset($decodeResponse->result)) {
$tradeNo = "";
//订单接口,要把订单号返回
if("POST" == $args["method"] && "pay" == $args["sendRequestUrl"]) {
$tradeNo = $decodeResponse->out_trade_no;
}
$decodeResponse = $decodeResponse->result;
if("POST" == $args["method"] && "pay" == $args["sendRequestUrl"]) {
$decodeResponse->tradeNo = $tradeNo;
}
}
return $decodeResponse;
}
}
}
}
?>

View File

@@ -0,0 +1,102 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobRole extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 创建角色
* @param array $data 参数
*/
public function createRole($data)
{
if (!empty($data)) {
//重设对象的属性
$this->cleanData();
$this->data = $data;
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'roles',
'data' => $this->data,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 获取角色
* @param $id id
*/
public function getRole($id)
{
if (!empty($id)) {
$sendRequest = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => 'roles/' . $id,
));
return $sendRequest;
} else {
$this->throwError('id不能为空');
}
}
/**
* 更新角色
* @param $id id
*/
public function updateRole($id, $field, $op, $data)
{
if (!empty($id) && !empty($field) && !empty($op) && !empty($data)) {
$this->data[$field] = array("__op" => $op, "objects" => $data);
$sendRequest = $this->sendRequest(array(
'method' => 'PUT',
'data' => $this->data,
'sendRequestUrl' => 'roles/' . $id,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 删除角色
* @param $id id
* @param $sessionToken sessionToken
*/
public function deleteRole($id, $sessionToken)
{
if (!empty($id) && !empty($sessionToken)) {
$sendRequest = $this->sendRequest(array(
'method' => 'DELETE',
'data' => $this->data,
'sessionToken' => $sessionToken,
'sendRequestUrl' => 'roles/' . $id,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
}
?>

View File

@@ -0,0 +1,114 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobSchemas extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 获取Schemas的信息
* @param $masterKey Master-Key
* @param $schemaName schemaName的名称
* @param $data
*/
public function getSchemas($masterKey, $schemaName="")
{
if (!empty($masterKey)) {
$url="";
if( $schemaName ) {
$url="schemas/" . $schemaName;
} else {
$url= "schemas" ;
}
$sendRequest = $this->sendRequest(array(
'X-Bmob-Master-Key' => $masterKey,
'method' => 'GET',
'sendRequestUrl' => $url,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* create Schemas
* @param $masterKey Master-Key
* @param $schemaName schemaName的名称
* @param $data
*/
public function createSchemas($masterKey, $schemaName, $data)
{
if (!empty($masterKey) && !empty($schemaName) && !empty($data)) {
$sendRequest = $this->sendRequest(array(
'X-Bmob-Master-Key' => $masterKey,
'method' => 'POST',
'data' => $data,
'sendRequestUrl' => "schemas/" . $schemaName,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* update Schemas
* @param $masterKey Master-Key
* @param $schemaName schemaName的名称
* @param $data
*/
public function updateSchemas($masterKey, $schemaName, $data)
{
if (!empty($masterKey) && !empty($schemaName) && !empty($data)) {
$sendRequest = $this->sendRequest(array(
'X-Bmob-Master-Key' => $masterKey,
'method' => 'PUT',
'data' => $data,
'sendRequestUrl' => "schemas/" . $schemaName,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* delete Schemas
* @param $masterKey Master-Key
* @param $schemaName schemaName的名称
*/
public function deleteSchemas($masterKey, $schemaName)
{
if (!empty($masterKey) && !empty($schemaName)) {
$sendRequest = $this->sendRequest(array(
'X-Bmob-Master-Key' => $masterKey,
'method' => 'DELETE',
'sendRequestUrl' => "schemas/" . $schemaName,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
}
?>

View File

@@ -0,0 +1,67 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobSms extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 发送短信验证码
* @param $mobile 发送的手机号
*/
public function sendSmsVerifyCode($mobile, $template="")
{
if (!empty($mobile)) {
if( $template ){
$data = array("mobilePhoneNumber" => $mobile, "template"=>$template);
} else {
$data = array("mobilePhoneNumber" => $mobile);
}
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'data' => $data,
'sendRequestUrl' => 'requestSmsCode',
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 验证短信验证码
* @param $mobile 发送的手机号
* @param $verifyCode 短信验证码
*/
public function verifySmsCode($mobile, $verifyCode)
{
if (!empty($mobile) && !empty($verifyCode)) {
$data = array("mobilePhoneNumber" => $mobile);
$sendRequest = $this->sendRequest(array(
'method' => 'POST',
'data' => $data,
'sendRequestUrl' => 'verifySmsCode/' . $verifyCode,
));
return $sendRequest;
} else {
$this->throwError('参数不能为空');
}
}
}
?>

View File

@@ -0,0 +1,35 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser batch对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobTimestamp extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 获取服务器时间
*/
public function getTimestamp()
{
$sendRequest = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => "timestamp",
));
return $sendRequest;
}
}
?>

View File

@@ -0,0 +1,292 @@
<?php
include_once 'BmobRestClient.class.php';
/**
* BmobUser User对象类
* @author karvinchen
* @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
*/
class BmobUser extends BmobRestClient
{
public function __construct($class = '')
{
parent::__construct();
}
/**
* 用户注册
* @param array $data 需要传入的参数
*/
public function register($data = array())
{
$this->cleanData();
if (!empty($data)) {
$request = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'users',
'data' => $data
));
return $request;
} else {
$this->throwError('输入参数不能为空');
}
}
/**
* 用户登录, 其中username和password为必填字段
* @param string $username 用户名, 必填
* @param string $password 密码, 必填
*/
public function login($username, $password)
{
if (!empty($username) || !empty($password)) {
$request = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => 'login',
'data' => array(
'username' => $username,
'password' => $password
)
));
return $request;
} else {
$this->throwError('用户名和密码不能为空');
}
}
/**
* 用手机号登录, 其中mobilePhoneNumber和smsCode为必填字段
* @param string $mobilePhoneNumber 手机号
* @param string $smsCode 验证码
*/
public function loginByMobile($mobilePhoneNumber, $smsCode)
{
if (!empty($mobilePhoneNumber) || !empty($smsCode)) {
$request = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'users',
'data' => array(
'mobilePhoneNumber' => $mobilePhoneNumber,
'smsCode' => $smsCode
)
));
return $request;
} else {
$this->throwError('手机号和验证码不能为空');
}
}
/**
* 获取用户的信息
* @param string $userId 用户id, 必填
*/
public function get($userId = 0, $condition = array())
{
if ($userId) {
//获取某个用户的信息
$request = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => 'users/' . $userId,
));
return $request;
} else {
//获取所有用户的信息
$request = $this->sendRequest(array(
'method' => 'GET',
'sendRequestUrl' => 'users',
'condition' => $condition,
));
return $request;
}
}
/**
* 更新用户的信息
* @param string $userId 用户id, 必填
* @param string $sessionToken 在用户登录或注册后获取, 必填
* @param array $data 需要更新的用户属性
*/
public function update($userId, $sessionToken, $data = array())
{
if (!empty($userId) || !empty($sessionToken)) {
if ($data) {
$request = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => 'users/' . $userId,
'sessionToken' => $sessionToken,
'data' => $data
));
} else {
$this->throwError('请输入需要更新的属性');
}
return $request;
} else {
$this->throwError('用户id和sessionToken不能为空');
}
}
/**
* 通过MasterKey更新用户的信息
* @param string $userId 用户id, 必填
* @param string $masterKey 后台应用密钥中的Master Key
* @param array $data 需要更新的用户属性
*/
public function updateByMasterKey($userId, $masterKey, $data = array())
{
if (!empty($userId) || !empty($masterKey)) {
if ($data) {
$request = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => 'users/' . $userId,
'masterKey' => $masterKey,
'data' => $data
));
} else {
$this->throwError('请输入需要更新的属性');
}
return $request;
} else {
$this->throwError('用户id和masterKey不能为空');
}
}
/**
* 请求重设密码,前提是用户将email与他们的账户关联起来
* @param string $email
*/
public function requestPasswordReset($email)
{
if (!empty($email)) {
$request = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'requestPasswordReset',
'data' => array("email" => $email)
));
return $request;
} else {
$this->throwError('email is required for the requestPasswordReset method');
}
}
/**
* 删除用户
* @param string $userId
* @param string $sessionToken
*/
public function delete($userId, $sessionToken)
{
if (!empty($userId) || !empty($sessionToken)) {
$request = $this->sendRequest(array(
'method' => 'DELETE',
'sendRequestUrl' => 'users/' . $userId,
'sessionToken' => $sessionToken
));
return $request;
} else {
$this->throwError('用户id和sessionToken不能为空');
}
}
/**
* 删除用户
* @param string $userId
* @param string $masterKey
*/
public function deleteByMasterKey($userId, $masterKey)
{
if (!empty($userId) || !empty($masterKey)) {
$request = $this->sendRequest(array(
'method' => 'DELETE',
'sendRequestUrl' => 'users/' . $userId,
'masterKey' => $masterKey
));
return $request;
} else {
$this->throwError('用户id和masterKey不能为空');
}
}
/**
* 使用短信验证码进行密码重置
* @param string $oldPassword 旧密码
* @param string $newPassword 新密码
*/
public function resetPasswordBySmsCode($smsCode, $newPassword)
{
if (!empty($newPassword) || !empty($smsCode)) {
$request = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => 'resetPasswordBySmsCode/' . $smsCode,
'data' => array("password" => $newPassword)
));
return $request;
} else {
$this->throwError('密码和短信验证码不能为空');
}
}
/**
* 用户输入一次旧密码做一次校验,旧密码正确才可以修改为新密码
* @param string $userId id
* @param string $sessionToken sessionToken
* @param string $oldPassword 旧密码
* @param string $newPassword 新密码
*/
public function updateUserPassword($userId, $sessionToken, $oldPassword, $newPassword)
{
if (!empty($oldPassword) || !empty($newPassword) || !empty($userId) || !empty($sessionToken)) {
$request = $this->sendRequest(array(
'method' => 'PUT',
'sendRequestUrl' => 'updateUserPassword/' . $userId,
'sessionToken' => $sessionToken,
'data' => array("oldPassword" => $oldPassword, "newPassword" => $newPassword)
));
return $request;
} else {
$this->throwError('参数不能为空');
}
}
/**
* 请求验证Email
* @param string $email email
*/
public function requestEmailVerify($email)
{
if (!empty($email)) {
$request = $this->sendRequest(array(
'method' => 'POST',
'sendRequestUrl' => 'requestEmailVerify',
'data' => array("email" => $email)
));
return $request;
} else {
$this->throwError('email不能为空');
}
}
}
?>

View File

@@ -0,0 +1,204 @@
<?php
include_once 'lib/BmobObject.class.php';
include_once 'lib/BmobUser.class.php';
include_once 'lib/BmobBatch.class.php';
include_once 'lib/BmobFile.class.php';
include_once 'lib/BmobImage.class.php';
include_once 'lib/BmobRole.class.php';
include_once 'lib/BmobPush.class.php';
include_once 'lib/BmobPay.class.php';
include_once 'lib/BmobSms.class.php';
include_once 'lib/BmobApp.class.php';
include_once 'lib/BmobSchemas.class.php';
include_once 'lib/BmobTimestamp.class.php';
include_once 'lib/BmobCloudCode.class.php';
include_once 'lib/BmobBql.class.php';
try {
/*
* bmobObject 的例子
*/
$bmobObj = new BmobObject("GameScore","sdf2332sddfdsdf");
// $res=$bmobObj->create(array("playerName"=>"game","score"=>20)); //添加对象
// $res=$bmobObj->get("bd89c6bce9"); // 获取id为bd89c6bce9的对象
$res=$bmobObj->get(); // 获取所有对象
// $res=$bmobObj->update("bd89c6bce9", array("score"=>60,"playerName"=>"game")); //更新对象bd89c6bce9, 任何您未指定的key都不会更改,所以您可以只更新对象数据的一个子集
// $res=$bmobObj->delete("bd89c6bce9"); //删除对象bd89c6bce9
// $res=$bmobObj->get("",array('where={"playerName":"game"}','limit=2')); //对象的查询,这里是表示查找playerName为"game"的对象,只返回2个结果
// $res=$bmobObj->increment("bd89c6bce9","score",array(-2)); //id为bd89c6bce9的field score数值减2
// $res=$bmobObj->increment("bd89c6bce9","score",array(2)); //id为bd89c6bce9的field score数值加2
// $res=$bmobObj->deleteField("ZS5wHHHV","score"); //在一个对象中删除一个字段
// $res=$bmobObj->addArray("list",array("person1","person2")); //在对象字段list中添加数组数据
// $res=$bmobObj->updateArray("ZS5wHHHV","list",array("person3","person2")); //修改对象id为"ZS5wHHHV"中数组字段list的数组
// $res=$bmobObj->deleteArray("ZS5wHHHV","list",array("person3","person2")); //删除对象id为"ZS5wHHHV"中数组字段list的数组
//数据关联
//添加关联关系
//在字段添加一行记录并在game添加一个关联关系指向Game对象, 其id为Vn7r999S
// $res=$bmobObj->addRelPointer(array(array("game","Game","Vn7r999S"), array("game1","Game","Vn7r999S")));
//在字段添加一行记录并在opponents添加多个关联关系指向Player对象
// $res=$bmobObj->addRelRelation("opponents",array(array("Player","30BRpppy"),array("Player","g5s7EEEV")));
//修改对象的关联数据指向Game对象, 其id为Vn7r999S
// $res=$bmobObj->updateRelPointer("794030b43a", "game", "Game", "Vn7r999S");
//修改对象的一对多的关联数据
// $res=$bmobObj->updateRelRelation("ce7f6de5c2", "opponents", array(array("Player","30BRpppy"), array("Player","g5s7EEEV")));
//删除对象的关联数据
// $res=$bmobObj->deleteRelation("ce7f6de5c2", "opponents", array(array("Player","30BRpppy"), array("Player","g5s7EEEV")));
////批量操作
// $bmobBatch = new BmobBatch();
// $data=array(
// array(
// "method"=>"POST",
// "path"=>"/1/classes/GameScore",
// "body"=>array(
// "score"=>1337,
// "playerName"=>"Sean Plott",
// ),
// ),
// array(
// "method"=>"POST",
// "path"=>"/1/classes/GameScore",
// "body"=>array(
// "score"=>1338,
// "playerName"=>"ZeroCool",
// ),
// ),
// );
// $res=$bmobBatch->batch($data);
//上传文件
/*
如果需要上传大文件,请在代码中调整php的配置:
ini_set('max_execution_time', 30); //每个PHP页面运行的最大时间值(秒)默认30秒
ini_set('max_input_time', 60); //每个PHP页面接收数据所需的最大时间默认60秒
ini_set('memory_limit', '8m'); //每个PHP页面所吃掉的最大内存默认8M
ini_set('upload_max_filesize', '2m'); //即允许上传文件大小的最大值。默认为2M
ini_set('post_max_size', '8m'); //指通过表单POST给PHP的所能接收的最大值包括表单里的所有值。默认为8M
*/
$bmobFile = new BmobFile();
//第一个参数是文件的名称,第二个参数是文件的url(可以是本地路径,最终是通过file_get_contents获取文件内容)
//返回值:{ public $cdn => string(5) "upyun" public $filename => string(7) "988.png" public $url => string(73) "http://bmob-cdn-1.b0.upaiyun.com/png/463305b840dddbf480a326d0775cc556.png" }
// $res=$bmobFile->uploadFile2("988.png","http://file.bmob.cn/M02/4A/CB/oYYBAFYu36mAAIN_AAEbMJNyjaw988.png");
// $res=$bmobFile->delete2("upyun", "http://bmob-cdn-1.b0.upaiyun.com/png/e7a0836940aa935f809ddbfd98a7ee74.png");
// // 生成缩微图
// $bmobImage = new BmobImage();
// $data=array("image"=>"http://file.bmob.cn/M00/01/49/wKhkA1OEmUmAXRToAAIAco88Nk08205940","mode"=>0, "quality"=>100, 'width'=>100);
// $res=$bmobImage->imageThumbnail($data);
// // 生成水印
// $data=array("image"=>"http://file.bmob.cn/M01/FB/94/oYYBAFVsLzaATYHUAAInI2Hg05M737.jpg","watermark"=>"http://file.bmob.cn/M01/F8/4C/oYYBAFVru0uAa0yyAAAsGVkLsy8979.jpg",
// "dissolve"=>100, 'gravity'=>"SouthWest","distanceX"=>10,"distanceY"=>10);
// $res=$bmobImage->imagesWatermark($data);
//角色的例子
$bmobRole = new BmobRole();
// $res = $bmobRole->createRole(array("name"=>"Mo1derators", "ACL"=>array("*"=>array("read"=>true,"write"=>true)))); //创建角色
// $res = $bmobRole->getRole("dcf9ad7d2e"); //获取角色
// $data=array(
// array(
// "__type"=>"Pointer",
// "className"=>"_User",
// "objectId"=>"WXHsFFFd",
// ),
// );
// $res = $bmobRole->updateRole("d4642acf90", "users", "AddRelation", $data); //更改角色
// $res = $bmobRole->deleteRole("d4642acf90", "d365d5834061d9f6805047131893ae13"); //删除角色
////推送的例子
// $bmobPush = new BmobPush();
// 添加设备表
// $res = $bmobPush->addInstallations(array("deviceType"=>"ios","deviceToken"=>"abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789","channels"=>array("Giants")));
// $res = $bmobPush->updateInstallations("fdcc6a94c6",array("injuryReports"=>true)); //更新设备表
// $res = $bmobPush->push(array("data"=>array("alert"=>"hello"))); //推送消息
////支付的例子
$bmobPay = new BmobPay();
//$res = $bmobPay->getOrder("fd343232cc6a94c6"); //查询订单
// $res =$bmobPay->webPay(0.01, "充值", "给应用充值0.01元");
////短信相关
$bmobSms = new BmobSms();
// $res = $bmobSms->sendSmsVerifyCode("131xxxxxxxx", "注册模板"); //发送短信验证码
// $res = $bmobSms->verifySmsCode("131xxxxxxxx","028584"); //发送短信验证码
////app相关
// $bmobApp = new BmobApp();
// $res = $bmobApp->getApp("h611115@126.com", "111111"); //获取全部app的信息
// $res = $bmobApp->getApp("h611115@126.com", "111111", "85b5xxxxxxxx9e59a795da547c68e6"); //获取app id 为"85b56934cce1129e59a795da547c68e6"的信息
// $res = $bmobApp->createApp("h611115@126.com", "111111", array("appName"=>"myapp111")); //创建一个名为"myapp111"的app
// $res = $bmobApp->updateApp("h611115@126.com", "111111", "330xxxxxxxxx578d1f923126547bea5", array("appName"=>"myapp11122")); //修改一个名为"myapp111"的app
//// schemas相关
$bmobSchemas = new BmobSchemas();
// $res = $bmobSchemas->getSchemas("e09fb5cbb5b825c78989504604c0dcff"); //获取表Game的信息
// $data=array(
// "className" => "City",
// "fields" => array(
// "name" => array(
// "type"=>"String",
// ),
// ),
// );
// $res = $bmobSchemas->createSchemas("e09fb5cbb5bxxxxxxxx9504604c0dcff", "City", $data); //创建表“City”并添加字段“name”
// $data=array(
// "className" => "City",
// "fields" => array(
// "name" => array(
// "type"=>"String",
// "__op"=>"Delete"
// ),
// ),
// );
// $res = $bmobSchemas->updateSchemas("e09fb5cbb5bxxxxxxxx9504604c0dcff", "City", $data); //在表“City”中删除字段“name”
// $res = $bmobSchemas->deleteSchemas("e09fb5cbb5bxxxxxxxx9504604c0dcff", "City"); //删除表“City”
//// 时间戳相关
// $bmobTimestamp = new BmobTimestamp();
// $res = $bmobTimestamp->getTimestamp(); //获取服务器时间
//// bql相关
$bmobBql = new BmobBql();
// $res = $bmobBql->query(array('bql=select * from GameScore where name=? limit ?,? order by name','values=["dennis", 0, 100]'));
// $res = $bmobBql->query(array('bql'=>'select * from GameScore where score=11'));
// $res = $bmobBql->query(array('bql'=>'select * from GameScore where score=?', 'values'=>'[11]'));
/*
* bmobUser 的例子
*/
$bmobUser = new BmobUser();
// $res = $bmobUser->register(array("username"=>"cooldude117", "password"=>"p_n7!-e8", "phone"=>"415-392-0202", "email"=>"bmobtest111@126.com")); //用户注册, 其中username和password为必填字段
// $res = $bmobUser->register(array("mobilePhoneNumber"=>"131xxxxxxxx", "smsCode"=>"502845")); //用户注册, mobilePhoneNumber 就是手机号码,而 smsCode 是使用 请求短信验证码API发送到用户手机上的 6位验证码字符串。如果是新用户且不传入 username默认用户名将是手机号码。
// $res = $bmobUser->login("test111@qq.com","111111"); //用户登录, 第一个参数为用户名,第二个参数为密码
// $res = $bmobUser->loginByMobile("131xxxxxxxx","745399"); //用手机号登录, 其中mobilePhoneNumber和smsCode为必填字段
// $res = $bmobUser->get("415b8fe99a"); // 获取id为415b8fe99a用户的信息
// $res = $bmobUser->get(); // 获取所有用户的信息
// $res=$bmobUser->get("",array('where={"age":11}'));
// $res = $bmobUser->update("415b8fe99a", "050391db407114d9801c8f2788c6b25a", array("phone"=>"02011111")); // 更新用户的信息
// $res = $bmobUser->updateByMasterKey("0290813a89", "e09fb5cbb5b825c78989504604c0dcff", array("phone"=>"02011122")); // 通过masterKey更新用户的信息
// $res = $bmobUser->requestPasswordReset("bmobtest111@126.com"); // 请求重设密码,前提是用户将email与他们的账户关联起来
// $res = $bmobUser->delete("415b8fe99a", "050391db407114d9801c8f2788c6b25a"); // 删除id为415b8fe99a的用户, 第一参数是用户id, 第二个参数为sessiontoken,在用户登录或注册后获取, 必填
// $res = $bmobUser->deleteByMasterKey("0290813a89", "e09fb5cbb5b825c78989504604c0dcff"); // 通过masterKey删除用户
// $res = $bmobUser->resetPasswordBySmsCode("111111", "134554"); // 使用短信验证码进行密码重置
// $res = $bmobUser->updateUserPassword("WXHsFFFd", "d365d5834061d9f6805047131893ae13" , "111111", "111111"); //用户输入一次旧密码做一次校验,旧密码正确才可以修改为新密码
// $res = $bmobUser->requestEmailVerify("h622222225@126.com"); //请求验证Email
/*
* BmobCloudCode 的例子
*/
// $cloudCode = new BmobCloudCode('getMsgCode'); //调用名字为getMsgCode的云端代码
// $res = $cloudCode->get(array("name"=>"bmob")); //传入参数name其值为bmob
var_dump($res);
} catch (Exception $e) {
echo $e;
}

33
Swoft_BackEndApi/app/bean.php Executable file
View File

@@ -0,0 +1,33 @@
<?php
use App\Common\DbSelector;
use Swoft\Db\Pool;
use Swoft\Http\Server\HttpServer;
use Swoft\Task\Swoole\TaskListener;
use Swoft\Task\Swoole\FinishListener;
use Swoft\Rpc\Client\Client as ServiceClient;
use Swoft\Rpc\Client\Pool as ServicePool;
use Swoft\Rpc\Server\ServiceServer;
use Swoft\Http\Server\Swoole\RequestListener;
use Swoft\WebSocket\Server\WebSocketServer;
use Swoft\Server\Swoole\SwooleEvent;
use Swoft\Db\Database;
use Swoft\Redis\RedisDb;
return [
'logger' => [
'flushRequest' => true,
'enable' => false,
'json' => false,
],
'httpServer' => [
'class' => HttpServer::class,
'port' => 18306
],
'httpDispatcher' => [
// Add global http middleware
'middlewares' => [
\App\Http\Middleware\CorsMiddleware::class
],
]
];

View File

@@ -0,0 +1 @@
1b33a23c-7810-4eca-a322-aa781f6736f0

View File

@@ -0,0 +1,3 @@
<?php
// Composer autoload
require_once dirname(__DIR__) . '/vendor/autoload.php';

14
Swoft_BackEndApi/bin/swoft Executable file
View File

@@ -0,0 +1,14 @@
#!/usr/bin/env php
<?php declare(strict_types=1);
// Bootstrap
require_once __DIR__ . '/bootstrap.php';
\Swoole\Runtime::enableCoroutine();
Swoole\Coroutine::set([
'max_coroutine' => 300000,
]);
// Run application
(new \App\Application())->run();

Some files were not shown because too many files have changed in this diff Show More