Custom casts allow you to transform XML elements into specific PHP classes automatically during import. The Laravel XML package supports three types of casts:
Eloquent models - Cast directly to Laravel model instances
Castable classes - Implement the Castable interface for full control
Default classes - Any class with a constructor that accepts an array
The Castable interface provides a standardized way to define how your class should be instantiated from XML data.
namespace Flowgistics\XML\Casts;interface Castable{ /** * Invoked every time this class was cast to XMLElement. * * @param array $data * @return Castable */ public static function fromCast(array $data): self;}
For complete control over object construction, implement the Castable interface. This is ideal when you need custom initialization logic or want to map XML data to specific constructor parameters.
You can add validation, transformation, or default values in your fromCast() method:
class Plant implements Castable{ public function __construct( public string $common, public string $botanical, public string $zone, public string $light, public string $price, public int $availability ) {} public static function fromCast(array $data): Castable { // You can add validation if (empty($data['COMMON'])) { throw new \InvalidArgumentException('Plant name is required'); } // Transform data as needed return new Plant( $data['COMMON'], $data['BOTANICAL'], $data['ZONE'], $data['LIGHT'], $data['PRICE'], (int) $data['AVAILABILITY'] ); }}$xml = XML::import('plants.xml') ->cast('PLANT')->to(Plant::class) ->get();// Each plant is now a typed Plant instanceforeach ($xml->PLANT as $plant) { echo "{$plant->common}: {$plant->price}\n";}
$xml = XML::import('plants.xml') ->cast('plant')->to(Plant::class) ->get();// $xml->plant is an array of Plant instancesforeach ($xml->plant as $plant) { echo $plant->common . "\n";}
You can chain casts with transformers for powerful data processing:
$xml = XML::import('notes.xml') ->cast('note')->to(Note::class) ->expect('note')->as('array') // Ensure it's always an array ->get();// $xml->note is always an array of Note modelsforeach ($xml->note as $note) { // Process each note}
Apply casts before transformers when you want to transform class instances. Apply transformers before casts when you want to filter or modify raw data first.