Multiple weather providers: a shared contract without losing important differences
Normalize selected weather quantities while retaining units, provenance and reasons for unavailability.
Two weather sources can report the same temperature in different units. A shared temperature field makes it tempting to hide that difference: each adapter returns a number and the interface displays them alike. Before comparing values, though, we need to establish that both describe the same quantity with the same temporal and spatial support. The same numeric shape does not provide that guarantee.
Consider a narrow teaching contract and two invented formats, A and B. They do not represent real providers. This example neither retrieves a forecast nor evaluates a model’s accuracy; it describes admission rules for one record and reasons to reject it. The standalone PHP lab has been run on synthetic data. This exercise tests only a teaching boundary.
Agree on the field first
Our required field is forecast air temperature at two metres for a specific instant. An optional capability is precipitation amount over an explicitly bounded interval. This is not a universal forecast schema. Another quantity needs its own semantics, units and admission rules.
This specificity matters even within one service. The Open-Meteo ECMWF documentation lists two-metre temperature, surface temperature and three-hour minima and maxima separately. Their presence in the list does not make them interchangeable. Our invented A and B do not implement this API; the documentation simply illustrates why the quantity and its support matter.
Adapter A accepts 20 degC, B accepts 68 degF. In both synthetic records the value applies to the same instant and two-metre height; their source and model identifiers differ. For our field B is converted using (F − 32) × 5 / 9. The observed normalized result is 20 degC for both, but the original number and unit, source, model and transformation version are retained alongside it.
This comparison establishes only compatibility of the declared fields in the example. It does not prove the models are identical, that values refer to the same model grid cell, or that either forecast is accurate. For a real integration, check the specific dataset’s documentation and spatial reference; height alone cannot establish a match of location.
Normalization must leave a trail
The teaching mapper’s temperature output includes an available state, quantity, normalized value and unit. It also retains the original value and unit, origin=forecast, transformation rule, source, model, valid time, receipt time and support. In B, model initialization time is unknown and remains null. Receipt time is not substituted for it.
The unit conversion and origin are separate. The formula changes the temperature’s representation, but it does not turn a forecast into an observation. If a source does not provide the required origin or identity, an adapter should not invent them from a field name. In this exercise, origin is specified by both invented contracts; that is not a general rule for arbitrary JSON.
PHP uses binary floating-point arithmetic without rounding on storage here. The 68 and 20 pair is convenient for this exact fixture expectation. For arbitrary fractions, consumers need an agreed precision and rounding policy; retaining the original permits later examination of the transformation. The string "20" is not accepted as a number: implicit type conversion can hide a source error.
Three states, not one zero
A provides a precipitation capability, but the first record contains null: the result is unavailable with reason missing. In the teaching contract B does not support the capability: the result is unavailable and unsupported. A third A record contains 0 mm with valid interval bounds: its result is an available numeric zero.
These are different messages for the next layer. The first permits data to be missing from this record. The second describes a capability declared by the invented format. The third contains a value. The interface can display “no data”, “not supported” or “0 mm” respectively, without turning uncertainty into dry weather. Interval bounds remain with an available value.
An incompatibility state is needed before a card is displayed. If surface temperature or an interval mean arrives for the two-metre instantaneous slot, the mapper rejects the record as incompatible. Do not silently change the label or assume a unit conversion fixed different semantics. For example, the Open-Meteo variable description distinguishes solar radiation averaged over the preceding hour from instantaneous radiation: temporal support must be read for the particular variable.
From contract to interface
Keep the boundary between normalization and presentation explicit. The mapper returns structured state; the next layer selects text for the interface language. If null is the only response to every problem, a visitor cannot tell whether data is temporarily missing or the source never promised that quantity. In the exercise, incompatible and invalid reject the entire record; they are not two more precipitation values. The product needs a separate way to report an error or use another validated record.
Not every difference should trigger automatic fallback. Suppose A did not return precipitation. Before substituting B, establish whether B supports the same quantity over the same interval, location and intended use. Even successful responses from both adapters do not prove all those conditions. Our example does not select between sources: it prepares an honest record or rejects it, leaving selection policy to a separate decision.
Similarly, treat 20 degC as a normalized representation, not the only evidence of input. If the transformation changes, the original value and unit help explain what was supplied. A rule version does not replace retained code or a rounding definition: it helps locate the relevant agreement. Comparing historical records also requires a policy for retaining those rules and provenance.
Admission and rejection of the entire record
Before returning a result, the mapper checks required identities, timestamp format, numeric types, units and time bounds. The exercise accepts only UTC instants to the second; a precipitation interval must start before it ends and end at the record’s valid time. An invalid calendar time or reversed bounds produces invalid. An exception rejects the entire record: the consumer receives no partially normalized temperature to publish.
The fixture policy uses −100 to 60 °C, or equivalent Fahrenheit limits, and 0 to 1000 mm for precipitation. These are chosen exercise limits, not universal meteorological laws. A real product defines limits for its source, quantity and use case and separately decides how to report rejection. Unknown units, nonnumeric values and nonfinite numbers are not repaired by guessing.
A literal NaN is not a valid JSON number: RFC 8259 excludes it from the number grammar. There are two checks: the decoder rejects such JSON, and admission of an already constructed PHP value separately rejects infinity or NaN. That protects the boundary even when calling code supplies an array without JSON decoding.
The code reads trusted teaching fixtures, not an arbitrary network stream. Before real use, size and nesting limits, duplicate JSON key handling, location identity and contract versioning would all need decisions. Standard JSON decoding alone does not prove duplicate keys were rejected. The exercise deliberately does not implement a secure general decoder; that is a significant limit. Check these requirements for the actual transport format and use case before connecting a real source.
What the lab checked
Synthetic inputs and expected JSON results have been fixed for the lab. The prepared checks compare both normalized records to those expectations, including original units and provenance; they separately check zero and the reasons for unavailability. Negative cases cover surface support, an interval mean, wrong unit, a string instead of a number, the exercise’s range, missing model, invalid time, reversed interval and constructed NaN.
The command php tools/weather-provider-contract-lab/test.php succeeded on PHP 8.5.12. The script confirmed exact matches against the expected JSON for the three A, B and A-zero outputs, plus three UI round trips. It also checked the frozen invalid-case matrix, four rejections of constructed NaN or infinity values, and invalid JSON. This is one standalone script, not PHPUnit methods; it does not contact a real weather provider or the network.
A shared contract is useful when the consumer knows what was accepted and what remains unknown. Start with a specific quantity and its boundaries, retain the input and provenance, and define distinct behavior for unsupported, missing and incompatible values. Adding a source then becomes a check of its promises, not just a renaming of fields.