Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fhir Models Laravel Package

ardenexal/fhir-models

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ardenexal/fhir-models
    

    Ensure your project uses PHP 8.0+ (check composer.json constraints).

  2. First Use Case: Parsing FHIR JSON

    use Ardenexal\Fhir\Models\FhirResource;
    
    $json = file_get_contents('patient-example.json');
    $resource = FhirResource::fromJson($json);
    
    // Access fields (e.g., Patient resource)
    $name = $resource->getName()[0]->getFamily();
    
  3. Key Classes to Know

    • FhirResource: Base class for all FHIR resources (e.g., Patient, Observation).
    • FhirBundle: For handling FHIR Bundles (collections of resources).
    • FhirFactory: Static helper for creating resources from JSON/XML.
  4. Where to Look First

    • Documentation: Check the PHP-FHIR-Tools repo for FHIR spec context.
    • Source: Browse src/Models/ for resource-specific classes (e.g., Patient.php).
    • Tests: tests/ folder for usage examples (if available).

Implementation Patterns

1. Parsing and Validation

  • Read-Only Parsing The package is designed for read-only operations. Validate input JSON/XML before parsing:

    $json = '{"resourceType": "Patient", "id": "example"}';
    $resource = FhirResource::fromJson($json);
    
    if (!$resource->isValid()) {
        throw new \InvalidArgumentException("Invalid FHIR resource: " . $resource->getErrors());
    }
    
  • Type-Safe Access Use getter methods (e.g., getId(), getName()) instead of direct property access. For nested fields:

    $telecom = $resource->getTelecom()[0];
    $phone = $telecom->getValue(); // Returns "tel:+1-555-555-5555"
    

2. Working with Bundles

  • Bundle Processing Parse a FHIR Bundle (e.g., from a search response):

    $bundle = FhirBundle::fromJson($bundleJson);
    foreach ($bundle->getEntry() as $entry) {
        $resource = $entry->getResource();
        if ($resource instanceof \Ardenexal\Fhir\Models\Patient) {
            // Process Patient
        }
    }
    
  • Filtering Resources Use instanceof checks to filter resources by type:

    $patients = array_filter($bundle->getEntry(), fn($entry) =>
        $entry->getResource() instanceof \Ardenexal\Fhir\Models\Patient
    );
    

3. Integration with Laravel

  • Service Container Binding Bind the factory for dependency injection:

    // config/app.php
    'bindings' => [
        \Ardenexal\Fhir\Models\FhirFactory::class => fn() => new \Ardenexal\Fhir\Models\FhirFactory(),
    ],
    
  • Request Parsing (API Endpoints) Parse FHIR payloads in Laravel controllers:

    use Illuminate\Http\Request;
    
    public function store(Request $request) {
        $resource = FhirResource::fromJson($request->getContent());
        // Process or store $resource
    }
    
  • Database Storage (Read-Only Limitation) Since the package is read-only, pair it with a database library (e.g., Eloquent) to persist data:

    $patientData = $resource->toArray(); // Convert to array for storage
    Patient::create($patientData);
    

4. Extending Functionality

  • Custom Resource Handling Extend FhirResource for domain-specific logic:

    class CustomPatient extends \Ardenexal\Fhir\Models\Patient {
        public function isActive() {
            return $this->getActive() === true;
        }
    }
    
  • Validation Rules Use Laravel’s validation to pre-check FHIR payloads:

    $validated = $request->validate([
        'resource' => 'required|json',
    ]);
    $resource = FhirResource::fromJson($validated['resource']);
    

Gotchas and Tips

Pitfalls

  1. Read-Only Constraint

    • Issue: The package does not support modifying resources. Attempting to set properties (e.g., $resource->id = 'new-id') will fail silently or throw errors.
    • Workaround: Use toArray() to modify data, then recreate the resource or store in a database.
  2. No FHIR Version Flexibility

    • Issue: The package likely defaults to FHIR R4 (check the original php-fhir-tools repo). Parsing older versions (e.g., DSTU2) may fail.
    • Workaround: Validate JSON against the FHIR schema validator before parsing.
  3. Nested Resource Handling

    • Issue: Complex nested resources (e.g., Composition.section.entry) require chained getters. Typos in property names (e.g., getSection() vs. getSections()) will return null.
    • Tip: Use IDE autocompletion or dump the resource structure:
      dd(get_object_vars($resource));
      
  4. Performance with Large Bundles

    • Issue: Parsing large FHIR Bundles (e.g., 1000+ resources) may consume significant memory.
    • Tip: Stream JSON or process entries in chunks:
      $bundle = FhirBundle::fromJson($json, true); // Stream parsing (if supported)
      

Debugging Tips

  1. Validate JSON First Use a tool like FHIR Validator to catch malformed input before parsing.

  2. Check Resource Type Always verify the resource type before casting:

    if (!$resource instanceof \Ardenexal\Fhir\Models\Patient) {
        throw new \RuntimeException("Expected Patient resource");
    }
    
  3. Enable Strict Typing Add this to composer.json to catch type issues early:

    "config": {
        "platform": {
            "php": "8.0"
        }
    }
    

Extension Points

  1. Custom Serialization Override toArray() or toJson() in a child class for custom output:

    class ApiPatient extends \Ardenexal\Fhir\Models\Patient {
        public function toApiArray() {
            return [
                'id' => $this->getId(),
                'name' => $this->getName()[0]->getFamily(),
            ];
        }
    }
    
  2. Event Listeners Trigger events when parsing resources (e.g., log invalid fields):

    $resource = FhirResource::fromJson($json);
    if (!$resource->isValid()) {
        event(new \App\Events\FhirValidationFailed($resource->getErrors()));
    }
    
  3. Caching Parsed Resources Cache parsed resources to avoid reprocessing identical JSON:

    $cacheKey = md5($json);
    $resource = cache()->remember($cacheKey, now()->addHours(1), fn() =>
        FhirResource::fromJson($json)
    );
    

Config Quirks

  • No Built-in Config The package has no configuration file. All behavior is hardcoded (e.g., FHIR version, validation rules).

    • Tip: Extend the package or wrap it in a service class to add config options.
  • Namespace Conflicts The package uses Ardenexal\Fhir\Models. Ensure your project doesn’t have naming conflicts (e.g., a Models namespace in your app).

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky