Download the PHP package getpop/field-query without Composer
On this page you can find all versions of the php package getpop/field-query. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download getpop/field-query
More information about getpop/field-query
Files in getpop/field-query
Package field-query
Short Description Component model for PoP, over which the component-based architecture is based
License GPL-2.0-or-later
Homepage https://github.com/getpop/field-query
Informations about the package field-query
Field Query
Syntax to query GraphQL through URL params, which grants a GraphQL API the capability to be cached on the server.
Install
Via Composer
Development
The source code is hosted on the PoP monorepo, under Engine/packages/field-query
.
Usage
Initialize the component:
Use it:
Why
The GraphQL query generally spans multiple lines, and it is provided through the body of the request instead of through URL params. As a result, it is difficult to cache the results from a GraphQL query in the server. In order to support server-side caching on GraphQL, we can attempt to provide the query through the URL instead, as to use standard mechanisms which cache a page based on the URL as its unique ID.
The syntax described and implemented in this project is a re-imagining of the GraphQL syntax, supporting all the same elements (field arguments, variables, aliases, fragments, directives, etc), however designed to be easy to write, and easy to read and understand, in a single line, so it can be passed as a URL param.
Being able to pass the query as a URL param has, in turn, several other advantages:
- It removes the need for a client-side library to convert the GraphQL query into the required format (such as Relay), leading to performance improvements and reduced amount of code to maintain
- The GraphQL API becomes easier to consume (same as REST), and avoids depending on a special client (such as GraphiQL) to visualize the results of the query
Who uses it
PoP uses this syntax natively: To load data in each component within the application itself (as done by the Component Model), and to load data from an API through URL param query
(as done by the PoP API).
A GraphQL server can implement this syntax as to support URI-based server-side caching. To achieve this, a service must translate the query from this syntax to the corresponding GraphQL syntax, and then pass the translated query to the GraphQL engine.
Syntax
Similar to GraphQL, the query describes a set of “fields”, where each field can contain the following elements:
- The field name: What data to retrieve
- Field arguments: How to filter the data, or format the results
- Field alias: How to name the field in the response
- Field directives: To change the behaviour of how to execute the operation
Differently than GraphQL, a field can also contain the following elements:
- Property names in the field arguments may be optional: To simplify passing arguments to the field
- Bookmarks: To keep loading data from an already-defined field
- Operators and Helpers: Standard operations (
and
,or
,if
,isNull
, etc) and helpers to access environment variables (among other use cases) can be already available as fields - Composable fields: The response of a field can be used as input to another field, through its arguments or field directives
- Skip output if null: To ignore the output if the value of the field is null
- Composable directives: A directive can modify the behaviour of other, nested directives
- Expressions: To pass values across directives
From the composing elements, only the field name is mandatory; all others are optional. A field is composed in this order:
- The field name
- Arguments:
(...)
- Bookmark:
[...]
- Alias:
@...
(if the bookmark is also present, it is placed inside) - Skip output if null:
?
- Directives: directive name and arguments:
<directiveName(...)>
The field looks like this:
To make it clearer to visualize, the query can be split into several lines:
Note:
Firefox already handles the multi-line query: Copy/pasting it into the URL bar works perfectly. To try it out, copyhttps://newapi.getpop.org/api/graphql/
followed by the query presented in each example into Firefox's URL bar, and voilà, the query should execute.Chrome and Safari do not work as well: They require to strip all the whitespaces and line returns before pasting the query into the URL bar.
Conclusion: use Firefox!
To retrieve several fields in the same query, we join them using ,
:
Retrieving properties from a node
Separate the properties to fetch using |
.
In GraphQL:
In PoP (View query in browser):
Retrieving nested properties
To fetch relational or nested data, describe the path to the property using .
.
In GraphQL:
In PoP (View query in browser):
We can use |
to bring more than one property when reaching the node:
In GraphQL:
In PoP (View query in browser):
Symbols .
and |
can be mixed together to also bring properties along the path:
In GraphQL:
In PoP (View query in browser):
Appending fields
Combine multiple fields by joining them using ,
.
In GraphQL:
In PoP (View query in browser):
Appending fields with strict execution order
This is a syntax + functionality feature. Combine multiple fields by joining them using ;
, telling the data-loading engine to resolve the fields on the right side of the ;
only after resolving all the fields on the left side.
The closest equivalent in GraphQL is the same as the previous case with ,
, however this syntax does not modify the behavior of the server.
In GraphQL:
In PoP (View query in browser):
In the GraphQL server, the previous query is resolved as this one (with self
being used to delay when a field is resolved):
Field arguments
Field arguments is an array of properties, to filter the results (when applied to a property along a path) or modify the output (when applied to a property on a leaf node) from the field. These are enclosed using ()
, defined using :
to separate the property name from the value (becoming name:value
), and separated using ,
.
Values do not need be enclosed using quotes "..."
.
Filtering results in GraphQL:
Filtering results in PoP (View query in browser):
Formatting output in GraphQL:
Formatting output in PoP (View query in browser):
Optional property name in field arguments
Defining the argument name can be ignored if it can be deduced from the schema (for instance, the name can be deduced from the position of the property within the arguments in the schema definition).
In PoP (View query in browser):
Aliases
An alias defines under what name to output the field. The alias name must be prepended with @
:
In GraphQL:
In PoP (View query in browser):
Please notice that aliases are optional, differently than in GraphQL. In GraphQL, because the field arguments are not part of the field in the response, when querying the same field with different arguments it is required to use an alias to differentiate them. In PoP, however, field arguments are part of the field in the response, which already differentiates the fields.
In GraphQL:
In PoP (View query in browser):
Bookmarks
When iterating down a field path, loading data from different sub-branches is visually appealing in GraphQL:
In GraphQL:
In PoP, however, the query can become very verbose, because when combining fields with ,
it starts iterating the path again all the way from the root:
In PoP (View query in browser):
Bookmarks help address this problem by creating a shortcut to a path, so we can conveniently keep loading data from that point on. To define the bookmark, its name is enclosed with [...]
when iterating down the path, and to use it, its name is similarly enclosed with [...]
:
In PoP (View query in browser):
Bookmark with Alias
When we need to define both a bookmark to a path, and an alias to output the field, these 2 must be combined: The alias, prepended with @
, is placed within the bookmark delimiters [...]
.
In PoP (View query in browser):
Variables
Variables can be used to input values to field arguments. While in GraphQL the values to resolve to are defined within the body (in a separate dictionary than the query), in PoP these are retrieved from the request ($_GET
or $_POST
).
The variable name must be prepended with $
, and its value in the request can be defined either directly under the variable name, or under entry variables
and then the variable name.
API call in GraphQL:
In PoP (View in browser: query 1, query 2):
Fragments
Fragments enable to re-use query sections. Similar to variables, their resolution is defined in the request ($_GET
or $_POST
). Unlike in GraphQL, the fragment does not need to indicate on which schema type it operates.
The fragment name must be prepended with --
, and the query they resolve to can be defined either directly under the fragment name, or under entry fragments
and then the fragment name.
While a fragment can contain |
(to split fields), it cannot contain ;
(to split operations) or ,
(to split queries), to avoid confusion (since these are computed from the root of the query, not the fragment).
In GraphQL:
In PoP (View in browser: query 1, query 2):
Directives
A directive enables to modify if/how the operation to fetch data is executed. Each field accepts many directives, each of them receiving its own arguments to customize its behaviour. The set of directives is surrounded by <...>
, the directives within must be separated by ,
, and their arguments follows the same syntax as field arguments: they are surrounded by (...)
, and its pairs of name:value
are separated by ,
.
In GraphQL:
In PoP (View in browser: query 1, query 2, query 3, query 4):
Operators and Helpers
Standard operations, such as and
, or
, if
, isNull
, contains
, sprintf
and many others, can be made available on the API as fields. Then, the operator name stands for the field name, and it can accept all the other elements in the same format (arguments, aliases, etc).
To pass an argument value as an array, we enclose it between []
and split its items with ,
. The format can be just value
(numeric array) or key:value
(indexed array).
In PoP (View in browser: query 1, query 2, query 3, query 4, query 5, query 6, query 7, query 8, query 9):
In the same fashion, helper functions can provide any required information, also behaving as fields. For instance, helper context
provides the values in the system's state, and helper var
can retrieve any specific variable from the system's state.
In PoP (View in browser: query 1, query 2):
Composable fields
The real benefit from having operators comes when they can receive the output from a field as their input. Since an operator is a field by itself, this can be generalized into “composable fields”: Passing the result of any field as an argument value to another field.
In order to distinguish if the input to the field is a string or the name of a field, the field must have field arguments brackets (...)
(if no arguments, then simply ()
). For instance, "id"
means the string "id", and "id()"
means to execute and pass the result from field "id".
In PoP (View in browser: query 1, query 2, query 3, query 4, query 5, query 6):
In order to include characters (
and )
as part of the query string, and avoid treating the string as a field to be executed, we must enclose it using quotes: "..."
.
In PoP (View query in browser):
Composable fields with directives
Composable fields enable to execute an operation against the queried object itself. Making use of this capability, directives in PoP become much more useful, since they can evaluate their conditions against each and every object independently. This feature can give raise to a myriad of new features, such as client-directed content manipulation, fine-grained access control, enhanced validations, and many others.
For instance, the GraphQL spec requires to support directives include
and skip
, which receive a parameter if
with a boolean value. While GraphQL expects this value to be provided through a variable (as shown in section Directives above), in PoP it can be retrieved from the object.
In PoP (View in browser: query 1))>.id|src), query 2)>.id|src)):
Skip output if null
Whenever the value from a field is null, its nested fields will not be retrieved. For instance, consider the following case, in which field "featuredImage"
sometimes is null:
In PoP (View query in browser):
As we have seen in section Composable fields with directives above, by combining directives include
and skip
with composable fields, we can decide to not output a field when its value is null. However, the query to execute this behaviour includes a directive added in the middle of the query path, making it very verbose and less legible. Since this is a very common use case, it makes sense to generalize it and incorporate a simplified version of it into the syntax.
For this, PoP introduces symbol ?
, to be placed after the field name (and its field arguments, alias and bookmark), to indicate "if this value is null, do not output it".
In PoP (View query in browser):
Composable directives and Expressions
Directives can be nested: An outer directive can modify the behaviour of its inner, nested directive(s). It can pass values across to its composed directives through “expressions”, variables surrounded with %...%
which can be created on runtime (coded as part of the query), or be defined in the directive itself.
In the example below, directive <forEach>
iterates through the elements of the array, for its composed directive <applyFunction>
to do something with each of them. It passes the array item through pre-defined expression %{value}%
(coded within the directive).
In PoP (View query in browser):
In the example below, directive <advancePointerInArrayOrObject>
communicates to directive <translate>
the language to translate to through expression %{toLang}%
, which is defined on-the-fly.
In PoP (View query in browser):
Combining elements
Different elements can be combined, such as the following examples.
A fragment can contain nested paths, variables, directives and other fragments:
In PoP (View query in browser):
A fragment can contain directives, which are transferred into the fragment resolution fields:
In PoP (View query in browser>&fragments[props]=title|date)):
If the field in the fragment resolution field already has its own directives, these are applied; otherwise, the directives from the fragment definition are applied:
In PoP (View query in browser>&fragments[props]=title|url<include(if:not(hasComments()))>)):
A fragment can contain an alias, which is then transferred to all fragment resolution fields as an enumerated alias (@aliasName1
, @aliasName2
, etc):
In PoP (View query in browser):
A fragment can contain the "Skip output if null" symbol, which is then transferred to all fragment resolution fields:
In PoP (View query in browser):
Combining both directives and the skip output if null symbol with fragments:
In PoP (View query in browser>&fragments[props]=title|url<include(if:hasComments())>|featuredImage)):
PHP versions
Requirements:
- PHP 8.1+ for development
- PHP 7.1+ for production
Supported PHP features
Check the list of Supported PHP features in leoloso/PoP
Preview downgrade to PHP 7.1
Via Rector (dry-run mode):
Standards
To check the coding standards via PHP CodeSniffer, run:
To automatically fix issues, run:
Change log
Please see CHANGELOG for more information on what has changed recently.
Testing
Report issues
To report a bug or request a new feature please do it on the PoP monorepo issue tracker.
Contributing
We welcome contributions for this package on the PoP monorepo (where the source code for this package is hosted).
Please see CODE_OF_CONDUCT for details.
Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
Credits
- Leonardo Losoviz
- All Contributors
License
GNU General Public License v2 (or later). Please see License File for more information.