Skip to content

Profiles

Daniel Carbone edited this page Nov 22, 2026 · 3 revisions

Profiles

A FHIR profile is a StructureDefinition that constrains a base resource or element type: tightening cardinality, fixing values, binding codes, and slicing repeating elements.

Starting with php-fhir v4.2.2, this library ships generated PHP classes for several widely used R4 profile packages. Each profile class is a plain subclass of its base type that adds the profile's constraints to validation and provides typed accessors for sliced elements.

Note: Profiles are currently generated for R4 only. They live under Versions/R4/Profiles/.

Included Packages

Directory FHIR Package Version Publisher Classes
R4Core hl7.fhir.r4.core 4.0.1 HL7 Inc 48
USCore hl7.fhir.us.core 9.0.0 HL7 Cross-Group Projects 55
SDC hl7.fhir.uv.sdc.r4 4.0.0 HL7 FHIR Infrastructure 36
SmartAppLaunch hl7.fhir.uv.smart-app-launch 2.2.0 HL7 FHIR Infrastructure 6
XverR5R4 hl7.fhir.uv.xver-r5.r4 0.1.0 HL7 FHIR Infrastructure 161

XverR5R4 provides R4 profile classes, not an R5-to-R4 translation map. The cross-version translator uses separate generated maps and does not resolve a target profile from meta.profile. A copied profile URL is not proof that the target resource conforms to that profile.

Each package directory contains a PackageMap and PackageAutoloader, with profile classes nested by the hierarchy of the base type they constrain. For example:

Versions/R4/Profiles/
├── ProfileMap.php
├── ProfileAutoloader.php
├── R4Core/
│   ├── PackageMap.php
│   ├── PackageAutoloader.php
│   ├── FHIRElement/MoneyQuantity.php
│   └── FHIRResource/FHIRDomainResource/ActualGroup.php
└── USCore/
    ├── PackageMap.php
    ├── PackageAutoloader.php
    └── FHIRResource/FHIRDomainResource/USCorePatientProfile.php

Each profile class header carries a "Profile Copyright Notice" identifying the package, author, and license.

Anatomy of a Profile Class

Taking USCorePatientProfile as an example:

class USCorePatientProfile extends FHIRPatient implements ProfileTypeInterface
{
    public const PROFILE_URL = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient';
    public const PROFILE_VERSION = '9.0.0';
    public const PROFILE_NAME = 'USCorePatientProfile';
    public const PROFILE_BASE_TYPE = 'Patient';
    public const PROFILE_INVARIANTS = [ /* ... */ ];
    // ...
}
  • It extends the base type. A USCorePatientProfile is a FHIRPatient: same fields, constructor, setters, and serialization. Anything that accepts FHIRPatient accepts the profile.
  • PROFILE_INVARIANTS lists the FHIRPath invariants declared by the profile (key, severity, human description, expression). They are informational only — FHIRPath expressions are not evaluated.
  • Profile validation rules are merged with the base type's rules (see Validation).
  • Slice accessors are generated for sliced elements (see Slices).

ProfileTypeInterface

Every profile class implements ProfileTypeInterface:

Method Description
static _getProfileUrl(): string Canonical URL of the profile.
static _getProfileVersion(): null|string Version of the profile's package, or null if none.
_getProfileValidationErrors(): array Errors from profile-added or tightened rules only. Empty if conformant.

Constructing Profile Instances

Profile classes are constructed like any other type (see Constructing Types):

<?php

use DCarbone\PHPFHIRGenerated\Versions\R4\Profiles\USCore\FHIRResource\FHIRDomainResource\USCorePatientProfile;
use DCarbone\PHPFHIRGenerated\Versions\R4\Types\FHIRElement\FHIRHumanName;
use DCarbone\PHPFHIRGenerated\Versions\R4\Types\FHIRElement\FHIRIdentifier;

$patient = new USCorePatientProfile(
    id: 'patient-1',
    identifier: [new FHIRIdentifier(system: 'urn:example', value: '12345')],
    name: [new FHIRHumanName(family: 'Human', given: ['Real'])],
);

Note: Constructing a profile class does not automatically populate meta.profile. Set it yourself if the serialized output must declare conformance:

$patient->setMeta(new FHIRMeta(profile: [USCorePatientProfile::PROFILE_URL]));

Slices

Where a profile slices a repeating element, accessors are generated that return only the values matching each slice. For USCorePatientProfile, the extension element is sliced into:

$patient->getRaceExtension();               // null|FHIRExtension
$patient->getEthnicityExtension();          // null|FHIRExtension
$patient->getTribalAffiliationExtension();  // FHIRExtension[]  (max > 1)
$patient->getSexExtension();                // null|FHIRExtension
$patient->getInterpreterRequiredExtension();// null|FHIRExtension

Slices with a maximum cardinality of 1 return a single value or null; others return an array. Matching uses the discriminator declared by the profile (e.g. url for extension slices) via ValueMatcher.

Slice accessors are read-only views over the underlying field; add values with the normal addExtension() / setExtension() methods.

Profile Validation

Profile classes participate in the standard validation system. A profile's rules are combined with its base type's rules such that a profile may only narrow the base:

  • min_occurs: the larger of the two wins
  • max_occurs: the smaller of the two wins (0 means the element must be absent)
  • all other rules: the profile's value replaces the base's

Two methods are available on a profile instance:

