首页 > 解决方案 > 将 Laravel 与微服务一起使用:是否可以在没有数据库的情况下使用 eloquent?

问题描述

我们正在使用微服务架构。laravel 服务有 2 组数据:

我想要像 eloquent(也许是API 资源?)这样的东西来构建数据/关系,但是它不需要进行数据库查询来加载数据,而是需要对其他服务进行 GRPC 调用。我正在考虑创建一个自定义类,该类从 eloquent 扩展并重载调用数据库的受保护函数,但这听起来像是一个糟糕的时刻。如果有人有做过我所描述的事情的经验,那么您的方向是什么?什么有效?什么没有?

标签: phplaraveleloquentmicroservicesgrpc

解决方案


所以,我最终根本没有使用 eloquent。我继续使用文档说明的协议设置。但我使用路由绑定在控制器中启用类型提示:

<?php

namespace App\Providers;

use OurNamespace\GrpcClient;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use OurNamespace\Customer;
use OurNamespace\CustomerIdInput;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
        Route::bind('customer', function ($customerId) {
            $grpcClient = app(GrpcClient::class);
            $customerIdInput = new CustomerIdInput();
            $customerIdInput->setCustomerId($customerId);
            list($customer, $status) = $grpcClient->GetCustomerDetails($customerIdInput)->wait();
            if ($status->code != 0) {
                error_log('ERROR - ' . print_r($status, 1));
                return redirect()->back()->withErrors(['There was an error retrieving that customer', $status->details]);
            }
            return $customer;
        });

来自GrpcClientAppServiceProvider。这样,如果我们想要进行查询,我们就不必手动实例化它。

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use OurNamespace\GrpcClient;
use Grpc\ChannelCredentials;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('OurNamespace\GrpcClient', function ($app) {
            return new GrpcClient(env('GRPC_HOST'), [
                'credentials' => ChannelCredentials::createInsecure(),
            ]);
        });


推荐阅读