簡體   English   中英

將 Laravel 與微服務一起使用:是否可以在沒有數據庫的情況下使用 eloquent?

[英]Using Laravel with microservices: Is it possible to use eloquent without a database?

我們正在使用微服務架構。 laravel服務有2組數據:

  • 容納管理員的數據庫。
  • 以及管理員可以訪問的所有其他數據,這些數據通過 GRPC 調用其他服務來實現。

我想要像 eloquent (也許是 API 資源?)之類的東西來構建數據/關系,但是它不需要進行數據庫查詢來加載數據,而是需要對其他服務進行 GRPC 調用。 我正在考慮制作一個從 eloquent 延伸出來的自定義 class 並重載調用數據庫的受保護函數,但這聽起來像是一個糟糕的時刻。 如果有人有我所描述的經驗,那么您 go 的方向是什么? 什么有效? 什么沒有?

所以,我最終根本沒有使用 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;
        });

GrpcClient來自 AppServiceProvider。 這樣,如果我們想要進行查詢,我們就不必手動實例化它。

<?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(),
            ]);
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM