Service examples for PHP
Elasticsearch Sample Code
Source
<?php
declare(strict_types=1);
use Elasticsearch\ClientBuilder;
use Platformsh\ConfigReader\Config;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// Get the credentials to connect to the Elasticsearch service.
$credentials = $config->credentials('elasticsearch');
try {
// The Elasticsearch library lets you connect to multiple hosts.
// On Platform.sh Standard there is only a single host so just
// register that.
$hosts = [
[
'scheme' => $credentials['scheme'],
'host' => $credentials['host'],
'port' => $credentials['port'],
]
];
// Create an Elasticsearch client object.
$builder = ClientBuilder::create();
$builder->setHosts($hosts);
$client = $builder->build();
$index = 'my_index';
$type = 'People';
// Index a few document.
$params = [
'index' => $index,
'type' => $type,
];
$names = ['Ada Lovelace', 'Alonzo Church', 'Barbara Liskov'];
foreach ($names as $name) {
$params['body']['name'] = $name;
$client->index($params);
}
// Force just-added items to be indexed.
$client->indices()->refresh(array('index' => $index));
// Search for documents.
$result = $client->search([
'index' => $index,
'type' => $type,
'body' => [
'query' => [
'match' => [
'name' => 'Barbara Liskov',
],
],
],
]);
if (isset($result['hits']['hits'])) {
print <<<TABLE
<table>
<thead>
<tr><th>ID</th><th>Name</th></tr>
</thead>
<tbody>
TABLE;
foreach ($result['hits']['hits'] as $record) {
printf("<tr><td>%s</td><td>%s</td></tr>\n", $record['_id'], $record['_source']['name']);
}
print "</tbody>\n</table>\n";
}
// Delete documents.
$params = [
'index' => $index,
'type' => $type,
];
$ids = array_map(function($row) {
return $row['_id'];
}, $result['hits']['hits']);
foreach ($ids as $id) {
$params['id'] = $id;
$client->delete($params);
}
} catch (Exception $e) {
print $e->getMessage();
}
Output
ID | Name |
WbGc6pUB4Y_uW66_5cN6 | Barbara Liskov |
InfluxDB Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
use InfluxDB\Client;
use InfluxDB\Database;
use InfluxDB\Point;
use InfluxDB\Database\RetentionPolicy;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// Get the credentials to connect to the InfluxDB service.
$credentials = $config->credentials('influxdb');
try {
// Connecting to the InfluxDB server. By default it has no user defined, so you will need to create it.
$client = new Client($credentials['host'], $credentials['port']);
$password = base64_encode(random_bytes(12));
$client->admin->createUser('deploy_user', $password, Client\Admin::PRIVILEGE_ALL);
// Now reconnect with an authenticated connection so that we can access a database.
$client = new Client($credentials['host'], $credentials['port'], 'deploy_user', $password);
$database = $client->selectDB('deploys');
// No database is created by default, so it needs to be created by the user.
if (!$database->exists()) {
$database->create(new RetentionPolicy('test', '1d', 2, true));
}
// Write some data.
$points = [
new Point(
'deploy_time', // name of the measurement
0.64, // the measurement value
['host' => 'server01', 'region' => 'us-west'], // optional tags
['cpucount' => 10], // optional additional fields
1546556400 // Time precision has to be set to seconds!
),
new Point(
'deploy_time', // name of the measurement
0.84, // the measurement value
['host' => 'server01', 'region' => 'us-west'], // optional tags
['cpucount' => 10], // optional additional fields
1547161200 // Time precision has to be set to seconds!
),
];
$result = $database->writePoints($points, Database::PRECISION_SECONDS);
// Read the data back.
$result = $database->query('select * from deploy_time LIMIT 5');
$points = $result->getPoints();
if ($points) {
print <<<TABLE
<table>
<thead>
<tr><th>Timestamp</th><th>Value</th></tr>
</thead>
<tbody>
TABLE;
foreach ($points as $point) {
printf("<tr><td>%s</td><td>%s</td></tr>\n", $point['time'], $point['value']);
}
print "</tbody>\n</table>\n";
}
// Drop the database.
$database->drop();
// And remove the user.
$client->admin->dropUser('deploy_user');
} catch (Exception $e) {
print $e->getMessage();
}
Output
Query has failed: unable to parse authentication credentials
Memcached Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// Get the credentials to connect to the Memcached service.
$credentials = $config->credentials('memcached');
try {
// Connecting to Memcached server.
$memcached = new Memcached();
$memcached->addServer($credentials['host'], $credentials['port']);
$memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$key = "Deploy day";
$value = "Friday";
// Set a value.
$memcached->set($key, $value);
// Read it back.
$test = $memcached->get($key);
printf('Found value <strong>%s</strong> for key <strong>%s</strong>.', $test, $key);
} catch (Exception $e) {
print $e->getMessage();
}
Output
Found value Friday for key Deploy day.
MongoDB Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
use MongoDB\Client;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// The 'database' relationship is generally the name of primary database of an application.
// It could be anything, though, as in the case here here where it's called "mongodb".
$credentials = $config->credentials('mongodb');
try {
$server = sprintf('%s://%s:%s@%s:%d/%s',
$credentials['scheme'],
$credentials['username'],
$credentials['password'],
$credentials['host'],
$credentials['port'],
$credentials['path']
);
$client = new Client($server);
$collection = $client->main->starwars;
$result = $collection->insertOne([
'name' => 'Rey',
'occupation' => 'Jedi',
]);
$id = $result->getInsertedId();
$document = $collection->findOne([
'_id' => $id,
]);
// Clean up after ourselves.
$collection->drop();
printf("Found %s (%s)<br />\n", $document->name, $document->occupation);
} catch (\Exception $e) {
print $e->getMessage();
}
MySQL Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// The 'database' relationship is generally the name of primary SQL database of an application.
// That's not required, but much of our default automation code assumes it.
$credentials = $config->credentials('database');
try {
// Connect to the database using PDO. If using some other abstraction layer you would
// inject the values from $database into whatever your abstraction layer asks for.
$dsn = sprintf('mysql:host=%s;port=%d;dbname=%s', $credentials['host'], $credentials['port'], $credentials['path']);
$conn = new \PDO($dsn, $credentials['username'], $credentials['password'], [
// Always use Exception error mode with PDO, as it's more reliable.
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
// So we don't have to mess around with cursors and unbuffered queries by default.
\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
// Make sure MySQL returns all matched rows on update queries including
// rows that actually didn't have to be updated because the values didn't
// change. This matches common behavior among other database systems.
\PDO::MYSQL_ATTR_FOUND_ROWS => TRUE,
]);
// Creating a table.
$sql = "CREATE TABLE People (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
city VARCHAR(30) NOT NULL
)";
$conn->query($sql);
// Insert data.
$sql = "INSERT INTO People (name, city) VALUES
('Neil Armstrong', 'Moon'),
('Buzz Aldrin', 'Glen Ridge'),
('Sally Ride', 'La Jolla');";
$conn->query($sql);
// Show table.
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$result->setFetchMode(\PDO::FETCH_OBJ);
if ($result) {
print <<<TABLE
<table>
<thead>
<tr><th>Name</th><th>City</th></tr>
</thead>
<tbody>
TABLE;
foreach ($result as $record) {
printf("<tr><td>%s</td><td>%s</td></tr>\n", $record->name, $record->city);
}
print "</tbody>\n</table>\n";
}
// Drop table
$sql = "DROP TABLE People";
$conn->query($sql);
} catch (\Exception $e) {
print $e->getMessage();
}
Output
Name | City |
Neil Armstrong | Moon |
Buzz Aldrin | Glen Ridge |
Sally Ride | La Jolla |
PostgreSQL Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// The 'database' relationship is generally the name of primary SQL database of an application.
// It could be anything, though, as in the case here here where it's called "postgresql".
$credentials = $config->credentials('postgresql');
try {
// Connect to the database using PDO. If using some other abstraction layer you would
// inject the values from $database into whatever your abstraction layer asks for.
$dsn = sprintf('pgsql:host=%s;port=%d;dbname=%s', $credentials['host'], $credentials['port'], $credentials['path']);
$conn = new \PDO($dsn, $credentials['username'], $credentials['password'], [
// Always use Exception error mode with PDO, as it's more reliable.
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
]);
$conn->query("DROP TABLE IF EXISTS People");
// Creating a table.
$sql = "CREATE TABLE IF NOT EXISTS People (
id SERIAL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
city VARCHAR(30) NOT NULL
)";
$conn->query($sql);
// Insert data.
$sql = "INSERT INTO People (name, city) VALUES
('Neil Armstrong', 'Moon'),
('Buzz Aldrin', 'Glen Ridge'),
('Sally Ride', 'La Jolla');";
$conn->query($sql);
// Show table.
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$result->setFetchMode(\PDO::FETCH_OBJ);
if ($result) {
print <<<TABLE
<table>
<thead>
<tr><th>Name</th><th>City</th></tr>
</thead>
<tbody>
TABLE;
foreach ($result as $record) {
printf("<tr><td>%s</td><td>%s</td></tr>\n", $record->name, $record->city);
}
print "</tbody>\n</table>\n";
}
// Drop table.
$sql = "DROP TABLE People";
$conn->query($sql);
} catch (\Exception $e) {
print $e->getMessage();
}
Output
SQLSTATE[08006] [7] connection to server at "postgresql.internal" (169.254.38.66), port 5432 failed: FATAL: remaining connection slots are reserved for non-replication superuser connections
RabbitMQ Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// Get the credentials to connect to the RabbitMQ service.
$credentials = $config->credentials('rabbitmq');
try {
$queueName = 'deploy_days';
// Connect to the RabbitMQ server.
$connection = new AMQPStreamConnection($credentials['host'], $credentials['port'], $credentials['username'], $credentials['password']);
$channel = $connection->channel();
$channel->queue_declare($queueName, false, false, false, false);
$msg = new AMQPMessage('Friday');
$channel->basic_publish($msg, '', 'hello');
echo "[x] Sent 'Friday'<br/>\n";
// In a real application you't put the following in a separate script in a loop.
$callback = function ($msg) {
printf("[x] Deploying on %s<br />\n", $msg->body);
};
$channel->basic_consume($queueName, '', false, true, false, false, $callback);
// This blocks on waiting for an item from the queue, so comment it out in this demo script.
//$channel->wait();
$channel->close();
$connection->close();
} catch (Exception $e) {
print $e->getMessage();
}
Redis Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// Get the credentials to connect to the Redis service.
$credentials = $config->credentials('redis');
try {
// Connecting to Redis server.
$redis = new Redis();
$redis->connect($credentials['host'], $credentials['port']);
$key = "Deploy day";
$value = "Friday";
// Set a value.
$redis->set($key, $value);
// Read it back.
$test = $redis->get($key);
printf('Found value <strong>%s</strong> for key <strong>%s</strong>.', $test, $key);
} catch (Exception $e) {
print $e->getMessage();
}
Output
Found value Friday for key Deploy day.
Solr Sample Code
Source
<?php
declare(strict_types=1);
use Platformsh\ConfigReader\Config;
use Solarium\Client;
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();
// Get the credentials to connect to the Solr service.
$credentials = $config->credentials('solr');
try {
$config = [
'endpoint' => [
'localhost' => [
'host' => $credentials['host'],
'port' => $credentials['port'],
'path' => "/" . $credentials['path'],
]
]
];
$client = new Client($config);
// Add a document
$update = $client->createUpdate();
$doc1 = $update->createDocument();
$doc1->id = 123;
$doc1->name = 'Valentina Tereshkova';
$update->addDocuments(array($doc1));
$update->addCommit();
$result = $client->update($update);
print "Adding one document. Status (0 is success): " .$result->getStatus(). "<br />\n";
// Select one document
$query = $client->createQuery($client::QUERY_SELECT);
$resultset = $client->execute($query);
print "Selecting documents (1 expected): " .$resultset->getNumFound() . "<br />\n";
// Delete one document
$update = $client->createUpdate();
$update->addDeleteById(123);
$update->addCommit();
$result = $client->update($update);
print "Deleting one document. Status (0 is success): " .$result->getStatus(). "<br />\n";
} catch (Exception $e) {
print $e->getMessage();
}
Output
Adding one document. Status (0 is success): 0
Selecting documents (1 expected): 1
Deleting one document. Status (0 is success): 0