Giter Site home page Giter Site logo

dumkaaa / extservice Goto Github PK

View Code? Open in Web Editor NEW
0.0 3.0 2.0 15 KB

Bitrix CMS library for work with external services with default Bitrix HTTPClient (request & response)

PHP 100.00%
bitrix bitrix-cms bitrix-module http-client http-requests hacktoberfest

extservice's Introduction

ExtService

Библиотека для работы с внешними сервисами (под Битрикс)

Установка

С использованием composer.

В файле composer.json в секцию require добавить:

"dumkaaa/ExtService": "dev-master"

в секцию repositories:

      {
        "type": "git",
        "url": "https://github.com/dumkaaa/ExtService"
      }

Выполнить команду

composer install

Настройка

В общем случае для каждого сервиса должен быть создан файл Service.php в папке /lib/model/название_сервиса, который должен лежать в своем пространстве имен в подпространстве app\model и расширять базовый класс BaseService.

Базовое использование

namespace app\model\virtu;

use ExtService\BaseService;

class Service extends BaseService
{    

    /**
     * Получение списка стран
     * @param Request $request Объект запроса
     * @return \ExtService\Interfaces\Response Объект ответа
     */
    protected function getCountry(Request $request)
    {
        $request->setParams([
            'method'  => 'GET',
            'url'     => $this->_url . '/ClassifierFeature/Classifier.dat',
            'headers' => [
                'x-vs-parameters' => json_encode([
                    "productId" => $this->getProductId($request),
                    "fieldList" => $this->getFieldList(),
                    "id" => "693d344f-6efd-4e88-9c45-7e293f94d64d"
                ])
            ]
        ]);
        return $this->query($request, new Response());
    }

Дополнительные параметры

При необходимости, возможно расширять и переопределять не только базовый класс сервиса, но и классы запроса (должен расширять ExtService\BaseRequest) и ответа (ExtService\Response).

В запросах и ответах можно управлять заголовками, cookies, устанавливать методы, другими данными, а также читать данные и обрабатывать ошибки.

Полная структура в таком случае будет выглядеть примерно следующим образом:

/lib
├── название_сервиса
|   ├── Service.php 
|   ├── Request.php
|   └── Response.php
└── название_другого_сервиса
    ├── Service.php 
    ├── Request.php
    └── Response.php

Также, для удобства можно использовать bxpimple для удобного подключения сервисов:

Locator::$item->registerFactories([

	'VirtuService' => function ($c) {
		$model = new \app\model\virtu\Service();
		return $model;
	},

	'VirtuRequest' => function ($c) {
		$model = new \app\model\virtu\Request();
		return $model;
	},

]);

и вызова их, в последствии:

$virtu = \bxpimple\Locator::$item->get('VirtuService');

extservice's People

Contributors

dumkaaa avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.