Download the PHP package willdurand/hateoas without Composer
On this page you can find all versions of the php package willdurand/hateoas. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download willdurand/hateoas
More information about willdurand/hateoas
Files in willdurand/hateoas
Package hateoas
Short Description A PHP library to support implementing representations for HATEOAS REST web services
License MIT
Informations about the package hateoas
Hateoas
A PHP library to support implementing representations for HATEOAS REST web services.
- Installation
- Working With Symfony
- Usage
- Introduction
- Configuring Links
- Embedding Resources
- Dealing With Collections
- Representations
- VndErrorRepresentation
- The Expression Language
- Context
- Adding Your Own Context Variables
- Expression Functions
- URL Generators
- Helpers
- LinkHelper
- Twig Extensions
- LinkExtension
- Serializers & Formats
- The JsonHalSerializer
- The XmlSerializer
- The XmlHalSerializer
- Adding New Serializers
- The HateoasBuilder
- XML Serializer
- JSON Serializer
- URL Generator
- Expression Evaluator/Expression Language
- Relation Provider
- (JMS) Serializer Specific
- Others
- Configuring a Cache Directory
- Configuring Metadata Locations
- Extending The Library
- Reference
- XML
- YAML
- Annotations/Attributes
- @Relation
- @Route
- @Embedded
- @Exclusion
- @RelationProvider
- Internals
- Versioning
Installation
The recommended way to install Hateoas is through
Composer. Require the willdurand/hateoas
package
by running the following command:
This will resolve the latest stable version.
Otherwise, install the library and setup the autoloader yourself.
Working With Symfony
There is a bundle for that! Install the BazingaHateoasBundle, and enjoy!
Usage
Important:
For those who use the
1.0
version, you can jump to this documentation page.For those who use the
2.0
version, you can jump to this documentation page.The following documentation has been written for Hateoas 3.0 and above.
Introduction
Hateoas leverages the Serializer library to provide a nice way to build HATEOAS REST web services. HATEOAS stands for Hypermedia as the Engine of Application State, and adds hypermedia links to your representations (i.e. your API responses). HATEOAS is about the discoverability of actions on a resource.
For instance, let's say you have a User API which returns a representation of a single user as follow:
In order to tell your API consumers how to retrieve the data for this specific
user, you have to add your very first link to this representation, let's
call it self
as it is the URI for this particular user:
Let's dig into Hateoas now.
Configuring Links
In Hateoas terminology, links are seen as relations added to resources. It is worth mentioning that relations also refer to embedded resources too, but this topic will be covered in the Embedding Resources section.
A link is a relation which is identified by a name
(e.g. self
) and that
has an href
parameter:
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
In the example above, we configure a self
relation that is a link because of
the href
parameter. Its value, which may look weird at first glance, will be
extensively covered in The Expression Language
section. This special value is used to generate a URI.
In this section, annotations/attributes are used to configure Hateoas. YAML formats are also supported. If you wish, you can use plain PHP too.
Important: you must configure both the Serializer and Hateoas the same way. E.g. if you use YAML for configuring Serializer, use YAML for configuring Hateoas.
The easiest way to try HATEOAS is with the HateoasBuilder
. The builder has
numerous methods to configure the Hateoas serializer, but we won't dig into
them right now (see The HateoasBuilder).
Everything works fine out of the box:
The $hateoas
object is an instance of JMS\Serializer\SerializerInterface
,
coming from the Serializer library. Hateoas does not come with its own
serializer, it hooks into the JMS Serializer.
By default, Hateoas uses the Hypertext Application
Language (HAL) for JSON
serialization. This specifies the structure of the response (e.g. that
"links" should live under a _links
key):
For XML, Atom Links are used by default:
It is worth mentioning that these formats are the default ones, not the only available ones. You can use different formats through different serializers, and even add your owns.
Now that you know how to add links, let's see how to add embedded resources.
Embedding Resources
Sometimes, it's more efficient to embed related resources rather than link to them, as it prevents clients from having to make extra requests to fetch those resources.
An embedded resource is a named relation that contains data, represented
by the embedded
parameter.
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
Note: You will need to exclude the manager property from the serialization,
otherwise both the serializer and Hateoas will serialize it.
You will also have to exclude the manager relation when the manager is null
,
because otherwise an error will occur when creating the href
link (calling
getId()
on null
).
Tip: If the manager property is an object that already has a _self
link, you can re-use that value for the href
instead of repeating it here.
See LinkHelper.
For json
, the HAL representation places these embedded relations inside
an _embedded
key:
In XML, serializing embedded
relations will create new elements:
The tag name of an embedded resource is inferred from the
@XmlRoot
annotation (xml_root_name
in YAML, xml-root-name
in XML) coming from the
Serializer configuration.
Dealing With Collections
The library provides several classes in the Hateoas\Representation\*
namespace to help you with common tasks. These are simple classes configured
with the library's annotations.
The PaginatedRepresentation
, OffsetRepresentation
and CollectionRepresentation
classes are
probably the most interesting ones. These are helpful when your resource is
actually a collection of resources (e.g. /users
is a collection of users).
These help you represent the collection and add pagination and limits:
The CollectionRepresentation
offers a basic representation of an embedded collection.
The PaginatedRepresentation
is designed to add self
, first
, and when
possible last
, next
, and previous
links.
The OffsetRepresentation
works just like PaginatedRepresentation
but is useful
when pagination is expressed by offset
, limit
and total
.
The RouteAwareRepresentation
adds a self
relation based on a given route.
You can generate absolute URIs by setting the absolute
parameter to true
in both the PaginatedRepresentation
and the RouteAwareRepresentation
.
The Hateoas library also provides a PagerfantaFactory
to easily build
PaginatedRepresentation
from a
Pagerfanta instance. If you use
the Pagerfanta library, this is an easier way to create the collection
representations:
You would get the following JSON content:
And the following XML content:
If you want to customize the inlined CollectionRepresentation
, pass one as
third argument of the createRepresentation()
method:
If you want to change the xml root name of the collection, create a new class with the xml root configured and use the inline mechanism:
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
Representations
As mentionned in the previous section, representations are classes configured with the library's annotations in order to help you with common tasks. The collection representations are described in Dealing With Collection.
VndErrorRepresentation
The VndErrorRepresentation
allows you to describe an error response following
the vnd.error
specification.
Serializing such a representation in XML and JSON would give you the following outputs:
Hint: it is recommended to create your own error classes that extend the
VndErrorRepresentation
class.
The Expression Language
Hateoas relies on the powerful Symfony ExpressionLanguage component to retrieve values such as links, ids or objects to embed.
Each time you fill in a value (e.g. a Relation href
in annotations or YAML),
you can either pass a hardcoded value or an expression.
In order to use the Expression Language, you have to use the expr()
notation:
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
You can learn more about the Expression Syntax by reading the official documentation: The Expression Syntax.
Context
Natively, a special variable named object
is available in each expression, and
represents the current object:
We call such a variable a context variable.
You can add your own context variables to the Expression Language context by adding them to the expression evaluator.
Adding Your Own Context Variables
Using the HateoasBuilder
, call the setExpressionContextVariable()
method to add
new context variables:
The foo
variable is now available:
Expression Functions
For more info on how to add functions to the expression language, please refer to https://symfony.com/doc/current/components/expression_language/extending.html
URL Generators
Since you can use the Expression Language to define
the relations links (href
key), you can do a lot by default. However if you
are using a framework, chances are that you will want to use routes to build
links.
You will first need to configure an UrlGenerator
on the builder. You can
either implement the Hateoas\UrlGenerator\UrlGeneratorInterface
, or use the
Hateoas\UrlGenerator\CallableUrlGenerator
:
You will then be able to use the @Route annotation:
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
Note that the library comes with a SymfonyUrlGenerator
. For example, to use it
in Silex:
Helpers
Hateoas provides a set of helpers to ease the process of building APIs.
LinkHelper
The LinkHelper
class provides a getLinkHref($object, $rel, $absolute = false)
method that allows you to get the href value of any object, for any given
relation name. It is able to generate a URI (either absolute or relative) from
any link relation:
The link
Function
The feature above is also available in your expressions (cf. The Expression
Language) through the link(object, rel, absolute)
function:
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
Pay attention to the href
expressions for the post
and relative
relations,
as well as their corresponding values in the following JSON content:
It is worth mentioning that you can force whether you want an absolute or
relative URI by using the third argument in both the getLinkHref()
method and
the link
function.
Important: by default, all URIs will be relative, even those which are defined as absolute in their configuration.
Twig Extensions
Hateoas also provides a set of Twig extensions.
LinkExtension
The LinkExtension
allows you to use the LinkHelper into your
Twig templates, so that you can generate links in your HTML templates for
instance.
This extension exposes the getLinkHref()
helper's method through the
link_href
Twig function:
Serializers & Formats
Hateoas provides a set of serializers. Each serializer allows you to generate either XML or JSON content following a specific format, such as HAL, or Atom Links for instance.
The JsonHalSerializer
The JsonHalSerializer
allows you to generate HAL compliant relations in JSON.
It is the default JSON serializer in Hateoas.
HAL provides its linking capability with a convention which says that a resource
object has a reserved property called _links
. This property is an object that
contains links. These links are key'ed by their link relation.
HAL also describes another convention which says that a resource may have
another reserved property named _embedded
. This property is similar to _links
in that embedded resources are key'ed by relation name. The main difference is
that rather than being links, the values are resource objects.
The XmlSerializer
The XmlSerializer
allows you to generate Atom
Links into your XML
documents. It is the default XML serializer.
The XmlHalSerializer
The XmlHalSerializer
allows you to generate HAL compliant relations in XML.
HAL in XML is similar to HAL in JSON in the sense that
it describes link
tags and resource
tags.
Note: the self
relation will actually become an attribute of the main
resource instead of being a link
tag. Other links will be generated as link
tags.
Adding New Serializers
You must implement the SerializerInterface
that describes two methods to serialize
links and embedded relations.
The HateoasBuilder
The HateoasBuilder
class is used to easily configure Hateoas thanks to a
powerful and fluent API.
All the methods below return the current builder, so that you can chain them.
XML Serializer
setXmlSerializer(SerializerInterface $xmlSerializer)
: sets the XML serializer to use. Default is:XmlSerializer
;setDefaultXmlSerializer()
: sets the default XML serializer (XmlSerializer
).
JSON Serializer
setJsonSerializer(SerializerInterface $jsonSerializer)
: sets the JSON serializer to use. Default is:JsonHalSerializer
;setDefaultJsonSerializer()
: sets the default JSON serializer (JsonHalSerializer
).
URL Generator
setUrlGenerator($name = null, UrlGeneratorInterface $urlGenerator)
: adds a new named URL generator. If$name
isnull
, the URL generator will be the default one.
Expression Evaluator/Expression Language
setExpressionContextVariable($name, $value)
: adds a new expression context variable;setExpressionLanguage(ExpressionLanguage $expressionLanguage)
;
(JMS) Serializer Specific
includeInterfaceMetadata($include)
: whether to include the metadata from the interfaces;setMetadataDirs(array $namespacePrefixToDirMap)
: sets a map of namespace prefixes to directories. This method overrides any previously defined directories;addMetadataDir($dir, $namespacePrefix = '')
: adds a directory where the serializer will look for class metadata;addMetadataDirs(array $namespacePrefixToDirMap)
: adds a map of namespace prefixes to directories;replaceMetadataDir($dir, $namespacePrefix = '')
: similar toaddMetadataDir()
, but overrides an existing entry.
Please read the official Serializer documentation for more details.
Others
setDebug($debug)
: enables or disables the debug mode;setCacheDir($dir)
: sets the cache directory.
Configuring a Cache Directory
Both the serializer and the Hateoas libraries collect metadata about your objects from various sources such as YML, XML, or annotations. In order to make this process as efficient as possible, it is recommended that you allow the Hateoas library to cache this information. To do that, configure a cache directory:
Configuring Metadata Locations
Hateoas supports several metadata sources. By default, it uses Doctrine annotations (PHP < 8.1) or native PHP attributes (PHP >= 8.1), but you may also store metadata in XML, or YAML files. For the latter, it is necessary to configure a metadata directory where those files are located:
Hateoas would expect the metadata files to be named like the fully qualified
class names where all \
are replaced with .
. If you class would be named
Vendor\Package\Foo
the metadata file would need to be located at
$someDir/Vendor.Package.Foo.(xml|yml)
.
Extending The Library
Hateoas allows frameworks to dynamically add relations to classes by providing an extension point at configuration level. This feature can be useful for those who want to to create a new layer on top of Hateoas, or to add "global" relations rather than copying the same configuration on each class.
In order to leverage this mechanism, the ConfigurationExtensionInterface
interface has to be implemented:
You can access the existing relations loaded from Annotations, XML, or YAML with
$classMetadata->getRelations()
.
If the $classMetadata
has relations, or if you add relations to it, its
relations will be cached. So if you read configuration files (Annotations, XML,
or YAML), make sure to reference them on the class metadata:
Reference
XML
See the
hateoas.xsd
file for more details.
YAML
Annotations
@Relation
This annotation can be defined on a class.
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
Property | Required | Content | Expression language |
---|---|---|---|
name | Yes | string | No |
href | If embedded is not set | string / @Route | Yes |
embedded | If href is not set | string / @Embedded | Yes |
attributes | No | array | Yes on values |
exclusion | No | @Exclusion | N/A |
Important: attributes
are only used on link relations (i.e. combined
with the href
property, not with the embedded
one).
@Route
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
This annotation can be defined in the href property of the @Relation annotation. This is allows you to your URL generator, if you have configured one.
Property | Required | Content | Expression language |
---|---|---|---|
name | Yes | string | No |
parameters | Defaults to array() | array / string | Yes (string + array values) |
absolute | Defaults to false | boolean / string | Yes |
generator | No | string / null | No |
@Embedded
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
This annotation can be defined in the embedded property of the
@Relation annotation. It is useful if you need configure the
exclusion
or xmlElementName
options for the embedded resource.
Property | Required | Content | Expression language |
---|---|---|---|
content | Yes | string / array | Yes (string) |
exclusion | Defaults to array() | @Exclusion | N/A |
xmlElementName | Defaults to array() | string | No |
@Exclusion
This annotation can be defined in the exclusion property of both the @Embedded annotations.
Property | Required | Content | Expression language |
---|---|---|---|
groups | No | array | No |
sinceVersion | No | string | No |
untilVersion | No | string | No |
maxDepth | No | integer | No |
excludeIf | No | string / boolean | Yes |
All values except excludeIf
act the same way as when they are used directly
on the regular properties with the serializer.
excludeIf
expects a boolean and is helpful when another expression would fail
under some circumstances. In this example, if the getManager
method is null
,
you should exclude it to prevent the URL generation from failing:
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
@RelationProvider
This annotation can be defined on a class. It is useful if you wish to serialize multiple-relations(links). As an example:
Property | Required | Content | Expression language |
---|---|---|---|
name | Yes | string | Yes |
It can be "name":
- A function:
my_func
- A static method:
MyClass::getExtraRelations
- An expression:
expr(service('user.rel_provider').getExtraRelations())
Here and example using the expression language:
Annotation (PHP < 8.1)
Attribute (PHP 8.1 and greater)
Here the UserRelPrvider
class:
$this->evaluator
implementing CompilableExpressionEvaluatorInterface
is used to parse the expression language
in a form that can be cached and saved for later use.
If you do not need the expression language in your relations, then this service is not needed.
The user.rel_provider
service is defined as:
In this case jms_serializer.expression_evaluator
is a service implementing CompilableExpressionEvaluatorInterface
.
Internals
This section refers to the Hateoas internals, providing documentation about hidden parts of this library. This is not always relevant for end users, but interesting for developers or people interested in learning how things work under the hood.
Versioning
willdurand/hateoas
follows Semantic Versioning.
End Of Life
As of October 2013, versions 1.x
and 0.x
are officially not supported anymore
(note that 1.x
was never released).
Stable Version
Version 3.x
is the current major stable version.
Version 2.x
is maintained only for security bug fixes and for major issues that might occur.
Contributing
See CONTRIBUTING file.
Running the Tests
Install the Composer dev
dependencies:
php composer.phar install --dev
Then, run the test suite using PHPUnit:
bin/phpunit
License
Hateoas is released under the MIT License. See the bundled LICENSE file for details.
All versions of hateoas with dependencies
jms/metadata Version ^2.0
jms/serializer Version ^3.18.2
symfony/expression-language Version ^3.4.47 || ~4.0 || ~5.0 || ~6.0 || ~7.0