• Stars
    star
    206
  • Rank 190,504 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 4 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Base library for your PHP SDKs

PHP SDK

Latest Version PHP Version tests Total Downloads

A framework for building simple to use SDKs in PHP 8.0 and above.

Installation

composer require juststeveking/php-sdk

Purpose

The purpose of this package is to provide a consistent and interoperable way to build PHP SDKs to work with 3rd party APis.

Usage

Working with this library is relatively simple, and an example can be found in the demo and examples directories.

The basic concept is that you will need to provide:

  • PSR-17 Request and Response Factory.
  • PSR-7 Messages

Inside this library we are using a PSR-18 implementation allowing you to connect the pieces together under the hood and provide SDK functionality using a replaceable set of components.

I highly recommend either:

To handle the Http PSRs as they are lightweight and designed to be simple and PSR compliant.

Building the SDK

To begin with we need to be able to build our SDK, to do this we can either use the constructor or use the static build method.:

SDK constructor

To create an SDK instance; simply pass through a uri, a Http Client that uses auto-discovery to find the available PSR-18 client, an authentication strategy, and an instance of the Container.

use JustSteveKing\HttpAuth\Strategies\BasicStrategy;
use JustSteveKing\HttpSlim\HttpClient;
use JustSteveKing\UriBuilder\Uri;
use JustSteveKing\PhpSdk\SDK;
use PHPFox\Container\Container;

$sdk = new SDK(
    uri: Uri::fromString('https://www.domain.com'),
    client: HttpClient::build(),
    strategy: new BasicStrategy(
        authString: base64_encode("username:password")
    ),
    container: Container::getInstance(),
);

SDK build

To use the static build method, the only requirement is to pass through a uri. If you want to set a custom Authentication Strategy you can also pass this through otherwise it will default to a Null Strategy.

use JustSteveKing\UriBuilder\Uri;
use JustSteveKing\PhpSdk\SDK;

$sdk = SDK::build(
    uri: 'https://www.domain.com',
);

Adding Resources to our SDK

Each Resource you add to your SDK requires 2 things:

  • Implements ResourceContract
  • Extends AbstractResource

Your resource should look like this:

use JustSteveKing\PhpSdk\Contracts\ResourceContract;
use JustSteveKing\PhpSdk\Resources\AbstractResource;

class TestResource extends AbstractResource implements ResourceContract
{
    protected string $path = '/test';

    public static function name(): string
    {
        return 'tests';
    }
}

The Path property allows you to set the uri path for this resource, and the static name method is how this resource is stored on the container.

To add this resource to the SDK, you can use the add method:

$sdk->add(
    name: TestResource::name(),
    resource: TestResource::class,
);

Internally this will add the resource onto container and inject the SDK into the constructor, allowing you to access the Http Client and other aspects of the SDK.

Calling a Resource

Now that you have added a resource to the SDK, you are able to call it using the PHP magic __get method:

$response = $sdk->tests->get();

This will return a nice PSR-7 response for you to work with inside your SDK code.

API

The below documents the API of the PHP-SDK:

SDK class

Your own SDK class should extend the base SDK class for easier integration.

  • __construct(URI $uri, HttpClient $client, Container $container, null|StrategyInterface $strategy) The SDK constructor.
  • static build(string $uri, null|StrategyInterface $strategy = null, null|Container = null): SDK This static build method allows the defaults to be set for you to get an SDK quickly.
  • add(string $name, string $resource): self The add method allows you to add resources onto the SDK container, and checks that the resource being passed extends the AbstractResource and implements the ResourceContract.
  • uri(): Uri Return the setup instance of UriBuilder that is being used, to allow you to manipulate the URI string.
  • client(): HttpClient Return the setup instance of the HttpClient that is being used, to allow you to enforce any changes that are required.
  • strategy(): StrategyInterface Returns the setup instance of the Authentication Strategy that is being used, to allow you to export the auth header array.
  • container(): Container Returns the setup instance of the Container, to allow you to bind make and work with the container directly should it be required.
  • __get(string $name): ResourceContract Returns a build instance of the called Resource if it has been added to the container.

