Skip to content

Commit 2927e09

Browse files
committed
Differentiate between mock and cache custom loaders.
1 parent 3330605 commit 2927e09

File tree

1 file changed

+28
-11
lines changed

1 file changed

+28
-11
lines changed

README.md

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -106,31 +106,48 @@ jsonld_set_document_loader('jsonld_default_secure_document_loader');
106106
// set a default custom document loader
107107
jsonld_set_document_loader('my_custom_doc_loader');
108108

109-
// a custom loader that demonstrates checking a simple in-memory cache
110-
// before falling back to the default loader
109+
// a custom loader that demonstrates using a simple in-memory mock for
110+
// certain contexts before falling back to the default loader
111111
// note: if you want to set this loader as the new default, you'll need to
112112
// store the previous default in another variable first and access that inside
113113
// the loader
114-
global $cache;
115-
$cache = array('http://example.com/mycontext' => (object)array(
114+
global $mocks;
115+
$mocks = array('http://example.com/mycontext' => (object)array(
116116
'hombre' => 'http://schema.org/name'));
117-
118-
function custom_load($url) {
119-
global $jsonld_default_load_document, $cache;
120-
if(isset($cache[$url])) {
117+
function mock_load($url) {
118+
global $jsonld_default_load_document, $mocks;
119+
if(isset($mocks[$url])) {
121120
// return a "RemoteDocument", it has these three properties:
122121
return (object)array(
123122
'contextUrl' => null,
124-
'document' => $cache[$url],
123+
'document' => $mocks[$url],
125124
'documentUrl' => $url);
126125
}
127126
// use default loader
128127
return call_user_func($jsonld_default_load_document, $url);
129128
}
130129

131-
// use the custom loader for just this call, witout modifying the default one
130+
// use the mock loader for just this call, witout modifying the default one
132131
$compacted = jsonld_compact($foo, 'http://example.com/mycontext', array(
133-
'documentLoader' => 'custom_load'));
132+
'documentLoader' => 'mock_load'));
133+
134+
// a custom loader that uses a simplistic in-memory cache (no invalidation)
135+
global $cache;
136+
$cache = array();
137+
function cache_load($url) {
138+
global $jsonld_default_load_document, $cache;
139+
if(isset($cache[$url])) {
140+
return $cache[$url];
141+
}
142+
// use default loader
143+
$doc = call_user_func($jsonld_default_load_document, $url);
144+
$cache[$url] = $doc;
145+
return $doc;
146+
}
147+
148+
// use the cache loader for just this call, witout modifying the default one
149+
$compacted = jsonld_compact($foo, 'http://schema.org', array(
150+
'documentLoader' => 'cache_load'));
134151
```
135152

136153
Commercial Support

0 commit comments

Comments
 (0)