// Everything: base type rules + profile rules, including nested child errors.
$errors = $patient->_getValidationErrors();

// Only rules the profile added or tightened. Does not descend into children.
$profileErrors = $patient->_getProfileValidationErrors();

Both return the same [field => [rule => message]] structure:

[
    'identifier' => [
        'min_occurs' => 'Field "identifier" on type "Patient" must have at least 1 elements, but it is empty',
    ],
]

Profiles introduce several rules beyond those used by base types. See Validation → Profile Validator Rules for the full list, including choice_occurs, slice_occurs, fixed_value, pattern_value, and code_binding.

Automatic Profile Resolution

When unserializing with ResourceParser, the library can inspect a resource's meta.profile and instantiate the matching profile class instead of the base type. This is off by default; enable it via UnserializeConfig:

<?php

use DCarbone\PHPFHIRGenerated\Encoding\ProfileResolutionEnum;
use DCarbone\PHPFHIRGenerated\Encoding\ResourceParser;
use DCarbone\PHPFHIRGenerated\Encoding\UnserializeConfig;
use DCarbone\PHPFHIRGenerated\Versions\R4\Version;
use DCarbone\PHPFHIRGenerated\Versions\VersionConfig;

$version = new Version(new VersionConfig(
    unserializeConfig: new UnserializeConfig(profileResolution: ProfileResolutionEnum::AUTO),
));

$json = '{
  "resourceType": "Patient",
  "meta": {"profile": ["http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient"]},
  "name": [{"family": "Human"}]
}';

$patient = ResourceParser::parse($version, $json);
// $patient is a USCorePatientProfile

Resolution applies to both JSON and XML, to the root resource, to Bundle entries, and to contained resources.

Resolution Options

Option Enum Default Description
profileResolution ProfileResolutionEnum OFF OFF always yields the base type. AUTO resolves from meta.profile.
onUnknownProfile OnUnknownProfileEnum FALLBACK A declared profile is not generated, or is not a profile of this resource.
onAmbiguousProfile OnAmbiguousProfileEnum FIRST_DECLARED Multiple unrelated known profiles are declared.
onProfileVersionMismatch OnProfileVersionMismatchEnum IGNORE_VERSION meta.profile carries a |version suffix differing from the generated one.
onProfileViolation OnProfileViolationEnum KEEP The resolved profile's _getProfileValidationErrors() is non-empty.

Each enum is string-backed, so configuration may use either the case or its value (e.g. 'auto', 'exception').

Enum Case Value Behaviour
ProfileResolutionEnum OFF 'off' Never resolve; always return the base type.
AUTO 'auto' Resolve using meta.profile.
OnUnknownProfileEnum FALLBACK 'fallback' Ignore the unknown entry; continue with remaining declared profiles.
EXCEPTION 'exception' Throw UnexpectedValueException.
OnAmbiguousProfileEnum FIRST_DECLARED 'firstDeclared' Use the first known profile in declaration order.
FALLBACK 'fallback' Return the base type.
EXCEPTION 'exception' Throw UnexpectedValueException.
OnProfileVersionMismatchEnum IGNORE_VERSION 'ignoreVersion' Resolve by URL only.
FALLBACK 'fallback' Ignore the mismatched entry.
EXCEPTION 'exception' Throw UnexpectedValueException.
OnProfileViolationEnum KEEP 'keep' Return the profile instance; caller may inspect errors.
FALLBACK 'fallback' Re-unserialize into the base type.
EXCEPTION 'exception' Throw UnexpectedValueException listing the violations.

When several declared profiles are known and one of them is a subclass of all the others, the most specific one is chosen and onAmbiguousProfile is not consulted.

Example of a strict configuration:

$config = new UnserializeConfig(
    profileResolution: 'auto',
    onUnknownProfile: 'exception',
    onAmbiguousProfile: 'exception',
    onProfileVersionMismatch: 'exception',
    onProfileViolation: 'exception',
);

Where Resolution Applies

Profile resolution happens inside VersionTypeMap::jsonUnserializeResource() / xmlUnserializeResource(), which is what ResourceParser uses.

It does not apply when calling a type's unserializer directly, nor when using the typed VersionClient::readOne*() methods — those always return the named base type:

// Always a FHIRPatient, regardless of configuration:
$patient = FHIRPatient::jsonUnserialize($json, config: $config);
$patient = $versionClient->readOnePatient(resourceID: 'patient-1');

// Honours profileResolution:
$patient = ResourceParser::parse($version, $json);

Looking Up Profiles

ProfileMap provides static lookups across all included packages:

<?php

use DCarbone\PHPFHIRGenerated\Versions\R4\Profiles\ProfileMap;

$url = 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient';

// Fully-qualified class name, or null if unknown. A "|version" suffix is ignored.
$class = ProfileMap::getProfileClassname($url);

// FHIR type name the profile constrains ("Patient"), or null if unknown.
$base = ProfileMap::getProfileBaseType($url);

// All profiles: [canonical URL => class name]
$all = ProfileMap::getProfileClasses();

// Unserialize directly into a known profile without ResourceParser:
$patient = $class::jsonUnserialize($json);

Autoloading

Profile classes are loaded lazily. The R4 Autoloader registers a ProfileAutoloader, which in turn registers each package's PackageAutoloader only when a class in that package's namespace is first requested. No profile code is loaded unless you use it. See Autoloading for details.

Clone this wiki locally