将 Laravel 模型映射到外部 API 的最佳方法是什么?
外部 API 具有以下实体:
在我的本地数据库上,我也有类似的实体:
每当在外部 API 上修改某些信息时,我都需要将某些信息存储在数据库中,基本上是将 API 映射到数据库。
为此推荐的方法或设计模式是什么?
我尝试过的:
1- 直接在模型中
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany(Post::class);
}
public function createPost(array $data, array $attributes)
{
$postId = Http::post('.../post', $data)->json('data.postId');
$this->posts()->create(array_merge([
'post_id' => $postId,
], $attributes));
}
}
///
$user->createPost([
'title' => 'foo',
'content' => 'bar'
], [
'publish_date' => now()
])
我不太喜欢在模型内部调用API,并且存在命名冲突的问题,比如更新一个帖子,我在帖子模型中调用什么方法,
$post->updatePost()
?感觉不对。
2 - 使用服务:
class UserService
{
public function __construct(
private User $user
) {
}
public function createPost(array $data, array $attributes = [])
{
$postId = Http::post('.../post', $data)->json('data.postId');
$this->user->posts()->create(array_merge([
'post_id' => $postId,
], $attributes));
}
}
///
$userService = new UserService($user);
$userService->createPost([
'title' => 'foo',
'content' => 'bar'
], [
'publish_date' => now()
])
服务方法感觉更干净,但我想知道是否有任何其他设计模式我可以遵循上述方法更好/更干净。
有人实施过类似的东西吗?如果有,你是怎么做到的?您是否将您的包装类称为服务,或者它是包装器/适配器/装饰器?
您想要实现的是通过代码同步数据。例如,Mysql 副本在 aws 中就是这样做的。在这种情况下,您的本地数据库将是副本(读取),而 api 数据库将是写入数据库。这比你通过 api 调用同步数据要好......
但无论如何。如果你真的想要或必须走这条路,那么你可以使用观察者,如果你所有的创建、更新和删除都不是通过大量查询完成的(RESTful api 无论如何都没有大量查询)。
作为旁注,您也可以查看一下:有没有办法处理 laravel 或 lumen 8、9、10 中任何表的过滤和聚合?