AbstractResource class

Your resources must all extend the Abstract Resource class.

  • __construct(SDK $sdk, null|string $path = null, string $authHeader = 'Bearer', array $with = [], array $relations = [], bool $strictRelations = false, null|string $load = null) The Resource constructor.
  • sdk(): SDK Return the setup instance of the SDK that has been passed through to the resource.
  • getWith(): array Return an array of relations to sideload onto the request.
  • getLoad(): string|null Return a string or null if a specific resource identifier has been passed in.
  • load(string|int $identifier): self The load method allows you to set a specific resource identifier to look for on an API.
  • uri(Uri $uri): self The uri method allows you to completely override the URI Builder on the SDK.
  • client(HttpClient $http): self The client method allows you to completely override the Http Client on the SDK.
  • strategy(StrategyInterface $strategy): self The strategy method allows you to completely override the Authentication Strategy on the SDK.
  • loadPath(): self Loads the path from the resource into to URI builder on the SDK.
  • get(): ResponseInterface Performs a GET request to the resource path, to return a list of resources.
  • find(string|int $identifier): ResponseInterface Performs a GET request to the resource path with an identifier appended to it, to return a single resource.
  • create(array $data): ResponseInterface Performs a POST request to the resource path, to create a new single resource.
  • update($identifier, array $data, string $method = 'patch'): ResponseInterface Performs either a PATCH or PUT request to the resource path with an identifier appended to it, to update a single resource.
  • delete(string|int $identifier): ResponseInterface Performs a DELETE request to the resource path with an identifier appended to it, to remove a resource.
  • where(string $key, $value): self Builds the query parameters in a famility query builder style syntax.

ResourceContract Interface

Your resources must implement the ResourceContract interface.

  • static name(): string Returns a string representation of the resource name, to allow it to be bound the the SDK container.

It is highly recommended that you use all of these internally in your API to give you the ability to control the process.

Building an SDK

To build an SDK, you can simply extend the SDK like so:

use Demo\Resources\Server;
use JustSteveKing\HttpAuth\Strategies\NullStrategy;
use JustSteveKing\HttpSlim\HttpClient;
use JustSteveKing\PhpSdk\SDK;
use JustSteveKing\UriBuilder\Uri;
use PHPFox\Container\Container;

class MySDK extends SDK
{
    public function __construct()
    {
        parent::__construct(
            uri: Uri::fromString(
                uri: 'https://www.domain.tld',
            ),
            client: HttpClient::build(),
            container: Container::getInstance(),
            strategy: new NullStrategy()),
        );
    }

    public static function boot(): MySDK
    {
        $client = new MySDK();

        $client->add(
            name: TestResource::name(),
            resource: TestResource::class,
        );

        return $client;
    }
}

Testing

TO run the test:

composer run test

Credits

LICENSE

The MIT LIcense (MIT). Please see License File for more information.

More Repositories

1

laravel-transporter

Transporter is a futuristic way to send API requests in PHP. This is an OOP approach to handling API requests.
PHP
457
star
2

laravel-feature-flags

I recommend using laravel/pennant for any future Feature Flag needs. This package will be frozen as is with no updates planned.
PHP
174
star
3

laravel-webhooks

A simple webhook implementation for Laravel.
PHP
79
star
4

laravel-redoc

A simple API documentation package for Laravel using OpenAPI and Redoc
PHP
75
star
5

os-process

A PHP Package to work with OS processes in an OOP way.
PHP
73
star
6

LaravelPostcodes

A service wrapper around postcodes.io
PHP
73
star
7

laravel-business-process

Laravel Business Process is a simple and clean way to run business process using a Laravel Pipeline, in a structured and type-safe way.
PHP
66
star
8

laravel-data-object-tools

A set of tools to make working with Data Transfer Objects easier in Laravel
PHP
64
star
9

http-status-code

A simple class to return correct status codes for http responses.
PHP
46
star
10

passwordless-auth

A passwordless auth approach in Laravel using Signed URLs
PHP
41
star
11

shop

Online Shop build in Laravel
PHP
39
star
12

