Introduction
Magewire knowledge required
It is highly advisable to possess a foundational understanding of Magewire in order to fully leverage the Evaluation API concept. Much of its functionality is inspired by Magewire's state handling, transitioning seamlessly between backend and frontend operations.
The Hyvä Checkout Evaluation API enables developers to transmit evaluation state from backend to frontend, defining frontend instructions and behaviors via backend code. This state might represent validation requirements, error messages, or JavaScript execution tasks. The Evaluation API bridges backend logic with frontend interactions, allowing Magento plugins to modify behavior and improving maintainability.
Why use it?
The Evaluation API provides an extensible foundation for passing instructions to the frontend both when loading the checkout and subsequent Magewire update requests. Additionally, maintainability is improved because it is driven by the backend which allows Magento goodies (such as Plugins) to be used in order to change the behaviour if/when required.
Example scenario
This example demonstrates a Magewire component with a numeric counter and increment/decrement buttons. The component evaluates whether the counter meets requirements before allowing the customer to proceed with checkout navigation.
Backend component implementation
The Magewire component implements the EvaluationInterface to evaluate the counter value. When the value is greater than zero, the component returns a Success result. Otherwise, it returns an Error Message that displays when the customer attempts to navigate forward.
<?php
class ExampleScenario extends \Magewirephp\Magewire\Component implements \Hyva\Checkout\Model\Magewire\Component\EvaluationInterface
{
public int $count = 0;
public function increment()
{
$this->count++;
}
public function decrements()
{
$this->count--;
}
// Evaluated upon page load and after triggering the increment or decrement actions.
public function evaluateCompletion(EvaluationResultFactory $resultFactory): EvaluationResult
{
if ($this->count > 0) {
// Mark the component as completed. This should be the final status if all functions are operating correctly.
return $resultFactory->createSuccess();
}
// This triggers a Magento flash message to inform customers when attempting to navigate forward or place an order.
return $resultFactory->createErrorMessage()
->withMessage('Count value must be greater than zero.')
->withVisibilityDuration(5000)
->asWarning();
// Initiates a custom window event when customers attempt to navigate forward or place an order.
return $resultFactory->createEvent()
->withCustomEvent('count-failure')
}
}
Frontend template
The template provides increment and decrement buttons that trigger Magewire actions to update the counter value.
<input type="number" wire:model="count"/>
<button type="button" wire:click="increment">Increment</button>
<button type="button" wire:click="decrement">Decrement</button>
How it works
The Evaluation API operates on a server-driven basis, processing results either upon page rendering or when triggered by Magewire updates (method calls or value syncing).
- The customer sees a value of
0and clicks the "increment" button - The Magewire action is sent to the server, incrementing the count
- After the Magewire update lifecycle completes, the evaluation state is automatically re-evaluated
- Since the count is now greater than zero, the evaluation returns a Success result
- The Evaluation API updates the component's evaluation state, removing restrictions and marking the component as completed
If the customer attempts to navigate forward while the count is still 0, the error message will display automatically. By default, error messages are bound to the Validation API, meaning they display when the customer presses the primary navigation button.
Dispatch immediately
In certain scenarios, specific evaluation results feature a dispatch capability, empowering developers to chain the dispatch() method. This action prevents the result from being bound to a button-click trigger, ensuring that the message is promptly displayed as soon as the Ajax response is received from the server.
Result type requirements
Hyvä Checkout comes equipped with various evaluation result types by default. These types are available in Hyva\Checkout\Model\Magewire\Component\Evaluation, where additional result types have been introduced across different versions. Therefore, available result types may differ depending on the version installed.
Backend type class
When implementing a component with the EvaluationInterface, you must include an evaluateCompletion() method within the component. This method automatically receives the $resultFactory as an argument, enabling developers to easily generate the desired result.
This example shows the structure of the Event result type, demonstrating how to use capabilities (reusable traits) and define custom methods for developers.
<?php
class Event extends \Hyva\Checkout\Model\Magewire\Component\Evaluation\EvaluationResult
{
// Inject the required (reusable) capabilities.
use \Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern\DetailsCapabilities;
use \Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern\DispatchCapabilities;
public const TYPE = 'event';
private string $event = 'evaluation:event:default';
public function getArguments(\Magewirephp\Magewire\Component $component): array
{
return [
'event' => $this->event,
'detail' => $this->getDetails($component)
];
}
// Offer developers the flexibility to execute custom events.
public function withCustomEvent(string $event): self
{
$this->event = $event;
// Always return $this to allow method chaining.
return $this;
}
}
Capabilities
Capabilities refer to reusable Traits that are adaptable for various scenarios to cater for different requirements. Each result type can possess its own unique set of capabilities. When utilized, developers must define the relevant arguments within the getArguments() result array.
This example demonstrates using the StackingCapabilities trait to add stack positioning to a custom result type.
<?php
class CustomResultType extends \Hyva\Checkout\Model\Magewire\Component\Evaluation\EvaluationResult
{
// Injects a 'withStackPosition' method.
use \Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern\StackingCapabilities;
public function getArguments(Component $component): array
{
return [
'stack' => [
'position' => $this->stackPosition // $stackPosition by default returns 500.
]
];
}
}
All available capabilities can be found in Hyva\Checkout\Model\Magewire\Component\Evaluation\Concern.
Frontend processor
Each result type must have its own unique processor from a frontend perspective. A processor is a callback that is automatically picked up either during page rendering or when the component is updated.
This example shows the Event processor implementation, demonstrating how to handle dispatch behavior and bind to the validation API.
Before 1.1.12 use hyvaCheckout.evaluation.processors['event'] = () => {}
hyvaCheckout.evaluation.registerProcessor('event', (component, el, result) => {
if (result.dispatch || false) {
window.dispatchEvent(new CustomEvent(result.arguments.event, {detail: result.arguments.detail}))
return result.result;
}
// Bind it onto the validation API to be triggered on a primary button click.
hyvaCheckout.validation.register(
result.hash,
() => window.dispatchEvent(new CustomEvent(result.arguments.event, {detail: result.arguments.detail})),
el,
result.id
)
return result.result;
})
The callback 'result' argument
The result arguments has a fixed set of variables evaluated by the checkout Evaluation Hydrator.
- arguments
array: Type arguments, which can vary per result type. - dispatch
bool: To be dispatched immediately or not. - result
bool: Positive or negative type result. - type
string: Result type name. - id
string: The Magewire component ID. - hash
string: SHA1 hash of the result array values.
More insights can be found in: \Hyva\Checkout\Model\Magewire\Component\Hydrator\Evaluation