Download the PHP package getpop/component-model without Composer
On this page you can find all versions of the php package getpop/component-model. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download getpop/component-model
More information about getpop/component-model
Files in getpop/component-model
Package component-model
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/component-model
Informations about the package component-model
Component Model
Component model for PoP, over which the component-based architecture is based.
Install
Via Composer
Development
The source code is hosted on the GatoGraphQL monorepo, under Engine/packages/component-model
.
Usage
Initialize the component:
Main Concepts
Everything is a Component
The term "component" is often used to describe the concept of encapsulating a set of related functions for building modular applications. In PoP, a component is called a "component", so from now on the names "component" and "component" are used interchangeably.
A component is simply a set of pieces of HTML, JavaScript and CSS code put all together to create an autonomous entity. Each component can be an atomic functionality, a composition of other components, or a combination of the two. Each component has a purpose, which can range from something very basic, such as a link or a button, to something very elaborate, such as a carousel or a drag-and-drop image uploader.
The relationship among components is defined on a strictly top-down fashion: a component wraps other components and knows who they are, but it doesn't know, and doesn't care, which components are wrapping him. Ever more complex components are created by iteratively wrapping simpler components, until reaching the top-most component representing the webpage:
In PoP, everything is a component:
The relationship of all components wrapping each other, from the top-most component all the way down to the last level, is called the component hierarchy. The PoP API has the component hierarchy at its core, implemented as an associative array on the server-side, in which each component states its name as the key attribute and whatever properties it needs as values, and then nests its descendant components under property "components", iteratively adding their own data and that of their own descendant components. Finally, this associative array is returned as a JSON object for consumption through the API:
Relational database data
PoP represents the database data in a relational manner, organized under each object type, object ID and object properties, mirroring the structure of the data in the database. This way, all data is normalized, fetched only once from the database, and printed only once in the output. It is added under entry databases
in the API response:
For instance, if fetching the data for blog posts with titles "Hello World!" and "Everything fine?" and author "Leo" both of them, then PoP brings the response below; please notice how property "author" contains the ID to the author object instead of printing the author data directly:
Each component knows which are its queried objects from section datasetcomponentdata
, which provides the IDs of the queried objects under property objectIDs
(IDs 4 and 9 for the blog posts), and knows from where to retrieve the database object data from under section databases
through section componentsettings
, which indicates to what type each object belongs under property outputKeys
(then, it knows that the post's author data, corresponding to the author with the ID given under property "author", is found under object type "users"):
The engine infers how to retrieve database data already from the component hierarchy
When a component displays a property from a DB object, the component may not know, or care, what object it is; all it cares about is defining what properties from the loaded object are required. For instance, consider the image below: a component loads an object from the database (in this case, a single post), and then its descendant components will show certain properties from the object, such as "title" and "content":
Hence, along the component hierarchy, some components will be in charge of loading the queried objects (the component loading the single post, in this case), and its descendant components will define what properties from the DB object are required ("title" and "content", in this case).
Fetching all the required properties for the DB object can be done automatically by traversing the component hierarchy: starting from the data loading component, we iterate all its descendant components all the way down until reaching a new data loading component, or until the end of the tree; at each level we obtain all required properties, and then merge all properties together and query them from the database, all of them only once. In the structure below, component "single-post" fetches the results from the DB, and subcomponents "post-title" and "post-content" define properties to be loaded for the queried DB object ("title" and "content" respectively); subcomponent "post-layout" does not require any data fields. Please notice how the executed query, which is calculated automatically from the component hierarchy and their required data fields, will contain all the properties needed by all the components and their subcomponents:
Which will result in the following (pseudo-)query:
The query to fetch data from the database is automatically updated whenever the component hierarchy changes. If we then add subcomponent "post-thumbnail", which requires data field "thumbnail", under "single-post":
Then the query is automatically updated with the new data:
This strategy also applies to relational objects. Consider the image below: Starting from the object domain "post", we need to change the DB object domain to entities "user" and "comment", corresponding to the post's author and each of the post's comments respectively, and then, for each comment, it must change the domain once again to "user", for the comment's author. After changing from one to another domain, from that level at the component hierarchy downwards, all required properties will be subjected to the new domain: Property "name" is fetched from the "user" object representing the post's author, "content" from the "comment" object representing each of the post's comments, and then "name" from the "user" object representing the author of each comment:
Going back to our previous example, if we need to show data from the post's author, stacking subcomponent "post-author" will change the domain at that level from "post" to the corresponding "user", and from this level downwards the DB object loaded into the context passed to the component is the user. Then, subcomponents "user-name" and "user-avatar" under "post-author" will load properties "name" and "avatar" under the user object:
Resulting in the following query:
Configuration values included, overridable through props
Note: the configuration layer must be added through another package
Instead of hardcoding classnames or other properties such as a title's HTML tag or an avatar max width inside of JavaScript files for rendering in the client, we can pass configuration values already through the API, so that then these can be directly updated on the server and without the need to redeploy JavaScript files:
Configuration values can be set through props, defined across the component hierarchy so that components can modify the behavior of their descendant components, and where higher-level components have priority for setting a prop. Setting props works in one direction only: parent components can set props on any descendant component, but no component can set props on any ancestor component or on any component belonging to a different branch from the component hierarchy. In the example below, "component1" can set props on "component2", "component3" and "component4", "component2" on "component3", and "component3" and "component4" on nobody:
Let's say we have a component "component3" with property "color", set as "red" by default. By not specifying a component target of the prop, the component in the pseudo-code below is setting a prop on itself:
Through property "componentpath", a component can target any of its descendant components any number of levels deep from itself. In the pseudo-code below, parent component "component2" adds property "componentpath" pointing to subcomponent "component3", overriding its value for property "color" to "green":
And this can go on for any number of ancestor components. For instance, in the pseudo-code below, the "component1" component, which is parent to "component2", can further override the value for property "color" applied to component "component3":
Component "component1" can set a property on component "component3", which is 2 levels below ("component1" => "component2" => "component3"), directly, without having to retransmit the information through the components in between (in this case through "component2"). Hence, the API allows to set props by skipping the components in between, i.e. not every component down a path must convey the prop value until it reaches its destination, and the prop value will be set on the context of the destination component and not pollute the contexts of the components in between.
Armed with these capabilities, the API allows for powerful customization of components, which enables to produce a wide array of layouts and functionalities for different use cases. For instance, in the image below a component <ShareButtons>
is embedded twice, printing descriptions ("Facebook", "Twitter", etc) or not just by setting property "show-description" as true
or false
:
And in the image below, a component can be rendered in three different fashions simply by overriding what classes are printed in the component:
The webpage is its own API endpoint
PoP will issue only one request to fetch all the data for all components in the page, normalizing the database data for all results. The API endpoint to be called is simply the same as the webpage URL for which we are fetching the data, just adding an additional parameter output=json
to indicate to bring the data in JSON format instead of printing it as HTML:
The component is its own API
Every component can interact with itself from client to server just by adding its component path to the webpage URL in which it has been included. This way, when creating a component, we don't need to create an API to go alongside with it (such as REST or GraphQL), because the component is already able to talk to itself in the server and load its own data: it is completely autonomous and self-serving.
This is accomplished by allowing to select what component paths (i.e. the path to a specific component starting from the top-most component) will be included in the response, so as to load data only starting from that level, and ignore anything above that level. This is done through adding parameters componentFilter=componentpaths
and componentpaths[]=path-to-the-component
to the URL (we use componentpaths[]
instead of componentpaths
for versatility, so that we can include more than one component path in a single request). The value for the componentpaths[]
parameter is a list of components separated by dots. Hence, fetching data for component "component5", located under component1 => component2 => component5
, is done by adding parameter componentpaths[]=component1.component2.component5
to the URL.
For instance, in the following component hierarchy every component is loading data, hence every level has an entry objectIDs
:
Then requesting the webpage URL adding parameters componentFilter=componentpaths
and componentpaths[]=component1.component2.component5
will produce the following response:
In essence, the API starts loading data starting from component1 => component2 => component5, that's why "component6", which comes under "component5", also brings its data, but "component3" and "component4" do not.
Each component that loads data exports the URL to interact with it under entry dataloadsource
from under section datasetcomponentmeta
:
Architecture Design and Implementation
In PoP, a component is called a "component", so from now on the terms "component" and "component" are used interchangeably.
Component Hierarchy and JSON Output
The relationship of all components wrapping each other, from the top-most component all the way down to the last level, is called the component hierarchy. This relationship can be expressed through an associative array (an array of key => property) on the server-side, in which each component states its name as the key attribute and its inner components under property "components":
Please notice how components are nested. This way, component properties will never collide with each other if having the same name, avoiding having to add namespaces for components. For instance, the property "class"
from one component's configuration will not override property "class"
from another component's configuration.
The API then simply encodes this array as a JSON object for consumption. Its format is a specification all by itself: As long as the server returns the JSON response in its required format, the client can consume the API independently of how it is implemented:
The relationship among components is defined on a strictly top-down fashion: a component wraps other components and knows who they are, but it doesn't know, and doesn't care, which components are wrapping him. For instance, in the JSON code above, component "component-level1"
knows it wraps components "component-level11"`` and "component-level12"
, and, transitively, it also knows it wraps "component-level121"
; but component "component-level11"
doesn't care who is wrapping him, consequently is unaware of "component-level1"
.
Having the component-based structure, we can now add the actual information required by each component, which is categorized into either settings (such as configuration values and other properties) and data (such as the IDs of the queried database objects and other properties), and placed accordingly under entries componentsettings
and datasetcomponentdata
:
Component properties (configuration values, what database data to fetch, etc) and descendant components are not added manually to the associative array. Instead, they are defined through an object called a ComponentProcessor on a component by component basis. The PoP engine will traverse all components in the component hierarchy, starting from the entry component, fetch the properties for each from the corresponding ComponentProcessor, and create the nested associative array with all properties for all components. A ComponentProcessor for a component called COMPONENT_SOMENAME
looks like this:
Database object data is retrieved and placed under a shared section called databases
, to avoid duplicating information when 2 or more different components fetch the same objects from the database. In addition, it is added in a relational manner to the associative array and printed in the JSON response, to avoid duplicating information when 2 or more different database objects are related to a common object (such as 2 posts having the same author). In other words, database object data is normalized. The structure is a dictionary, organized under each object type first and object ID second, from which we can obtain the object properties:
API response example
For instance, the API response below contains a component hierarchy with two components, "page" => "post-feed"
, where component "post-feed"
fetches blog posts. Please notice the following:
- Each component knows which are its queried objects from property
objectIDs
(IDs 4 and 9 for the blog posts) - Each component knows the object type for its queried objects from property
outputKeys
(each post's data is found under "posts", and the post's author data, corresponding to the author with the ID given under the post's property "author", is found under "users"): - Because the database object data is relational, property "author" contains the ID to the author object instead of printing the author data directly
Definition of a Component
Every component has a unique name that identifies it, defined as a constant:
All the properties of the components are implemented through objects called ComponentProcessor.
Virtual Components
Virtual components are "dynamically-generated" components: components with a base personality and dynamic behaviour. For instance, the custom-querying capabilities of the API create the component hierarchy based on the value of URL parameter query
, creating a virtual component along its path for each of the nested relationships.
Virtual components cannot depend on props for defining their behaviour, because at the time of creating the component hierarchy we don't have the $props
available (otherwise it's a chicken or egg situation). Hence, the particular properties given to a virtual component are coded into the component name itself. Then, the personality of the component is given by the component with name "componentname"
, and the virtual component attributes are the runtime element which define its dynamic behaviour.
ComponentProcessor
A ComponentProcessor is an object class in which to define all the properties of a component. ComponentProcessors are implemented following the SOLID methodology, establishing an object inheritance scheme to progressively add properties to components. The base class for all ComponentProcessors is AbstractComponentProcessor
:
In practice, because a component is implemented through a ComponentProcessor object, describing a component equals to describing how the ComponentProcessor implements all functions to define the properties of the component.
Every ComponentProcessor can handle more than 1 component: Because different components will naturally share many properties, then having a single ComponentProcessor implement many components is more legible and reduces the amount of code required compared to having 1 ComponentProcessor per component. Which components are handled by the ComponentProcessor is defined through function getSubcomponentsToProcess
:
Once the ComponentProcessor class is instantiated, all of its defined components become available to be added to the component hierarchy.
To access the properties of a component, we must reference its corresponding ComponentProcessor through function getComponentProcessor
from class ComponentProcessor_Manager
:
Anatomy of a Component
Because a ComponentProcessor can handle several components, then each of its functions will receive a parameter $component
indicating which is the component being processed. Please notice how, inside the function, we can conveniently use switch
statements to operate accordingly (components with shared properties can easily share the logic) and, according to SOLID, we first obtain the results of the parent class and then the ComponentProcessor adds its own properties:
In addition to parameter $component
, most functions will also receive a $props
parameter, with the value of the "props" set on the component (more on section Props):
Composition
Components are composed of other components through function getSubcomponents
:
Note: the component hierarchy is created by calling
getSubcomponents
on the entry-component and then repeating the process, iteratively, for its descendant components.
Abstract ComponentProcessors can define what descendant components will be required through placeholder functions, to be implemented by an inheriting ComponentProcessor:
Function Names and Caching
The component hierarchy depends not on the URL, but on what components are needed in that URL. Hence, a component hierarchy included in different URLs can be cached and reused across them. For instance, requesting /events/1/
/events/2/
will most like have the same component hierarchy. Then, the 2nd request can reuse the cached component hierarchy from the first request, avoiding to calculate all required properties again and thus optimizing performance.
Most properties can be cached, however a number of them cannot be cached. For instance, adding configuration property "classname"
with value post-{id}
, where ID is the id of the requested post, cannot be cached, since the ID depends directly on the URL. To address this and maximize how much caching can be achieved, PoP has split component properties into non-overlapping segments: "cacheable" and "non-cacheable", and implemented through appropriate functions.
Caching is carried out on two different areas: the server-side and the client-side. All functionality will be required on the server, however not everything will necessarily reach the client. For instance, "props" are used to modify configuration values; while configuration values are sent to the client, the "props" themselves are not. Caching for these two cases is different, and as such the functions to define them will be different, as explained next.
Server-side only Properties: Model and Request
Properties that will only required on the server-side of the application, and never reach the client, can be divided into "model" and "request":
- model: it is a synonym of "component hierarchy". It represents all those component properties which are fixed to the component hierarchy. Hence, when caching the component hierarchy on the server, these properties can be included in the cache.
- request: properties which can change based on the requested URL, hence they cannot be included when caching the component hierarchy.
For instance, a prop "description"
setting value "Welcome to my site!"
is immutable within the component hierarchy, hence it can be set in a model
function. Prop "classname"
with value post-{id}
, where ID is the id of the requested post, which depends directly on the URL, must be set under a request
function.
Client-side Properties: Immutable, Mutable on Model, and Mutable on Request
Properties which are sent to the client-side (eg: configuration values) can also be cached on the client-side application, so that once a component hierarchy has been loaded, we can avoid fetching this information again and, if we already have all the data to satisfy the request, we can render a layout without even having to communicate with the server.
Caching on the server-side is easy: each component hierarchy is cached on its own file, so these can be handled independently. In the client-side, however, we will be caching together the JSON response from different requests, involving different component hierarchies which have shared properties, and we want to cache these shared properties only once in total instead of once per request. For instance, requesting /posts/1
may have component hierarchy "singlepost" => "postlayout"
, while /events/1
may have component hierarchy "singlepost" => "eventlayout"
. In this case, the first level, "singlepost"
, is shared across different requests.
To deal with this situation, we need to make the naming of functions a bit more granular: the term model
explained above has been further split into two, immutable
and mutable on model
, and the term request
has been renamed as mutable on request
. How and why this works is explained in detail in section Client-side caching of the "Architecture Design and Implementation" document.
The difference between immutable
and mutable on model
is that properties on mutable on model
can change their value depending on the component's descentant components:
- immutable: properties which are fixed
- mutableonmodel: properties which can change based on the descendant components
- mutableonrequest: properties which can change based on the requested URL
For instance, we could have a configuration property "descendants"
explicitly declaring the names of its descendant components. In the example below, component "singlepost"
has descendant component "postlayout"
and configuration property "descendants"
with value ["postlayout"]
:
Then, properties are filled like this: class: "text-center"
is immutable
, descendants: ["component2"]
is mutable on model
, and class: "post-37"
, which corresponds to post-{id}
, is mutable on request
.
Props
Components are most useful when they are generic and enable customization through properties, or "props". For instance, a component can define a prop to change the background color configuration value, define how many objects to fetch from the database, or anything it may need.
Setting props works in one direction only: components can set props on any descendant component, but no component can set props on any ancestor component or on any component belonging to a different branch from the component hierarchy. In the structure below, "component1" can set props on "component2", "component3" and "component4", "component2" on "component3", and "component3" and "component4" on nobody:
Components can set props on descendant components whichever number of levels below in the component hierarchy, and it is done directly, i.e. without involving the components in between or affecting their props. In the structure above, "component1" can set a prop directly on "component3" without going through "component2".
Setting props is done through functions initModelProps($component, &$props)
and initRequestProps($component, &$props)
. A prop must be implemented in either function, but not on both of them. initRequestProps
is used for defining props that depend directly on the requested URL, such as adding a classname post-{id}
to prop "class"
, where {id}
is the ID of the requested post on that URL. initModelProps
is used for everything else.
Setting props is done at the very beginning: Immediately after obtaining the component hierarchy, PoP Engine will invoke these 2 functions before anything else (i.e. before getting the configuration, fetching database data, etc). Hence, with the exception of the functions to create the component hierarchy (i.e. getSubcomponents
and those inner functions invoked by getSubcomponents
), every function in the ComponentProcessor
can receive $props
.
initModelProps
and initRequestProps
store the props under parameter $props
, hence it is passed by reference. In all other functions, $props
may also be passed by reference, but only for performance issues, to not duplicate the object in memory.
Inside these 2 functions, we get to set the props through the following 3 functions:
function setProp($component_or_componentpath, &$props, $field, $value, $starting_from_componentpath = array())
function appendProp($component_or_componentpath, &$props, $field, $value, $starting_from_componentpath = array())
function mergeProp($component_or_componentpath, &$props, $field, $value, $starting_from_componentpath = array())
These 3 functions are similar to each other, with the following differences:
appendProp
is used to append a value to an existing prop, hence it is a cumulative property. It is often used for adding classnames. For instance, having components "component1" and "component2" both execute appendProp
on "component3" for property "class"
with values "big"
and "center"
respectively, will make the "class"
property of "component3" be set as "big center"
.
mergeProp
is similar, but concerning arrays. It is often used for adding params to be printed on the element in the DOM. For instance, having components "component1" and "component2" both execute mergeProp
on "component3" for property "params"
with values ["data-target" => "#main"]
and ["data-mode" => "static"]
respectively, will make the "params"
property of "component3" be set as ["data-target" => "#main", "data-mode" => "static"]
.
setProp
is not cumulative, but accepts only 1 value: that one that is set the first. Hence, higher-level components have priority for setting a property value over lower-level ones along the component hierarchy. For instance, having components "component1" and "component2" both execute setProp
on "component3" for property "title"
with values "First title"
and "Second title"
respectively, will make the "title"
property of "component3" be set as "First title"
.
All 3 methods receive the same parameters:
$component_or_componentpath
: This value can either be a string with the name of the component on which to set the prop, or an array. If it is the name of the component, there are 2 possibilities: if the target component is the same component setting the prop, then the component is setting a prop on itself (eg: to set the default value for the prop); if not, it will set a prop on the descendant component with that name wherever it is found along the subcomponent hierarchy. If it is an array, then this is already the subpath to the targeted descendant component where to set the prop.&$props
: This is the object storing all the props, a unique object passed across all components along the component hierarchy to initialize all props$field
: Name of the property$value
: Value to set on the property$starting_from_componentpath
: Array with a component subpath from which to find the target component where to set the prop
Every component first initializes its own props, and only then continues the flow to the parent class, so that inheriting classes have priority over their ancestors in the object inheritance scheme:
Accessing the value of the prop is done through function getProp($component, &$props, $field, $starting_from_componentpath = array())
. The signature of the function is similar to the ones above, however without parameter $value
.
Let's see an example: a component for rendering maps has 2 orientations: "horizontal"
and "vertical"
. It is composed by components "map" => "map-inner"
, and both these components need this property. Component "map"
will set the value by default to "vertical"
, obtain the value for this prop just in case an ancestor component had already set the prop, and then set this value on component "map-inner"
. Function below is implemented for component "map"
:
By default, component map will have prop "orientation"
set with value "vertical"
. However, parent component "map-wrapper"
can set this prop beforehand to "horizontal"
:
Data-Loading
Along the component hierarchy, certain components will define what objects from the database are required, and their descendants will indicate what properties the database object must have. Consider the image below, in which a component "singlepost"
defines to what DB object to load, and its descendant components "post-title"
and "post-content"
indicate that the object must have properties "title"
and "content"
loaded:
Dataloading Components
Those components indicating what DB objects must be loaded are called "dataloading" components. To do this, dataloading components must define the functions and properties below.
Defining the DataSource
Indicate if the results are immutable
(eg: results which never change and are cacheable) or mutable on request
, through function getDatasource
. By default results are set as mutable on request
(through constant \PoP\ComponentModel\Constants\DataSources::MUTABLEONREQUEST
), so only when results are immutable
this function must be implemented:
Defining the Database Object IDs
Define the IDs of the objects to be retrieved from the database, through function getDbobjectIds
. If the component already knows what database objects are required, it can simply return them:
However, most likely, the objects are not known in advance, and must be found through a query. In this case, the ComponentProcessor must inherit from class QueryDataAbstractComponentProcessor
, which implements getDbobjectIds
transferring the responsibility of finding the database object IDs to function getDbobjectIds
from the corresponding Dataloader.
Defining the Dataloader
Define what Dataloader to use, which is the object in charge of fetching data from the database, through function getDataloader
:
Defining the Query Args
Customize a query to filter data, which is passed to the Dataloader, through functions getImmutableDataloadQueryArgs
and getMutableonrequestDataloadQueryArgs
:
Defining the QueryInputOutputHandler
After fetching data, we can communicate state (eg: are there more results? what's the next paging number? etc) through Data-Posting and Operations):
Defining the Data Properties
If the component needs to pass a variable to any other object involved in fetching/processing data (ActionExecuter, etc), it can do so through "data properties", set through functions getImmutableHeaddatasetcomponentDataProperties
and getMutableonrequestHeaddatasetcomponentDataProperties
:
Conditionally Loading Database Data
We can instruct a dataloading component to not load its data simply by setting its prop "skip-data-load"
to true
:
Note: Being a prop, this value can be set either by the dataloading component itself, or by any of its ancestor components.
Among others, the following are several uses cases for not loading the data for a component:
- Loading the Search page without any search parameter
- Validate that the logged-in user has the required permissions
- Load data not when loading the site, but only when loading a page in an SPA
Dataloading + Descendant Components
Starting from a dataloading component, and including itself, any descendant component can execute the functions described below: loading properties or "data fields" on the database object, and "switching domain" from the current database object to another one.
Defining the Data-Fields
"Data fields", which are the properties to be required from the loaded database object, are defined through function getLeafComponentFieldNodes
:
The value for "data-fields" is resolved through an object called a ObjectTypeFieldResolver, described below.
Switching domain to a relational object
When defining what data to retrieve, we can also "switch domain", which is changing from the current database object to another one, defined as a relationship.
Consider the image below: Starting from the object type "post", and moving down the component hierarchy, we will need to shift the DB object type to "user" and "comment", corresponding to the post's author and each of the post's comments respectively, and then, for each comment, it must change the object type once again to "user" corresponding to the comment's author. After switching to a new domain, from that level at the component hierarchy downwards, all required properties, or data-fields, will be subjected to the new domain: Property "name" is fetched from the "user" object representing the post's author, "content" from the "comment" object representing each of the post's comments, and then "name" from the "user" object representing the author of each comment:
Switching domins is accomplished through function getRelationalComponentFieldNodes
. It must return an array, in which each key is the property, or "data-field", containing the ID of the object to switch to, and its value is another array, in which the key is the Dataloader to use to load this object, and its values are the components to use:
Note: Similar to
getComponents
, this method also loads components into the component hierarchy, hence it cannot receive parameter$props
.
Alternatively, instead of explicitly defining the name of the dataloader, we can also select the default dataloader defined for that field through constant POP_CONSTANT_SUBCOMPONENTDATALOADER_DEFAULTFROMFIELD
, which are defined through the ObjectTypeFieldResolver. In the example below, the default dataloaders for fields "author"
and "comments"
will be automatically selected:
Dataloader
The dataloader object is in charge of fetching database data. It knows what type of data it must fetch (posts, users, comments, etc) and how to do it. All dataloaders inherit from class Dataloader
. Given an array of IDs, it must fetch the corresponding objects from the database, through function executeGetData
:
For instance, a dataloader fetching posts will implement the function like this:
The dataloader must also implement the following functions:
getFieldprocessor
: return the name of the ObjectTypeFieldResolver that will handle the data-fields for all objects returned by the dataloadergetDatabaseKey
: return the object type under which objects returned by the dataloader will be stored underdatabases
in the JSON response
For instance, a dataloader fetching posts will implement these functions like this:
In addition, most likely dataloader will also be in charge of obtaining the $ids
to fetch from the database. In this case, it must inherit from class QueryDataDataloader
, and implement function getDbobjectIds
:
For instance, a dataloader fetching the single post will simply return the object ID of the post in the Context Vars:
Dataloaders fetching lists of results (eg: a list of posts, a list of users, etc) will need to execute a query and filter the results. This logic has been implemented in trait Dataloader_ListTrait
, which requires to implement functions getQuery
to generate the query from the $query_args
provided through Data Properties, and executeQueryIDs
to, given the generated $query
, return the list of object IDs:
For instance, a dataloader fetching a list of posts will be implemented like this:
ObjectTypeFieldResolver
The ObjectTypeFieldResolver is the object resolving "data-fields" to their corresponding value. It must inherit from class AbstractObjectTypeFieldResolver
, and implement function getValue
, which receives two parameters, $resultitem
which is the database object, and $field
which is the data-field to resolve, and must return the value for that property applied to the database object.
Note: the names of fields cannot include the following special characters: "," (
\PoP\ComponentModel\Tokens\Param::VALUE_SEPARATOR
), "." (POP_CONSTANT_DOTSYNTAX_DOT
) or "|" (POP_CONSTANT_PARAMFIELD_SEPARATOR
)
For instance, a ObjectTypeFieldResolver for posts looks like this:
The ObjectTypeFieldResolver also allows to select the default dataloader to process a specific field through function getFieldDefaultDataloader
. This feature is required for switching domain through function getRelationalComponentFieldNodes
and deciding to not explicitly indicate the dataloader to use to load relationships, but use the default one for that field instead. For instance, for the fieldprocessor for posts, it is implemented like this:
ObjectTypeFieldResolverExtension
A ObjectTypeFieldResolverExtension is an object that allows to resolve data-fields for specific ObjectTypeFieldResolvers, either to override their value or to extend them. For instance, it can be implemented at the application level, resolving those application-specific data fields. It must inherit from class ObjectTypeFieldResolver_HookBase
and implement function getValue
, which receives three parameters, $resultitem
which is the database object, $field
which is the data-field to resolve, and $fieldprocessor
which is the ObjectTypeFieldResolver object hooked into, and must return the value for that property applied to the database object.
For instance, a ObjectTypeFieldResolverExtension for posts might add a custom "disclaimer" message, and it looks like this:
Filtering Data
By implementing the interface DataloadQueryArgsFilter
components can also filter the data fetched by the ancestor dataloading component. For that, they must implement functions filterDataloadQueryArgs
, to filter the query for some property, and getValue
, to provide the corresponding value. For instance, a component that performs a search of content looks like this (notice that since it extends from TextFormInputsBase
, its getValue
function is already implemented by class FormInputsBase
):
QueryInputOutputHandler
The QueryInputOutputHandler is an object that synchronizes the state of the query between client and server. It must inherit from class QueryInputOutputHandlerBase
and implement the following functions:
Before fetching data from the database, function prepareQueryArgs
populates the $query_args
object used passed to the dataloader to fetch data. It can get values from the request (eg: set through the application in the client) or define default values.
After fetching data from the database, functions getQueryState
, getQueryParams
and getQueryResult
, all of them receiving parameters $data_properties, $checkpoint_validation, $executed, $objectIDs
, send information about the executed query back to the client: state values (eg: are there more results?), parameter values (eg: how many results to bring each time) and result values (eg: was execution successful?) correspondingly.
ActionExecuter
In addition to loading data, "dataloading" components can also post data, or execute any operation supported by the underlying CMS (log in/out the user, send emails, logging, etc).
To achieve this, the ComponentProcessor must define the ActionExecuter object for the component through function getActionExecuterClass
:
The ActionExecuter is an object to execute actions or operations. It must inherit from class AbstractActionExecuter
, and implement function execute
:
For instance, an ActionExecuter to log the user out will look like this:
Storing and reusing the results from an execution
The results obtained in function execute
can be stored for other objects (ComponentProcessors, ActionExecuters) to use and base their logic upon them. For instance, a component is able to load data or not depending on the success or not of an execution.
Storing and accessing the execution results is done through function setResult
and getResult
from the ActionExecution_Manager
object. For instance, an ActionExecuter to create a comment will store the new comment ID:
A ComponentProcessor can modify what data it will fetch from the database through function prepareDataPropertiesAfterMutationExecution
, which is invoked after executing the component's corresponding ActionExecuter. For instance, after creating a comment, we can load it immediately or, if the creation was not successful, state to skip loading any database object:
Checkpoints
A "checkpoint" is a condition that must be satisfied when performing an operation-access validation. These validations do not include content validations, such as checking if the user has filled-in the form correctly; instead, they are used to find out if the user can access a certain page or functionality, such as checking if the user is logged in to access the user account page, checking if the user IP has been whitelisted to execute special scripts, etc.
Components can specify their checkpoints through 2 functions in the ComponentProcessor:
getDataAccessCheckpoints
: Define the checkpoints to access data for the component: both load data or execute the component's actionexecutergetActionExecutionCheckpoints
: Define the checkpoints to execute the component's actionexecuter
The reason why these 2 functions are split like is, is to allow a page perform the validation only when posting data. Then, an "Add Post" page can require no checkpoints when first loaded, which enables to cache it, and only perform the validation (eg: is user logged in?) when executing the POST operation and triggering the actionexecuter.
For instance, a component that needs to validate that the user's IP is whitelisted can do it like this:
Pages can also be assigned checkpoints through their SettingsProcessor. Whenever a component is directly associated with a page (eg: component COMPONENT_MYPOSTS_SCROLL
is directly associated to POP_PAGE_MYPOSTS
) then it is assigned the checkpoints associated with that page. Associating a component with a page is done through function getRelevantPage
from the ComponentProcessor, like this:
A checkpoint is resolved through a Checkpoint.
Checkpoint
A Checkpoint is an object inheriting from class AbstractCheckpoint
, which handles checkpoints, resolving if a checkpoint is satisfied or not through function process
. When a checkpoint is not satisfied, it must thrown an error. Otherwise, the base class will eventually return true
, signalling that the validation is satisfied.
For instance, to validate if the user IP is whitelisted can be implemented like this:
Extra URIs
Will be added soon...
DataStructureFormatter
Will be added soon...
ComponentDecoratorProcessor
Will be added soon...
ComponentFilter
Will be added soon...
Context Vars
It is a global variable, hosted under PoP_ComponentManager_Vars::$vars
, accessed through PoP_ComponentManager_Vars::getVars
, and naturally referred as $vars
, which holds important information needed to process the webpage. Properties in $vars
are those which are accessed widely throughout the application, and which, upon changing their value, alter the component hierarchy.
1. Properties which are accessed widely throughout the application
$vars
acts as a single, central repository of information, where properties can be calculated just once or initialized with default values, and promoting consistency, by providing a unique place from where to fetch a certain value from anywhere in the application.
For instance, property output
, which is obtained through $_GET["output"]
and accepts values "HTML"
or "JSON"
, is accessed through $vars['output']
, and is initialized to value "HTML"
if $_GET["output"]
is empty.
2. Properties which, upon changing their value, alter the component hierarchy
Changing the values of certain properties will alter the component hierarchy. For instance, passing parameter componentFilter=componentpaths
in the URL will make the component hierarchy only include those components specified under parameter componentpaths[]
. Hence, property componentFilter
must be in $vars
.
Keeping these properties in $vars
is needed for the following reasons:
1. To calculate the modelInstanceId
: the modelInstanceId
is the unique identifier representing the particular instance of the component hierarchy. This id is calculated by function ModelInstanceProcessor_Utils::getModelInstanceID()
, which simply calculates a hash of the values of all properties which alter the component hierarchy. Because not all properties in $vars
alter the component hierarchy, these ones must be defined by implementing hook "ModelInstanceProcessor:model_instance_components"
.
2. To determine the entry component: The component hierarchy's top-most component is called the entry component. Every potential entry component must define a list of conditions, to be evaluated against $vars
, that need be satisfied to be chosen the entry component (more on this under PageComponentProcessors).
3. To decouple processed page from requested page: Storing all properties which modify the component hierarchy under $vars
, making sure that these properties are only accessed through $vars
all throughout the application, and then modifying these values directly in $vars
, makes it possible to manipulate the response, for instance adding more data. This way, it is possible to fetch more than one page's content on a single request (for preloading views to cache on the client or other use cases), or send personalized transactional emails to many users on a single request, among other use cases.
Setting properties in $vars
When first accessed, $vars
is initialized with certain current request values, such as:
- Hierarchy (home, single, page, author, etc)
- Output (HTML, JSON, etc)
- Component filter, if any
- Mangled output?
- The queried object (the post object in single hierarchy, the user object in author hierarchy, etc)
- Others
Plugins must add their own properties and corresponding values in $vars
by implementing hook "\PoP\ComponentModel\Engine_Vars:add_vars"
. $vars
can be reset
at any moment and filled with different values, for instance to process a different request.
PageComponentProcessor
Will be added soon...
SettingsProcessor
Will be added soon...
Component Model Cache
Will be added soon...
PHP versions
Requirements:
- PHP 8.1+ for development
- PHP 7.4+ for production
Supported PHP features
Check the list of Supported PHP features in GatoGraphQL/GatoGraphQL
Preview downgrade to PHP 7.4
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
To execute PHPUnit, run:
Static Analysis
To execute PHPStan, run:
Report issues
To report a bug or request a new feature please do it on the GatoGraphQL monorepo issue tracker.
Contributing
We welcome contributions for this package on the GatoGraphQL 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.
All versions of component-model with dependencies
composer/semver Version ^3.2
getpop/componentrouting Version ^6.0.2
getpop/definitions Version ^6.0.2
getpop/graphql-parser Version ^6.0.2
getpop/loosecontracts Version ^6.0.2
jrfnl/php-cast-to-type Version ^2.0
league/pipeline Version ^1.0
psr/simple-cache Version ^3.0
symfony/cache Version ^6.0
symfony/expression-language Version ^6.0