-
Notifications
You must be signed in to change notification settings - Fork 173
access data from a secondary database
jeff-h edited this page Dec 4, 2015
·
1 revision
This example data provider allows your resource to draw data from a secondary database (i.e. the kind Drupal defines in settings.php
's $databases
array.) This data provider refers to a dbName
value, which is pulled from the resource's annotation data, and which describes which database Drupal should use.
It may be placed anywhere in a PSR-4 filesystem path, but in the given code, it exists at my_module/src/Plugin/DataProvider/DataProviderDbQueryExternalDB.php
.
<?php
/**
* @file
* Contains \Drupal\my_module\Plugin\DataProvider\DataProviderDbQueryExternalDB.
*/
namespace Drupal\my_module\Plugin\DataProvider;
use Drupal\restful\Plugin\resource\DataProvider\DataProviderDbQuery;
class DataProviderDbQueryExternalDB extends DataProviderDbQuery {
/**
* Get a basic query object, using the specified database.
*
* @return \SelectQuery
* A new SelectQuery object for this connection.
*/
protected function getQuery() {
$db_name = $this->options['dbName'];
$table = $this->getTableName();
return \Database::getConnection('default', $db_name)->select($table)->fields($table);
}
}
This would be used by a resource as follows:
?php
/**
* @file
* Contains \Drupal\my_module\Plugin\resource\db_query\participant\Myresource__1_0.
*/
namespace Drupal\my_module\Plugin\resource\db_query\myresource;
use Drupal\restful\Plugin\resource\ResourceDbQuery;
use Drupal\restful\Plugin\resource\ResourceInterface;
/**
* Class Myresource__1_0
* @package Drupal\my_module\Plugin\resource
*
* @Resource(
* name = "myresource:1.0",
* resource = "myresource",
* label = "My Resource",
* description = "Expose my resource to the REST API.",
* authenticationTypes = TRUE,
* authenticationOptional = TRUE,
* dataProvider = {
* "dbName": "my_secondary_db", // As per the key specified in settings.php
* "tableName": "my_table",
* "idColumn": "my_tables_primary_key_column",
* "primary": "my_tables_primary_key_column",
* "idField": "my_tables_primary_key_column",
* },
* majorVersion = 1,
* minorVersion = 0
* )
*/
class Myresource__1_0 extends ResourceDbQuery implements ResourceInterface {
// ...your method overrides here...
/**
* {@inheritdoc}
*/
protected function dataProviderClassName() {
return '\Drupal\my_module\Plugin\DataProvider\DataProviderDbQueryExternalDB';
}
}