achrafbardan/simple-resources

这是我的包 simple-resources-for-laravel

2.0.0 2024-05-13 17:07 UTC

This package is auto-updated.

Last update: 2024-09-13 18:01:13 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

这是一个简化资源使用的包。它用于自动猜测并将资源链接到模型。分页集合在资源中也可以自动包装。

安装

您可以通过 composer 安装此包

composer require AchrafBardan/simple-resources-for-laravel

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="simple-resources-for-laravel-config"

这是已发布配置文件的内容

return [
    "model_namespace" => "App\\Models",
    "resource_namespace" => "App\\Http\\Resources",

    /**
     * When this is set to false, you have to add the \AchrafBardan\SimpleResources\Contracts\HasResource interface to your models.
     * When set to true you can still optionally add the interface to your models, this interface will than be used instead of the guesser.
     */
    "guess_resource" => true
];

可选地,您可以使用以下命令发布视图

php artisan vendor:publish --tag="simple-resources-for-laravel-views"

用法

在返回模型或集合之前,您可以通过 ResourceFactory 传递它。资源工厂会为您找到模型、集合甚至是分页集合的资源。

use AchrafBardan\SimpleResources\ResourceFactory;
...
$resource = ResourceFactory::make($model);
return response()->json($resource);

您还可以使用辅助函数 resource,它与 ResourceFactory::make 相同

use function AchrafBardan\SimpleResources\resource;
...
$resource = resource($model);
return response()->json($resource);

它还旨在用于资源内部的子模型和集合,以下是一个示例。

// App/Http/Resources/TestResource.php
...
class TestResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'child' => resource($this->whenLoaded('child'))
        ];
    }
}

测试

composer test

贡献

请参阅 CONTRIBUTING 了解详细信息。

安全漏洞

请查看 我们的安全策略 了解如何报告安全漏洞。

鸣谢

许可证

MIT 许可证 (MIT)。请参阅 许可证文件 了解更多信息。