This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
There are MANY different ways to handle switching out the data source. Since this course is on Environment Variables, I'm going to show you ONE way to use environment variables by storing a complex data type using JSON.
More Explanation
This video went quickly though a number of items you should already be familiar with. If you would like a refresher, please check the following resources.
- File Handling with PHP - where we cover Reading JSON and Writing JSON
- putenv() function - Sets the value of an environment variable. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state. This can be useful for testing.
- PHP Arrays and Control Structures where we cover switch statements
- Integrating PHP with Databases where we cover PDO
Code Example
// set environment variable
putenv('REPOSITORY={"type":"sqlite","source":"inc/quotes.db"}');
//read environment variable into an object
$repository = json_decode(getenv('REPOSITORY'));
switch ($repository->type) {
case 'text':
$file = file($repository->source);
// grab a random array element
$quote = $file[array_rand($file)];
break;
case 'sqlite':
try {
//if you are working in workspaces you will most likely need to start with 'sqlite:/www/'
$db = new PDO("sqlite:" . $repository->source);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$result = $db->query('SELECT quote FROM Quotes ORDER BY RANDOM() LIMIT 1');
$quote = $result->fetchColumn();
break;
} catch (Exception $e) {
echo "Error!: " . $e->getMessage();
}
default:
$quote = 'It works on my machine.';
}
Optionally you can decode JSON data into an associative array if you prefer, by setting the second parameter of the json_decode function to true.
$repository = json_decode(getenv('REPOSITORY'), true);
switch ($repository['type']) {
...
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up