php - 将 Laravel 与微服务一起使用:是否可以在没有数据库的情况下使用 eloquent?
问题描述
我们正在使用微服务架构。laravel 服务有 2 组数据:
- 容纳管理员的数据库。
- 以及管理员可以访问的所有其他数据,这些数据来自对其他服务的 GRPC 调用。
我想要像 eloquent(也许是API 资源?)这样的东西来构建数据/关系,但是它不需要进行数据库查询来加载数据,而是需要对其他服务进行 GRPC 调用。我正在考虑创建一个自定义类,该类从 eloquent 扩展并重载调用数据库的受保护函数,但这听起来像是一个糟糕的时刻。如果有人有做过我所描述的事情的经验,那么您的方向是什么?什么有效?什么没有?
解决方案
所以,我最终根本没有使用 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(),
]);
});
推荐阅读
- python-3.x - dlib RuntimeError 在我的 xml 中带有浮点数
- c - 为什么我不能访问指向堆栈数组指针的指针?
- php - 未捕获的异常:“未收到来自使用 GSM 调制解调器发送 SMS 的调制解调器的响应”
- android - 如何获取指纹安卓设备的名称?
- c++ - 包括没有完整路径的库
- javascript - 如何仅使用 Nest.js 框架中的依赖注入容器?
- java - 如何点击按钮立即申请
- laravel - Laravel Blade - @extends 从 html 字符串 - 有可能吗?
- kubernetes - Kubernetes:如果 nodePort 是随机的,如何访问服务?
- python - 如果它大于所述日期,如何绕过此错误以使列为零?“ TypeError:无效的类型提升”