API Reference - Grazulex/laravel-arc GitHub Wiki
🔍 API Reference
Overview
This comprehensive API reference covers all classes, methods, and attributes available in Laravel Arc DTOs.
Core Classes
LaravelArcDTO Class
The main base class for creating Data Transfer Objects.
use Grazulex\Arc\LaravelArcDTO;
class UserDTO extends LaravelArcDTO
{
#[Property(type: 'string', required: true)]
public string $name;
}
Constructor
__construct(array $data = [])
Create a new DTO instance with data validation and casting.
$dto = new UserDTO([
'name' => 'John Doe',
'email' => '[email protected]'
]);
Magic Methods
__get(string $name): mixed
Get property value directly.
echo $dto->name; // Direct property access
__set(string $name, mixed $value): void
Set property value with validation.
$dto->name = 'Jane Doe'; // Direct property assignment
__isset(string $name): bool
Check if property exists and is set.
if (isset($dto->name)) {
// Property exists and is set
}
Data Access Methods
get(string $key): mixed
Get an attribute from the DTO.
$value = $dto->get('name');
set(string $key, mixed $value): static
Set an attribute with validation and casting.
$dto->set('name', 'John Doe');
has(string $key): bool
Check if the DTO has an attribute.
if ($dto->has('name')) {
// Attribute exists
}
Conversion Methods
toArray(): array
Convert DTO to array.
$array = $dto->toArray();
toJson(int $options = 0): string
Convert DTO to JSON.
$json = $dto->toJson();
$prettyJson = $dto->toJson(JSON_PRETTY_PRINT);
Validation Methods
static rules(): array
Get validation rules for the DTO.
$rules = UserDTO::rules();
// Returns: ['name' => 'required|string|max:255', ...]
Factory Methods (DTOFactoryTrait)
static fake(): static
Generate a DTO with fake data.
$fakeUser = UserDTO::fake();
static fakeMany(int $count): array
Generate multiple DTOs with fake data.
$users = UserDTO::fakeMany(5);
static factory(): DTOFactory
Get factory instance for advanced fake data generation.
$user = UserDTO::factory()
->with('name', 'John Doe')
->fake()
->create();
Property Attribute
The main attribute for defining DTO properties.
use Grazulex\Arc\Attributes\Property;
#[Property(/* parameters */)]
public string $property_name;
Parameters
Core Parameters
-
type
(string) - The property type- Values:
'string'
,'int'
,'float'
,'bool'
,'array'
,'date'
,'enum'
,'nested'
,'collection'
- Required: Yes
- Values:
-
required
(bool) - Whether the property is required- Default:
true
- Default:
-
default
(mixed) - Default value for the property- Can be a scalar value, array, or enum case
-
validation
(string) - Laravel validation rules- Example:
'required|email|max:255'
- Example:
-
class
(string) - Target class for complex types- Required for
enum
,nested
, andcollection
types - Example:
UserStatus::class
for enums,AddressDTO::class
for nested
- Required for
Transformation Parameters
transform
(array) - Array of transformer classes to apply- Example:
[TrimTransformer::class, LowercaseTransformer::class]
- Example:
Date-Specific Parameters
-
format
(string) - Date format for date properties- Example:
'Y-m-d'
- Example:
-
timezone
(string) - Timezone for date properties- Example:
'Europe/Brussels'
- Example:
-
immutable
(bool) - Use CarbonImmutable for date properties- Default:
false
- Default:
Examples
// Basic string property
#[Property(type: 'string', required: true, validation: 'max:100')]
public string $name;
// Numeric property with constraints
#[Property(type: 'int', required: true, validation: 'min:0|max:120', default: 0)]
public int $age;
// Email property
#[Property(type: 'string', required: true, validation: 'email')]
public string $email;
// Enum property
#[Property(type: 'enum', class: UserStatus::class)]
public UserStatus $status;
// Array property
#[Property(type: 'array', required: false, default: [])]
public array $tags;
// Property with transformation
#[Property(
type: 'string',
required: true,
transform: [TrimTransformer::class, LowercaseTransformer::class]
)]
public string $email;
// Nested DTO property
#[Property(type: 'nested', class: AddressDTO::class, required: false)]
public ?AddressDTO $address;
// Collection property
#[Property(type: 'collection', class: OrderItemDTO::class, required: false, default: [])]
public array $items;
// Date property
#[Property(type: 'date', required: false, format: 'Y-m-d')]
public ?Carbon $birth_date;
Transformation System
Built-in Transformers
Laravel Arc includes several built-in transformer classes:
TrimTransformer
- Remove leading/trailing whitespaceLowercaseTransformer
- Convert to lowercaseUppercaseTransformer
- Convert to uppercaseHashTransformer
- Hash values (configurable algorithm)SlugTransformer
- Convert to URL-friendly slug
Custom Transformers
Implement custom transformers using the TransformerInterface
:
use Grazulex\Arc\Contracts\TransformerInterface;
class CustomTransformer implements TransformerInterface
{
public function transform(mixed $value): mixed
{
// Custom transformation logic
return $transformedValue;
}
}
// Usage
#[Property(
type: 'string',
transform: [CustomTransformer::class]
)]
public string $custom_field;
Validation System
Automatic Rule Generation
Validation rules are automatically generated based on property attributes:
// This property:
#[Property(type: 'string', required: true, validation: 'max:100')]
public string $name;
// Generates these rules:
[
'name' => 'required|string|max:100'
]
Rule Mapping
Property Type | Generated Rules |
---|---|
string |
string |
int |
integer |
float |
numeric |
bool |
boolean |
array |
array |
date |
date |
enum |
Validation based on enum values |
nested |
Validates nested DTO |
collection |
Validates array of DTOs |
Custom Validation
Use Laravel validation rules in the validation
parameter:
#[Property(
type: 'string',
required: true,
validation: 'required|string|unique:users,email|max:255'
)]
public string $email;
Exceptions
InvalidDTOException
Thrown when DTO validation or type casting fails.
use Grazulex\Arc\Exceptions\InvalidDTOException;
try {
$dto = new UserDTO(['email' => 'invalid-email']);
} catch (InvalidDTOException $e) {
echo $e->getMessage();
// Get specific error details if available
$field = $e->getField() ?? 'unknown';
$value = $e->getValue() ?? null;
}
Console Commands
Laravel Arc provides several Artisan commands for DTO management:
make:dto
Generate DTOs from models or create new ones.
# Basic DTO generation
php artisan make:dto User
# Generate from existing model
php artisan make:dto User --model=User
# With relations and validation
php artisan make:dto User --model=User --with-relations --with-validation
# Custom path
php artisan make:dto User --path=app/Data
dto:analyze
Analyze DTO structure and properties.
# Analyze specific DTO
php artisan dto:analyze UserDTO
# Analyze with verbose output
php artisan dto:analyze UserDTO --verbose
# JSON output
php artisan dto:analyze UserDTO --json
dto:validate
Validate data against DTO definition.
# Validate JSON data
php artisan dto:validate UserDTO --data='{"name":"John","email":"[email protected]"}'
# Interactive validation
php artisan dto:validate UserDTO
# Validate from file
php artisan dto:validate UserDTO --file=test-data.json
Key Interfaces
TransformerInterface
Interface for custom transformers.
use Grazulex\Arc\Contracts\TransformerInterface;
class CustomTransformer implements TransformerInterface
{
public function transform(mixed $value): mixed
{
// Custom transformation logic
return $transformedValue;
}
}
DTOInterface
Interface implemented by all DTOs.
use Grazulex\Arc\Contracts\DTOInterface;
class CustomDTO implements DTOInterface
{
// Must implement required methods
public function toArray(): array;
public function toJson(int $options = 0): string;
// ... other required methods
}
Type System
Supported Types
Type | PHP Type | Description |
---|---|---|
string |
string |
String values |
int |
int |
Integer values |
float |
float |
Floating point values |
bool |
bool |
Boolean values |
array |
array |
Array values |
date |
Carbon\Carbon |
Date/time values |
enum |
UnitEnum|BackedEnum |
PHP 8+ enums |
nested |
Custom DTO | Nested DTO objects |
collection |
array |
Array of DTO objects |
Type Casting
Laravel Arc automatically casts values to the appropriate PHP types:
// String to int
$dto = new UserDTO(['age' => '30']); // '30' becomes 30 (int)
// String to enum
$dto = new UserDTO(['status' => 'active']); // 'active' becomes UserStatus::ACTIVE
// Array to nested DTO
$dto = new UserDTO([
'address' => ['street' => '123 Main St'] // Array becomes AddressDTO
]);
Best Practices
1. Property Organization
Group related properties together and use consistent naming:
class UserDTO extends LaravelArcDTO
{
// Identity
#[Property(type: 'string', required: true)]
public string $name;
#[Property(type: 'string', required: true, validation: 'email')]
public string $email;
// Profile
#[Property(type: 'int', required: false, validation: 'min:0|max:150')]
public ?int $age;
// Relationships
#[Property(type: 'nested', class: AddressDTO::class, required: false)]
public ?AddressDTO $address;
}
2. Validation Strategy
Use specific validation rules that match your business logic:
#[Property(type: 'string', required: true, validation: 'email|max:254')]
public string $email;
#[Property(type: 'string', required: true, validation: 'min:8|regex:/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/')]
public string $password;
3. Nullable Properties
Use nullable types for optional properties:
#[Property(type: 'string', required: false)]
public ?string $description = null;
#[Property(type: 'nested', class: ProfileDTO::class, required: false)]
public ?ProfileDTO $profile = null;
4. Default Values
Provide sensible defaults where appropriate:
#[Property(type: 'bool', required: false, default: true)]
public bool $is_active = true;
#[Property(type: 'array', required: false, default: [])]
public array $tags = [];
#[Property(type: 'enum', class: UserRole::class, default: UserRole::USER)]
public UserRole $role = UserRole::USER;
🔍 Complete API Reference - This covers all the main classes, methods, and features available in Laravel Arc DTOs. For detailed examples and usage patterns, see the Examples Gallery.