PHP code example of mellivora / laravel-api-caster
1. Go to this page and download the library: Download mellivora/laravel-api-caster library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mellivora / laravel-api-caster example snippets
use Mellivora\Http\Api\Entity;
use Mellivora\Http\Api\Response;
// From HTTP Response
$response = new Response($httpResponse);
$entity = Entity::from($response);
// From array data
$entity = new Entity([
'id' => 123,
'name' => 'John Doe',
'email' => '[email protected]'
]);
// Access data
echo $entity->id; // 123
echo $entity->name; // John Doe
echo $entity->email; // [email protected]
class UserEntity extends Entity
{
// Include only specific fields
protected array $;
// Rename fields
protected array $renames = [
'user_id' => 'id',
'full_name' => 'name',
];
// Append computed attributes
protected array $appends = ['display_name'];
public function getDisplayNameAttribute(): string
{
return $this->name . ' (' . $this->email . ')';
}
}
use Mellivora\Http\Api\Contracts\Castable;
use Mellivora\Http\Api\Contracts\CastsAttributes;
class MoneyCaster implements Castable
{
public static function castUsing(array $arguments): CastsAttributes
{
return new class implements CastsAttributes {
public function getCastValue(Entity $entity, string $key, $value): Money
{
return new Money($value);
}
public function fromCastValue(Entity $entity, string $key, mixed $value): int
{
return $value->getCents();
}
};
}
}
class OrderEntity extends Entity
{
protected array $casts = [
'total' => MoneyCaster::class,
];
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.