Skip to content

Commit 05704ea

Browse files
authored
improvements and tests for laravel (GoogleCloudPlatform#334)
* improvements and tests for laravel * removes unix_socket addition, as this was merged in a laravel PR
1 parent 37dd203 commit 05704ea

File tree

5 files changed

+160
-167
lines changed

5 files changed

+160
-167
lines changed
Lines changed: 3 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -1,111 +1,7 @@
11
Laravel on App Engine Flexible Environment
22
==========================================
33

4-
## Overview
4+
**Code and tests for the Google Cloud Community article
5+
[Run Laravel on Google App Engine Flexible Environment][5]**
56

6-
This guide will help you deploy Laravel on [App Engine Flexible Environment][1]
7-
8-
## Prerequisites
9-
10-
Before setting up Laravel on App Engine, you will need to complete the following:
11-
12-
1. Create a project in the [Google Cloud console][2]. Note your **Project ID**, as you will need it
13-
later.
14-
15-
## Install Laravel
16-
17-
1. Use composer to download Laravel and its dependencies
18-
```sh
19-
composer create-project laravel/laravel
20-
```
21-
22-
1. cd laravel
23-
1. composer install
24-
1. php artisan key:generate
25-
26-
## Set up the Database
27-
28-
Laravel on App Engine Flexible uses a database for sessions and cache. This is
29-
to allow the cache and session to persist across instances.
30-
31-
1. Follow the instructions to set up a [CloudSQL Second Generation instance][3]
32-
33-
1. Follow the instructions to
34-
[install the Cloud SQL Proxy client on your local machine][4]. The Cloud SQL
35-
Proxy is used to connect to your Cloud SQL instance when running locally.
36-
37-
1. Use the Cloud SDK from command-line to run the following command. Copy the
38-
connectionName value for the next step.
39-
```sh
40-
gcloud beta sql instances describe [YOUR_INSTANCE_NAME]
41-
```
42-
43-
1. Start the Cloud SQL Proxy using the connection name from the previous step:
44-
```sh
45-
cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306
46-
```
47-
48-
1. Use the MySQL client or similar program to connect to your instance and
49-
create a database for the application. When prompted, use the root password
50-
you configured:
51-
```sh
52-
mysql -h 127.0.0.1 -u root -p -e "CREATE DATABASE laravel;"
53-
```
54-
55-
1. Run the database migrations for Laravel. This can be done by setting your
56-
parameters in `.env` or by passing them in as environemnt variables:
57-
```sh
58-
# create a migration for the session table
59-
php artisan session:table
60-
DB_DATABASE=laravel \
61-
DB_USERNAME=root \
62-
DB_PASSWORD=supersecretpassword \
63-
php artisan migrate --force
64-
```
65-
1. Update `app.yaml` with the values for your database configuration.
66-
67-
1. Finally, edit `config/database.php` and add a line for "unix_socket" to the
68-
'mysql' connection configuration:
69-
```php
70-
'mysql' => [
71-
// ...
72-
'unix_socket' => env('DB_SOCKET', ''),
73-
```
74-
75-
76-
## Copy over App Engine's `app.yaml` File
77-
78-
For your app to deploy on App Engine Flexible, you will need to copy over
79-
`app.yaml`:
80-
81-
```sh
82-
# clone this repo somewhere
83-
git clone https://github.com/GoogleCloudPlatform/php-docs-samples /path/to/php-docs-samples
84-
85-
# copy the file below to the root directory of your Laravel project
86-
cp /path/to/php-docs-samples/appengine/flexible/laravel/app.yaml /path/to/laravel
87-
```
88-
89-
`app.yaml` contains production environemnt variables and App Engine
90-
configuration for your project.
91-
92-
## Add deploy commands to composer
93-
94-
Finally, you need to have scripts run after your application deploys. Add the
95-
following scripts to your project's composer.json:
96-
97-
```json
98-
{
99-
"scripts": {
100-
"post-deploy-cmd": [
101-
"chmod -R 755 bootstrap\/cache",
102-
"php artisan cache:clear"
103-
]
104-
}
105-
}
106-
```
107-
108-
[1]: https://cloud.google.com/appengine/docs/flexible/
109-
[2]: https://console.cloud.google.com
110-
[3]: https://cloud.google.com/sql/docs/create-instance
111-
[4]: https://cloud.google.com/sql/docs/external#install
7+
[5]: https://cloud.google.com/community/tutorials/run-laravel-on-appengine-flexible
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
runtime: php
2+
env: flex
3+
4+
runtime_config:
5+
document_root: public
6+
7+
# required on some platforms so ".env" is not skipped
8+
skip_files: false
9+
10+
env_variables:
11+
# The values here will override those in ".env". This is useful for
12+
# production-specific configuration. However, Feel free to set these values
13+
# in ".env" instead if you prefer.
14+
APP_LOG: errorlog
15+
STORAGE_DIR: /tmp
16+
CACHE_DRIVER: database
17+
SESSION_DRIVER: database
18+
## Set these environment variables according to your CloudSQL configuration.
19+
DB_HOST: localhost
20+
DB_DATABASE: YOUR_DB_DATABASE
21+
DB_USERNAME: YOUR_DB_USERNAME
22+
DB_PASSWORD: YOUR_DB_PASSWORD
23+
DB_SOCKET: /cloudsql/YOUR_CLOUDSQL_CONNECTION_NAME
24+
25+
beta_settings:
26+
# for Cloud SQL, uncomment and set this value to the Cloud SQL
27+
# connection name, e.g.
28+
# "project:region:cloudsql-instance"
29+
cloud_sql_instances: "YOUR_CLOUDSQL_CONNECTION_NAME"

appengine/flexible/laravel/app.yaml

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,12 @@ env: flex
44
runtime_config:
55
document_root: public
66

7+
# required on some platforms so ".env" is not skipped
8+
skip_files: false
9+
710
env_variables:
811
# The values here will override those in ".env". This is useful for
912
# production-specific configuration. However, Feel free to set these values
1013
# in ".env" instead if you prefer.
1114
APP_LOG: errorlog
12-
CACHE_DRIVER: database
13-
SESSION_DRIVER: database
1415
STORAGE_DIR: /tmp
15-
## Set these environment variables according to your CloudSQL configuration.
16-
DB_HOST: localhost
17-
DB_DATABASE: YOUR_DB_DATABASE
18-
DB_USERNAME: YOUR_DB_USERNAME
19-
DB_PASSWORD: YOUR_DB_PASSWORD
20-
DB_SOCKET: /cloudsql/YOUR_CLOUDSQL_CONNECTION_NAME
21-
22-
# required on some platforms so ".env" is not skipped
23-
skip_files: false
24-
25-
beta_settings:
26-
# for Cloud SQL, uncomment and set this value to the Cloud SQL
27-
# connection name, e.g.
28-
# "project:region:cloudsql-instance"
29-
cloud_sql_instances: "YOUR_CLOUDSQL_CONNECTION_NAME"
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
<?php
2+
/**
3+
* Copyright 2016 Google Inc.
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+
namespace Google\Cloud\Samples\AppEngine\Laravel;
19+
20+
use Google\Cloud\TestUtils\AppEngineDeploymentTrait;
21+
use Google\Cloud\TestUtils\ExecuteCommandTrait;
22+
use Google\Cloud\TestUtils\FileUtil;
23+
use Monolog\Logger;
24+
use GuzzleHttp\Client;
25+
26+
class DeployDatabaseSessionTest extends \PHPUnit_Framework_TestCase
27+
{
28+
use AppEngineDeploymentTrait;
29+
use ExecuteCommandTrait;
30+
31+
public static function beforeDeploy()
32+
{
33+
// verify and set environment variables
34+
self::verifyEnvironmentVariables();
35+
36+
// ensure logging output is displayed in phpunit
37+
self::$logger = new Logger('phpunit');
38+
39+
$tmpDir = sys_get_temp_dir() . '/test-' . FileUtil::randomName(8);
40+
41+
// move into the target directory
42+
self::setWorkingDirectory($tmpDir);
43+
self::createLaravelProject($tmpDir);
44+
self::addPostDeployCommands($tmpDir);
45+
46+
// set the directory in gcloud and move there
47+
self::$gcloudWrapper->setDir($tmpDir);
48+
chdir($tmpDir);
49+
}
50+
51+
private static function verifyEnvironmentVariables()
52+
{
53+
$envVars = [
54+
'LARAVEL_CLOUDSQL_CONNECTION_NAME',
55+
'LARAVEL_DB_DATABASE',
56+
'LARAVEL_DB_USERNAME',
57+
'LARAVEL_DB_PASSWORD',
58+
];
59+
foreach ($envVars as $envVar) {
60+
if (false === getenv($envVar)) {
61+
self::fail("Please set the ${envVar} environment variable");
62+
}
63+
}
64+
}
65+
66+
private static function createLaravelProject($targetDir)
67+
{
68+
// install
69+
$laravelPackage = 'laravel/laravel';
70+
$cmd = sprintf('composer create-project --no-scripts %s %s', $laravelPackage, $targetDir);
71+
$process = self::createProcess($cmd);
72+
$process->setTimeout(300); // 5 minutes
73+
self::executeProcess($process);
74+
75+
// copy and set the proper env vars in app.yaml
76+
$appYaml = str_replace([
77+
'YOUR_CLOUDSQL_CONNECTION_NAME',
78+
'YOUR_DB_DATABASE',
79+
'YOUR_DB_USERNAME',
80+
'YOUR_DB_PASSWORD',
81+
], [
82+
getenv('LARAVEL_CLOUDSQL_CONNECTION_NAME'),
83+
getenv('LARAVEL_DB_DATABASE'),
84+
getenv('LARAVEL_DB_USERNAME'),
85+
getenv('LARAVEL_DB_PASSWORD'),
86+
], file_get_contents(__DIR__ . '/../app-dbsessions.yaml'));
87+
file_put_contents($targetDir . '/app.yaml', $appYaml);
88+
89+
// copy over the base .env file
90+
self::execute('cp .env.example .env');
91+
92+
// generate the secret
93+
self::execute('php artisan key:generate');
94+
}
95+
96+
private static function addPostDeployCommands($targetDir)
97+
{
98+
$contents = file_get_contents($targetDir . '/composer.json');
99+
$json = json_decode($contents, true);
100+
$json['scripts']['post-deploy-cmd'] = [
101+
'chmod -R 755 bootstrap\/cache',
102+
];
103+
$newContents = json_encode($json, JSON_PRETTY_PRINT);
104+
file_put_contents($targetDir . '/composer.json', $newContents);
105+
}
106+
107+
public function testHomepage()
108+
{
109+
// Access the blog top page
110+
$resp = $this->client->get('/');
111+
$this->assertEquals(
112+
'200',
113+
$resp->getStatusCode(),
114+
'top page status code'
115+
);
116+
$content = $resp->getBody()->getContents();
117+
$this->assertContains('Laravel', $content);
118+
}
119+
}

appengine/flexible/laravel/test/DeployTest.php

Lines changed: 6 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,6 @@ class DeployTest extends \PHPUnit_Framework_TestCase
3030

3131
public static function beforeDeploy()
3232
{
33-
// verify and set environment variables
34-
self::verifyEnvironmentVariables();
35-
3633
// ensure logging output is displayed in phpunit
3734
self::$logger = new Logger('phpunit');
3835

@@ -41,58 +38,24 @@ public static function beforeDeploy()
4138
// move into the target directory
4239
self::setWorkingDirectory($tmpDir);
4340
self::createLaravelProject($tmpDir);
44-
self::addPostBuildCommands($tmpDir);
41+
self::addPostDeployCommands($tmpDir);
4542

4643
// set the directory in gcloud and move there
4744
self::$gcloudWrapper->setDir($tmpDir);
4845
chdir($tmpDir);
4946
}
5047

51-
private static function verifyEnvironmentVariables()
52-
{
53-
$envVars = [
54-
'LARAVEL_CLOUDSQL_CONNECTION_NAME',
55-
'LARAVEL_DB_DATABASE',
56-
'LARAVEL_DB_USERNAME',
57-
'LARAVEL_DB_PASSWORD',
58-
];
59-
foreach ($envVars as $envVar) {
60-
if (false === getenv($envVar)) {
61-
self::fail("Please set the ${envVar} environment variable");
62-
}
63-
}
64-
}
65-
6648
private static function createLaravelProject($targetDir)
6749
{
6850
// install
69-
$laravelVersion = 'laravel/laravel';
70-
$cmd = sprintf('composer create-project --no-scripts %s %s', $laravelVersion, $targetDir);
51+
$laravelPackage = 'laravel/laravel';
52+
$cmd = sprintf('composer create-project --no-scripts %s %s', $laravelPackage, $targetDir);
7153
$process = self::createProcess($cmd);
7254
$process->setTimeout(300); // 5 minutes
7355
self::executeProcess($process);
7456

75-
// copy and set the proper env vars in app.yaml
76-
$appYaml = str_replace([
77-
'YOUR_CLOUDSQL_CONNECTION_NAME',
78-
'YOUR_DB_DATABASE',
79-
'YOUR_DB_USERNAME',
80-
'YOUR_DB_PASSWORD',
81-
], [
82-
getenv('LARAVEL_CLOUDSQL_CONNECTION_NAME'),
83-
getenv('LARAVEL_DB_DATABASE'),
84-
getenv('LARAVEL_DB_USERNAME'),
85-
getenv('LARAVEL_DB_PASSWORD'),
86-
], file_get_contents(__DIR__ . '/../app.yaml'));
87-
file_put_contents($targetDir . '/app.yaml', $appYaml);
88-
89-
// add "socket" to "config/database.php"
90-
$databaseConfig = str_replace(
91-
"'driver' => 'mysql',",
92-
"'driver' => 'mysql',
93-
'unix_socket' => env('DB_SOCKET', ''),",
94-
file_get_contents($targetDir . '/config/database.php'));
95-
file_put_contents($targetDir . '/config/database.php', $databaseConfig);
57+
// copy in the app.yaml
58+
copy(__DIR__ . '/../app.yaml', $targetDir . '/app.yaml');
9659

9760
// copy over the base .env file
9861
self::execute('cp .env.example .env');
@@ -101,7 +64,7 @@ private static function createLaravelProject($targetDir)
10164
self::execute('php artisan key:generate');
10265
}
10366

104-
private static function addPostBuildCommands($targetDir)
67+
private static function addPostDeployCommands($targetDir)
10568
{
10669
$contents = file_get_contents($targetDir . '/composer.json');
10770
$json = json_decode($contents, true);

0 commit comments

Comments
 (0)