laravel-envoyer-sdk

A simple to use PHP class to work with the Laravel Envoyer API
PHP
36
star
13

laravel-stoplight-elements

A simple API documentation package for Laravel using OpenAPI and Stoplight Elements
PHP
36
star
14

laravel-skeleton

My personal Laravel skeleton application.
PHP
30
star
15

laracon-winter-2022-talk

My talk from Laracon Online WInter 2022
PHP
30
star
16

laravel-api-toolkit

A toolkit for creating APIs in Laravel
PHP
24
star
17

fluent-validation

Fluent Validation is a helper package, that allows you to use sensible defaults for your Laravel validation rules.
PHP
24
star
18

password-generator

Generate random, memorable passwords easily.
PHP
22
star
19

companies-house-laravel

A Laravel wrapper to get companies house information and validate company numbers.
PHP
21
star
20

laravel-erp

A simple to use opinionated ERP package to work with Laravel
PHP
20
star
21

uri-builder

A simple URI builder in PHP that is slightly opinionated
PHP
19
star
22

sdk-tools

A set of tools you can use to help make better SDKs.
PHP
19
star
23

ollama-php

A PHP SDK for interacting with the Ollama API.
PHP
18
star
24

todo-cli

A simple CLI application to work with the Todoist API to quickly check your own todo list
PHP
17
star
25

go-api

A simple Go API following concepts of Domain Driven Design for educational purposes.
Go
16
star
26

launchpad

A helpful Laravel package to help me get started in Laravel projects quicker.
PHP
15
star
27

laravel-nuxt

PHP
14
star
28

phponline.dev

The web application for PHP Online
PHP
13
star
29

laravel-buttondown-email

Manage Newsletters in Laravel, using the buttondown.email API
PHP
12
star
30

laravel-stubs

An opinionated version of the Laravel stubs
PHP
11
star
31

skeleton

The skeleton application for Laravel APIs
PHP
11
star
32

invoice-number

A simple to use PHP Invoice Number Generator.
PHP
10
star
33

laravel-erp-crm

A Laravel ERP Module providing CRM functionality
PHP
9
star
34

config-loader

A simple to use configuration loader for PHP.
PHP
8
star
35

dotfiles-mac

This repo is my ongoing progress for working on my personal dotfiles for my devices.
Shell
8
star
36

http-auth-strategies

A simple PHP package that is used to create different Http Auth Headers
PHP
8
star
37

talk-template

This is a template I use to bootstrap my talks, it has all the main components I need to give a good presentation that is well thought out and designed.
Svelte
8
star
38

laravel-tall-eventsourcing-example

An example of using EventSourcing and the TALL stack at the same time
PHP
7
star
39

converter

A CLI tool to turn JSON and YAML into PHP Data Objects quickly
Go
7
star
40

http-slim

A slim psr compliant http client to provide better interoperability
PHP
7
star
41

eloquent-log-driver

A Laravel Log Driver for Eloquent
PHP
7
star
42

masking-engine

A data masking engine for PHP.
PHP
7
star
43

laravel-otp-auth

A Laravel package to provide a one time password authentication flow.
PHP
6
star
44

forum

This is the repo from my Building a Forum livestreams
PHP
6
star
45

laravel-key-factory

A simple package to generate Eloquent model keys
PHP
6
star
46

castr

The cast application from my stream
PHP
6
star
47

http-helpers

A collection of helpers to use when working with HTTP.
PHP
6
star
48

school-management

An open-source School Management Application built with Laravel and Livewire
PHP
6
star
49

laravel-api-service-tutorial

PHP
6
star
50

laravel-toolkit

A simple toolkit package to help me do what I do with Laravel
PHP
6
star
51

jetstream-typescript-vue

Laravel Jetstream with Typescript Vue and Shadcn-vue
Vue
6
star
52

pulsara

A New Universe of Social Connectivity
PHP
6
star
53

tranquil-stay

The Tranquil Stay Booking System is a specialised web-based platform designed to streamline the reservation process for a single hotel.
PHP
6
star
54

