4. Producer - nuvoleweb/integration GitHub Wiki
Create a Producer programmatically
To create a Producer programmatically we will make use of the ProducerFactory
static class. In order to have a Producer working correctly we need to add at least one Resource Schema object and a Backend object, so we must create those first.
use Drupal\integration_producer\ProducerFactory;
use Drupal\integration\Backend\BackendFactory;
use Drupal\integration\ResourceSchema\ResourceSchemaFactory;
$resource_schema = ResourceSchemaFactory::create('article')
->setField('title', 'Title')
->setField('image', 'Image')
->setField('body', 'Body');
$backend = BackendFactory::create('filesystem', 'filesystem_backend')
->setBackendSetting('path', '/path/to/data')
->setResourceSchema('article')
->setResourceSchemaSetting('article', 'folder', 'article');
$producer = ProducerFactory::create('article')
->setBackend('filesystem')
->setEntityBundle('article')
->setResourceSchema('article')
->setMapping('title', 'title')
->setMapping('body', 'body');
Note that, at this point, Backend and Resource Schema configuration is only stored in the class static cache. To persist configuration objects in the database use the following:
$backend->getConfiguration()->save();
$resource_schema->getConfiguration()->save();
$producer->getConfiguration()->save();
At this point we can export a node by just executing:
foreach ([1, 2, 3] as $nid) {
$node = node_load($nid);
$document = $producer->push($node);
}
Since we used a filesystem backend our documents have been exported in the form of JSON
files in the /path/to/data
folder:
$ tree /path/to/data
/path/to/data/
└── article
├── node-article-1.json
├── node-article-2.json
└── node-article-3.json
Each JSON
file contains a valid data exchange format document:
$ cat /path/to/data/article/node-article-1.json
{
"_id": "node-article-1",
"default_language": "und",
"languages": [
"und"
],
"fields": {
"subject": {
"und": [
"Lorem ipsum"
]
},
"abstract": {
"und": [
"Vivamus laoreet. Nunc sed turpis. Fusce fermentum."
]
},
"abstract_summary": {
"und": [
""
]
}
},
"type": "article",
"producer": "",
"producer_content_id": "node-article-97",
"created": "2016-01-22 15:29:15",
"updated": "2016-01-22 15:29:15",
"version": "v1"
}