Convert remote api response data into laravel model

Overview

laravel remote model

Create remote driver to convert remote api request into laravel model.

中文文档

日本語文書

overview

Install the version between laravel5.5-laravel8, and then install the quick service package.

composer require windawake/laravelremodel dev-master

First execute the command php artisan laravelremodel:example-models to copy the three files OrderDetailRemote.php, OrderRemote.php, and ProductRemote.php under the ./vendor/windawake/laravelremodel/examples/Models directory to the app folder.

├── app
│   ├── Console
│   │   └── Kernel.php
│   ├── Exceptions
│   │   └── Handler.php
│   ├── Http
│   │   ├── Controllers
│   │   ├── Kernel.php
│   │   └── Middleware
│   ├── Models
│   │   ├── OrderDetailRemote.php
│   │   ├── OrderRemote.php
│   │   └── ProductRemote.php

Then execute php ./vendor/windawake/laravelremodel/examples/sqlite/build.php to create the SQLite database file test.db

Add the configuration of sqlite and adds testsuite of Remote in phpunit.xml.

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>

        <testsuite name="Remote">
            	<directory>./vendor/windawake/laravelremodel/tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="MAIL_DRIVER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value="./test.db"/>
    </php>
</phpunit>

Finally, run the test command ./vendor/bin/phpunit --testsuit=Remote The running results are shown below, 18 orm examples have passed in the test.

root@DESKTOP-VQOELJ5:/web/linux/php/laravel/laravel58# ./vendor/bin/phpunit --testsuit=Remote
PHPUnit 7.5.20 by Sebastian Bergmann and contributors.

..................                                                18 / 18 (100%)

Time: 208 ms, Memory: 20.00 MB

OK (18 tests, 21 assertions)

features

  1. The app backend code does not need to be refactored, and it gradually connects with the basic service interface of the business.
  2. Support lazy loading, avoiding 1+n query api.
  3. Supports join tables, join tables, native SQL queries, aggregate queries, sub-queries, etc. Almost all laravel orm features can be used.
  4. The laravel service container writing method is used, so the query compiler and distributed transaction methods can be customized. (Distributed transactions have not yet been implemented).

principle

The api interface of the basic service is encapsulated into an ORM. The model at the back end of the app is just a virtual model, which is a mirror image of the business basic service model. For example, the purple ProductModel is a mirror image, but OrderLogic uses it almost the same as the white ProductModel. What are the benefits of doing this? All the features of the laravel model can be reused. Because many packages now do a lot of new functions for the model, it is a pity not to use them.

how to use

Create a new ProductRemote class that inherits the RemoteModel class.

<?php
namespace App\Models;

use Laravel\Remote2Model\RemoteModel;

class ProductRemote extends RemoteModel {
    const CREATED_AT = null;
    const UPDATED_AT = null;

    protected $primaryKey = 'pid';
    protected $table = 'product';
    public $timestamps = false;

    public function getHandle()
    {
        /**
         * @var RemoteTool
         */
        $remoteTool = app('laravelremodel.tool');
        $condition = $remoteTool->queryToCondition($this->queryBuilder);

        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', 'http://127.0.0.1:18001/api/product', [
            'query' => [
                'condition' => $condition
            ],
        ]);
        $json = $res->getBody()->getContents();
        
        $list = json_decode($json, true);
        return $list;
    }
    
}

Here is an example of querying getHandle. By default, 5 methods are provided: getHandle, updateHandle, insertGetIdHandle, deleteHandle and existsHandle. After inheriting the RemoteModel class, without defining these methods such as getHandle, it will use the db drive by default, just like the normal Model class.

model method similar to mysql syntax purpose
getHandle select Query list, query details, query aggregation operations (count, max, etc.)
updateHandle update Update record
insertGetIdHandle insert Insert record
deleteHandle delete Delete record
existsHandle select Determine whether it exists
You might also like...
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

Easily capture every incoming request and the corresponding outgoing response in your Laravel app.
Easily capture every incoming request and the corresponding outgoing response in your Laravel app.

Easily capture every incoming request and the corresponding outgoing response in your Laravel app. This package is designed to work only with the Lara

This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

A Laravel response helper methods.
A Laravel response helper methods.

A Laravel response helper methods. The package respond provides a fluent syntax to form array or json responses.

Provides a powerful error response system for Laravel
Provides a powerful error response system for Laravel

Laravel Exceptions Laravel Exceptions was created by, and is maintained by Graham Campbell, and provides a powerful error response system for both dev

Laravel Custom Response Messages from Passport Oauth2 Server

This is a sample repository showing how to install Oauth2 server using Laravel's passport package and customize its responses.

Laravel Response Formatter
Laravel Response Formatter

I created this package to make it easier to format the response from a controller. I have used this package in my projects and I hope you enjoy it!

[READ ONLY] WordPress-specific Comment data model

Comments WordPress-specific Comment Data Model Install Via Composer composer require pop-wp-schema/comments Development The source code is hosted on t

Releases(v1.0.1)
Owner
张子彬
研究c语言,php,gcc
张子彬
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
Easily validate data attributes through a remote request

Laravel Remote Rule Easily validate data attributes through a remote request. This package allows you to define a subset of custom rules to validate a

H-FARM Innovation 27 Nov 20, 2022
Simplest Slugify for PHP to convert string into a slug.

Simplest Slugify for PHP to convert string into a slug. Documentation You can find the detailed documentation here in Slugify Documentation. Contribut

Pharaonic 6 Mar 12, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

Michael Rubel 15 Oct 29, 2022
Simple and ready to use API response wrapper for Laravel.

Laravel API Response Simple Laravel API response wrapper. Installation Install the package through composer: $ composer require obiefy/api-response Re

Obay Hamed 155 Dec 14, 2022
Turn any Eloquent model into a list!

Listify Turn any Eloquent model into a list! Description Listify provides the capabilities for sorting and reordering a number of objects in a list. T

Travis Vignon 138 Nov 28, 2022
Simple package to handle response properly in your API.

Simple package to handle response properly in your API. This package uses Fractal and is based on Build APIs You Won't Hate book.

Optania 375 Oct 28, 2022
Laravel Philips Hue package to control your lights with remote support

Laravel Philips Hue ?? Introduction I created this package for my company Ploi (https://ploi.io) to control our office lights. For example, when we re

Dennis Smink 81 Aug 11, 2022