webpractik / api
该软件包已被 废弃 并不再维护。没有建议的替代软件包。
轻松创建ajax响应
1.2
2019-04-08 14:23 UTC
Requires
- composer/installers: >=1.0.22 <2.0
This package is auto-updated.
Last update: 2022-10-11 23:20:35 UTC
README
Bitrix CMS中编写API的简单界面。
将所有处理程序放置在/api/空间,使开发者能够编写统一的处理程序。
为那些厌倦了编写组件处理程序、在doc_root中产生大量文件(如/ajax文件夹)以及尚未实施laravel/symphony路由器的人提供的解决方案。
⚠️ 已弃用
建议使用
- Bitrix原生控制器
- Laravel/Symphony控制器
本模块适用于旧项目或向后兼容。
在Bitrix CMS中安装
composer require webpractik/api
- 在管理员面板中安装模块
安装过程
在安装过程中
- 在DocRoot根目录添加
api-router.php
- 在
urlrewrite.php
中安装/api/
路由 - 在
local/components/webpractik/api/
中安装组件
编写处理程序
- 在本地webpractik:api组件中注册
$arUrlTemplates
路由
class ApiRouterExtended extends \Webpractik\Api\ApiRouter { public $sefVariables = []; public $arUrlTemplates = [ '\MySite\Lk\Response\Resubmit' => 'application/resubmit/', ]; public $arLoadModules = [ 'webpractik.main' ]; }
在模块中传递需要自动加载的模块(@todo fixme)
- 添加处理程序 \MySite\Lk\Response\Resubmit,它继承自 \Webpractik\Api\Response
方法 | 描述 |
---|---|
public function handler(){} | 主要逻辑 |
public function validate() | 验证逻辑。当 |
public $method | GET/POST - 期望的请求类型 |
public $request | \Bitrix\Main\HttpRequest https://dev.1c-bitrix.ru/api_d7/bitrix/main/request/index.php |
public $response | \Webpractik\Api\JsonResponse |
JSON示例
{ "status": true, "errors": [] }
JsonResponse接口
方法 | 描述 |
---|---|
addError($strError) | 添加错误 |
addParam($name, $value) | 向JSON添加参数 |
setSuccess/setFail | 设置状态为true/false |
send | json_encode + die() |
sendSuccess | setSuccess + send() |
sendFail($strError) | addError($strError) + send() |
haveErrors() | true |
getErrors() | 数组 |
getResponse() | 数组 |
示例
class FormRegister extends \Webpractik\Api\Response { public function handler() { if (!$this->register()) { $this->response->sendFail('Ошибка регистрации') } $this->response ->addParam('password', $this->password) ->setSuccess() ->send(); } public function validate() { if (!$this->request->getPost('email')) { $this->response->addError('Не введен email'); } if (!$this->request->getPost('login')) { $this->response->addError('Не введен логин'); } return $this->response->haveErrors(); } }
这是一个抽象示例,仅为了展示功能。