Skip to content

Commit c31bd09

Browse files
committed
feat: refactor postgres sample to use slim app
1 parent 8e3b542 commit c31bd09

File tree

10 files changed

+539
-185
lines changed

10 files changed

+539
-185
lines changed

cloud_sql/postgres/pdo/README.md

Lines changed: 44 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,62 @@
22

33
## Before you begin
44

5-
1. Before you use this code sample, you need to have [Composer](https://getcomposer.org/) installed or downloaded into this folder. Download instructions can be found [here](https://getcomposer.org/download/).
5+
1. Before you use this code sample, you need to have [Composer](https://getcomposer.org/) installed or downloaded into this folder. Download instructions can be found [here](https://getcomposer.org/download/). Once you've installed composer, use it to install required dependencies by running `composer install`.
66
2. Create a PostgreSQL Cloud SQL Instance by following these [instructions](https://cloud.google.com/sql/docs/postgres/create-instance). Note the connection string, database user, and database password that you create.
77
3. Create a database for your application by following these [instructions](https://cloud.google.com/sql/docs/postgres/create-manage-databases). Note the database name.
88
4. Create a service account with the 'Cloud SQL Client' permissions by following these [instructions](https://cloud.google.com/sql/docs/postgres/connect-external-app#4_if_required_by_your_authentication_method_create_a_service_account). Download a JSON key to use to authenticate your connection.
9-
5. Use the information noted in the previous steps:
9+
10+
## Running Locally
11+
12+
To run this application locally, download and install the `cloud_sql_proxy` by following the instructions [here](https://cloud.google.com/sql/docs/postgres/sql-proxy#install).
13+
14+
To authenticate with Cloud SQL, set the `$GOOGLE_APPLICATION_CREDENTIALS` environment variable:
1015

1116
```bash
1217
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json
13-
export CLOUD_SQL_CONNECTION_NAME='::'
14-
export DB_USER='my-db-user'
15-
export DB_PASS='my-db-pass'
16-
export DB_NAME='my-db-name'
17-
export DB_HOSTNAME='localhost' # If connecting using TCP instead of Unix Sockets
1818
```
1919

20-
Note: Saving credentials in environment variables is convenient, but not secure - consider a more secure solution such as [Cloud KMS](https://cloud.google.com/kms/) to help keep secrets safe.
20+
To run the Cloud SQL proxy, you need to set the instance connection name. See the instructions [here](https://cloud.google.com/sql/docs/postgres/quickstart-proxy-test#get_the_instance_connection_name) for finding the instance connection name.
2121

22-
## Running Locally
22+
```bash
23+
export CLOUD_SQL_CONNECTION_NAME='::'
24+
```
2325

24-
To run this application locally, download and install the `cloud_sql_proxy` by following the instructions [here](https://cloud.google.com/sql/docs/postgres/sql-proxy#install).
26+
Once the proxy is ready, use one of the following commands to start the proxy in the background.
27+
28+
You may connect to your instance via either unix sockets or TCP. To connect using a socket, you must provide the `-dir` option when starting the proxy. To connect via TCP, you must provide a port as part of the instance name. Both are demonstrated below.
2529

26-
Once the proxy is ready, use the following command to start the proxy in the background:
30+
### Unix Socket mode
2731

2832
```bash
29-
$ ./cloud_sql_proxy -dir=/cloudsql --instances=$CLOUD_SQL_CONNECTION_NAME --credential_file=$GOOGLE_APPLICATION_CREDENTIALS
33+
$ ./cloud_sql_proxy -dir=/cloudsql \
34+
--instances=$CLOUD_SQL_CONNECTION_NAME \
35+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
3036
```
3137

3238
Note: Make sure to run the command under a user with write access in the `/cloudsql` directory. This proxy will use this folder to create a unix socket the application will use to connect to Cloud SQL.
3339

40+
### TCP mode
41+
42+
```bash
43+
$ ./cloud_sql_proxy \
44+
--instances=$CLOUD_SQL_CONNECTION_NAME=tcp:5432 \
45+
--credential_file=$GOOGLE_APPLICATION_CREDENTIALS
46+
```
47+
48+
### Set Configuration Values
49+
50+
Set the required environment variables for your connection to Cloud SQL. If you are using TCP mode as described above, do not set the `CLOUD_SQL_CONNECTION_NAME` variable.
51+
52+
```bash
53+
export DB_USER='my-db-user'
54+
export DB_PASS='my-db-pass'
55+
export DB_NAME='my-db-name'
56+
export DB_HOSTNAME='localhost'
57+
```
58+
59+
Note: Saving credentials in environment variables is convenient, but not secure - consider a more secure solution such as [Secret Manager](https://cloud.google.com/secret-manager/) to help keep secrets safe.
60+
3461
Execute the following:
3562

3663
```bash
@@ -39,15 +66,16 @@ $ php -S localhost:8080
3966

4067
Navigate towards http://localhost:8080 to verify your application is running correctly.
4168

42-
## Google App Engine Standard
69+
## Google App Engine Flex
4370

44-
To run on GAE-Standard, create an App Engine project by following the setup for these [instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
71+
To run on App Engine Flex, create an App Engine project by following the setup for these [instructions](https://cloud.google.com/appengine/docs/standard/php7/quickstart#before-you-begin).
4572

4673
First, update `app.yaml` with the correct values to pass the environment variables into the runtime.
4774

75+
Then, make sure that the service account `service-{PROJECT_NUMBER}>@gae-api-prod.google.com.iam.gserviceaccount.com` has the IAM role `Cloud SQL Client`.
76+
4877
Next, the following command will deploy the application to your Google Cloud project:
4978

5079
```bash
51-
$ gcloud app deploy
80+
$ gcloud beta app deploy
5281
```
53-

cloud_sql/postgres/pdo/app.yaml

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2018 Google LLC
1+
# Copyright 2020 Google LLC
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -12,18 +12,26 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
runtime: php72
15+
runtime: php
16+
env: flex
1617

1718
# Remember - storing secrets in plaintext is potentially unsafe. Consider using
18-
# something like https://cloud.google.com/kms/ to help keep secrets secret.
19+
# something like https://cloud.google.com/secret-manager/ to help keep secrets
20+
# secret.
1921
env_variables:
20-
CLOUD_SQL_CONNECTION_NAME: ::
22+
CLOUD_SQL_CONNECTION_NAME: "::"
2123
DB_USER: my-db-user
2224
DB_PASS: my-db-pass
23-
DB_NAME: my_db
25+
DB_NAME: my-db
26+
27+
beta_settings:
28+
cloud_sql_instances: "::"
29+
30+
runtime_config:
31+
document_root: .
2432

2533
# Defaults to "serve index.php" and "serve public/index.php". Can be used to
2634
# serve a custom PHP front controller (e.g. "serve backend/index.php") or to
2735
# run a long-running PHP script as a worker process (e.g. "php worker.php").
2836
#
29-
# entrypoint: serve index.php
37+
# entrypoint: serve index.php

cloud_sql/postgres/pdo/composer.json

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "google/cloud-sql-postgres-example",
3+
"autoload": {
4+
"psr-4": {
5+
"Google\\Cloud\\Samples\\CloudSQL\\Postgres\\": "src"
6+
}
7+
},
8+
"autoload-dev": {
9+
"psr-4": {
10+
"Google\\Cloud\\Samples\\CloudSQL\\Postgres\\Tests\\": "src"
11+
}
12+
},
13+
"require": {
14+
"php": ">= 7.2",
15+
"slim/slim": "^4.5",
16+
"slim/twig-view": "^3.1",
17+
"pimple/pimple": "^3.3",
18+
"guzzlehttp/psr7": "^1.6",
19+
"http-interop/http-factory-guzzle": "^1.0"
20+
},
21+
"require-dev": {
22+
"phpunit/phpunit": "^8.5"
23+
}
24+
}

cloud_sql/postgres/pdo/index.php

Lines changed: 49 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,54 @@
11
2-
# Copyright 2018 Google LLC
3-
#
4-
# Licensed under the Apache License, Version 2.0 (the "License");
5-
# you may not use this file except in compliance with the License.
6-
# You may obtain a copy of the License at
7-
#
8-
# http://www.apache.org/licenses/LICENSE-2.0
9-
#
10-
# Unless required by applicable law or agreed to in writing, software
11-
# distributed under the License is distributed on an "AS IS" BASIS,
12-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-
# See the License for the specific language governing permissions and
14-
# limitations under the License.
15-
16-
require_once 'src/DB.php';
17-
require_once 'src/Votes.php';
18-
19-
use Google\Cloud\Samples\CloudSQL\Postgres\DB;
20-
use Google\Cloud\Samples\CloudSQL\Postgres\Votes;
21-
22-
$votes = new Votes(DB::createPdoConnection());
23-
24-
if ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'GET') {
25-
$list = $votes->list();
26-
27-
$vote_count = $votes->count_candidates();
28-
$tab_count = $vote_count['tabs'];
29-
$space_count = $vote_count['spaces'];
30-
31-
include_once("./template.php");
32-
} elseif ($_SERVER['REQUEST_URI'] == '/' && $_SERVER['REQUEST_METHOD'] == 'POST') {
2+
/*
3+
* Copyright 2020 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
declare(strict_types=1);
19+
20+
use GuzzleHttp\Psr7;
21+
22+
include __DIR__ . '/vendor/autoload.php';
23+
24+
$app = include __DIR__ . '/src/app.php';
25+
26+
$app->get('/', function ($request, $response) {
27+
$this->get('votes')->createTableIfNotExists();
28+
29+
return $this->get('view')->render($response, 'template.twig', [
30+
'votes' => $this->get('votes')->listVotes(),
31+
'tabCount' => $this->get('votes')->getCountByValue('TABS'),
32+
'spaceCount' => $this->get('votes')->getCountByValue('SPACES'),
33+
]);
34+
});
35+
36+
$app->post('/', function ($request, $response) {
37+
$this->get('votes')->createTableIfNotExists();
38+
3339
$message = 'Invalid vote. Choose Between TABS and SPACES';
3440

35-
if (!empty($_POST['team']) && in_array($_POST['team'], ['SPACES', 'TABS'])) {
36-
$message = $votes->save($_POST['team']);
41+
$formData = $request->getParsedBody() + [
42+
'voteValue' => ''
43+
];
44+
45+
if (in_array($formData['voteValue'], ['SPACES', 'TABS'])) {
46+
$message = $this->get('votes')->insertVote($formData['voteValue'])
47+
? 'Vote cast for ' . $formData['voteValue']
48+
: 'An error occurred';
3749
}
3850

39-
echo $message;
40-
}
51+
return $response->withBody(Psr7\stream_for($message));
52+
});
53+
54+
$app->run();
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
xml version="1.0" encoding="UTF-8"?>
2+
<phpunit colors="true">
3+
<testsuites>
4+
<testsuite name="CloudSQLPostgresSample">
5+
<directory>testsdirectory>
6+
testsuite>
7+
testsuites>
8+
<filter>
9+
<whitelist>
10+
<directory suffix=".php">srcdirectory>
11+
whitelist>
12+
filter>
13+
phpunit>

cloud_sql/postgres/pdo/src/DB.php

Lines changed: 0 additions & 51 deletions
This file was deleted.

0 commit comments

Comments
 (0)