torann/remote-model

一个类似于 eloquent 的模型,用于 Laravel 框架。

0.2.1 2017-01-31 16:44 UTC

This package is auto-updated.

Last update: 2024-09-08 09:49:35 UTC


README

此模型提供了一个类似于 eloquent 的基类,可以用于构建远程 API 的自定义模型。

安装

使用 composer 安装

$ composer require torann/remote-model

客户端

自定义请求方法

要在模型中实现自定义 API 请求方法,简单扩展 Torann\RemoteModel\Model 类并在应用模型中使用该扩展模型。

示例

<?php

namespace App;

use APIClient;
use Torann\RemoteModel\Model;

class BaseModel extends Model
{
   /**
    * Make request through API.
    *
    * @return mixed
    */
   protected function request($endpoint = null, $method, $params)
   {
       $endpoint = $endpoint ? $endpoint : $this->endpoint;

       $results = APIClient::$method($endpoint, $params);

       return $results ? $this->newInstance($results) : null;
   }
}

客户端包装方法

$client = new Client();

$client->{ENDPOINT}()->{METHOD}();

ENDPOINT 模型类的“蛇形小写”,复数名称将用作端点名称,除非显式指定了另一个名称。在模型顶部使用 protected $endpoint = 'users';,这与 Laravel 模型的 $table 变量类似。

METHOD 这是端点上的操作。可以是包装类提供的任何内容。

示例客户端包装

<?php

namespace PackageName\Api;

use PackageName\Api\Exception\BadMethodCallException;
use PackageName\Api\Exception\InvalidArgumentException;

class Client
{
    /**
     * The HTTP client instance used to communicate with API.
     *
     * @var HttpClient
     */
    private $httpClient;

    /**
     * Instantiate a new client.
     */
    public function __construct()
    {
        $this->httpClient = new HttpClient;
    }

    /**
     * @param string $name
     *
     * @throws InvalidArgumentException
     *
     * @return ApiInterface
     */
    public function api($name)
    {
        switch ($name)
        {
            case 'users':
                $api = new Endpoints\Users($this);
                break;

            case 'reviews':
                $api = new Endpoints\Reviews($this);
                break;

            default:
                throw new InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name));
        }

        return $api;
    }

    /**
     * @param string $name
     *
     * @throws InvalidArgumentException
     *
     * @return ApiInterface
     */
    public function __call($name, $args)
    {
        try {
            return $this->api($name);
        }
        catch (InvalidArgumentException $e) {
            throw new BadMethodCallException(sprintf('Undefined method called: "%s"', $name));
        }
    }
}

示例客户端包装端点

这只是作为一个示例。

<?php

namespace PackageName\Api\Endpoints;

use PackageName\Api\Client;

class Users
{
    /**
     * The client.
     *
     * @var \PackageName\Api\Client
     */
    protected $client;

    /**
     * @param \PackageName\Api\Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * Register a user.
     *
     * @param  array $params
     *
     * @return array
     */
    public function add(array $params)
    {
        return $this->client->post('users', $params);
    }

    /*
     * Update user data
     *
     * @param  array $params
     *
     * @return object
     */
    public function update(array $params)
    {
        return $this->client->patch('users/self', $params);
    }

    /**
     * Get extended information about a user by its id.
     *
     * @param  string $user_id
     *
     * @return array
     */
    public function find($user_id)
    {
        return $this->client->get('users/'.rawurlencode($user_id));
    }
}

客户端服务提供者

在检索任何数据之前必须设置 API 客户端。要设置客户端,请使用静态方法 Model::setClient

以下是一个示例,说明如何通过服务提供者设置客户端。

<?php

namespace App\Providers;

use Torann\RemoteModel\Model;
use PackageName\API\Client;
use Illuminate\Support\ServiceProvider;

class ApiServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        Model::setClient($this->app['apiclient']);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('apiclient', function () {
            return new Client(); // API Client
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return string[]
     */
    public function provides()
    {
        return [
            'apiclient'
        ];
    }
}

示例模型

<?php

namespace App;

use DateTime;
use Torann\RemoteModel\Model as BaseModel;

class User extends BaseModel
{
    protected $hidden = [
        'password'
    ];

    protected $casts = [
        'age' => 'integer'
    ];

    public function save()
    {
        return API::post('/items', $this->attributes);
    }

    public function setBirthdayAttribute($value)
    {
        $this->attributes['birthday'] = strtotime($value);
    }

    public function getBirthdayAttribute($value)
    {
        return new DateTime("@$value");
    }

    public function getAgeAttribute($value)
    {
        return $this->birthday->diff(new DateTime('now'))->y;
    }
}

使用模型

$item = new User([
    'name' => 'john'
]);

$item->password = 'bar';

echo $item; // {"name":"john"}

变更日志

0.1.0

  • 修复父 ID 错误

0.0.1

  • 首次发布