laravel-erp-contracts

A package to use when building modules for the Laravel ERP package
PHP
5
star
55

LaravelCityMapper

PHP
5
star
56

nuxt-demo

A NuxtJS demo using tailwind and best practices
JavaScript
5
star
57

workflow

This package is aimed to be a simplistic PHP workflow package that works in a similar fashion to GitHub Actions.
PHP
5
star
58

crm

A Laravel CRM
PHP
5
star
59

micro

A simple to use boilerplate for Slim PHP, for APIs
PHP
5
star
60

laravel-dub

The official Dub.co Laravel integration.
PHP
5
star
61

micro-core

A collection of core components to be used within the micro boilerplate for slim framework.
PHP
4
star
62

ploi-cli

The (unofficial) Ploi CLI application
PHP
4
star
63

ParameterBag

PHP
4
star
64

gtin-php

A PHP package for validating GTIN codes for use in plain PHP and in Laravel.
PHP
4
star
65

calendar

A calendar application built in Laravel
PHP
4
star
66

Bolt-Medium

A Medium Inspired blogging theme for Bolt CMS
HTML
4
star
67

open-source-training-php

This repo is an open source training plan for developers who are interested in learning PHP and related frameworks.
4
star
68

phponline

A community platform
PHP
4
star
69

webhooks

The simplest way to start sending webhooks in PHP.
PHP
4
star
70

personal-github-actions

This repo contains some personal GitHub Actions that do cool things for me
4
star
71

learn-php

This repo is for an online presentation, that gives a gentle introduction to PHP as a language. This can be used as reference material, and is aimed to be used as is with no other downloads needed.
PHP
4
star
72

lapi

LAPI is a very opinionated Laravel template for building APIs in Laravel
PHP
3
star
73

feature-request-platform

PHP
3
star
74

go-api-problem

A simple struct in GoLang for creating API Problems in your API
Go
3
star
75

cypher-query-builder

PHP
3
star
76

BankPHP

Bank is a small and simple, but powerful, database toolkit.
PHP
3
star
77

aggregator

A news aggregator built with Vue, InertiaJS, Laravel, TailwindCSS. Using Dub.co for short-links
PHP
3
star
78

standup

A Web application for managing stand ups as a team
PHP
3
star
79

lemon-squeezy

An unofficial PHP SDK for working with the LemonSqueezy API
PHP
3
star
80

package-skeleton

A PHP Package Skeleton
3
star
81

docker-compose-slim

A simple and clean Slim setup for running with docker-compose
PHP
3
star
82

api-boilerplate

Blade
3
star
83

common-casts

A PHP package that provides common Data and Value Objects, that are Laravel castable.
PHP
3
star
84

fox

A Slim framework 3 bootstrap that is very foxy indeed
CSS
3
star
85

example-go-api

This is an example Go API from my stream on YouTube https://youtu.be/EnWIg_IZg_8
Go
3
star
86

api-starter

A Laravel starter kit for your next API.
PHP
2
star
87

juststeveking.uk-next

HTML
2
star
88

packagist-api

A dead simple API package for the Packagist API.
PHP
2
star
89

neo4j-http-adapter

PHP
2
star
90

JustSteveKing

My GitHub Profile README
2
star
91

fortify-skeleton

A Laravel skeleton repository that uses Laravel Fortify for authentication and FilamentPHP
PHP
2
star
92

amezmo-cli

A CLI tool for the Amezmo API.
PHP
2
star
93

juststeveking.uk-astro

A personal website built using Astro
Astro
2
star
94

federated-auth-service-example

An example of federated authentication as a service in Laravel
PHP
2
star
95

slack

PHP
2
star
96

laravel-mapbox-api

A Laravel package for working with the mapbox API
Shell
2
star
97

cv-builder

This is the repo for the cv-builder stream series
JavaScript
2
star
98

laravel-service

This is an example repo on how to create small/micro-services in Laravel.
PHP
2
star
99

forge-dashboard

An example repo on how to use Laravel Transporter in a Laravel application.
PHP
2
star
100

phponline.dev-new

JavaScript
2
star