maxkut / model-entities
json对象的包装器
v0.3.0
2020-04-10 16:08 UTC
Requires
- php: ^7.2
- ext-json: *
- illuminate/contracts: 5.5.*|5.6.*|5.7.*|5.8.*|6.*|7.*
- nesbot/carbon: 1.*|2.*
Requires (Dev)
- phpunit/phpunit: ^8.4
- symfony/var-dumper: ^4.3
This package is auto-updated.
Last update: 2024-09-11 02:06:15 UTC
README
#PHP 对 json
数据的封装
用于更易于管理和文档化的json字段模型数据或不同API的响应数据的工作
###安装 composer require maxkut/model-entities
###概念 该库包含两个抽象类 \Entities\Entity
和 \Entities\EntityCollection
,它们包含辅助方法来对最终对象的属性进行类型化。记录创建的类的属性非常重要。这样您就不会忘记某个对象有哪些属性。以下示例中,Settings类的属性已在PhpDoc中进行了记录。此外,您的ide将为您提供提示。
###示例
// Как пример сложных json полей модели App\Models\User namespace App\Models\Entities\User; use Entities\Entity; /** * Class Settings * @property bool $property1 * @property int $property2 * @property array $property3 */ class Settings extends Entity { /** * @var bool $strictParams - если true, * то любые свойства, которые не объявлены в $attributes, $casts или для него нет акцессора/мутатора * вызовут исключение Entities\Exceptions\NotDefinedPropertyException */ public $strictParams = true; protected $attributes = [ 'property1' => null, 'property2' => null, 'property3' => null, ]; protected $casts = [ 'property1' => 'bool', 'property2' => 'int', 'property3' => 'array', ]; } /////////////////////////////////////////// /// На примере моделей Eloquent ORM /// надо создать методы преобразования (акцессор и мутатор) для этого поля namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\Entities\User\Settings; class User extends Model { //... protected function getSettingsAttribute($value){ return Settings::make($value); } protected function setSettingsAttribute($value){ $this->attributes['settings'] = Settings::make($value)->toJson(); } }