Skip to content

Commit

Permalink
updated for dotenv DB credentials
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-matt-smith committed May 20, 2020
1 parent a57e798 commit 755b30a
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 77 deletions.
5 changes: 5 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
MYSQL_USER=root
MYSQL_PASSWORD=passpass
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_DATABASE=evote
17 changes: 7 additions & 10 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,21 @@ All Notable changes to `pdo-crud-for-free-repositories` will be documented in th
Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles.

## NEXT - 2021...

- some SQL generation (CREATE TABLE etc.)
not sure all seems to be working nicely ....


### Added
2 main changes for this release:

- default constructor for DatabaseTableRepository()
major change:

- defaults are that <Name>Repository relates to a <Name> entity class
- <Name> entity class is in same namespace as <Name>Repository
- thee DB table is <name> (singular, lowercase)
- DB credentials are now read from a `.env` file

### Deprecated
- constructor for DatabaseTableRepository()
- remove dependency on global constants (since read from `.env`)

- changed name of method to insert row into database from `create(...)` to `insert(...)`

### Fixed
- Nothing
- updated README - removed more old refernces to `dvd` (replaced with `movie`)

### Removed
- Nothing
Expand Down
82 changes: 41 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ $ composer require mattsmithdev/pdo-crud-for-free-repositories

## Usage

This example assumes you have a MySQL DB table named 'movie', with columns 'id' and 'title'. You need to write a corresponding class 'Movie' (note capitalization on the first letter). Also you need to write a repository class to work between your PHP class and is corresponding table, in this example the repository class is named 'MovieRepository':
This example assumes you have a MySQL DB table named 'movie', with columns 'id' and 'title'. You need to write a corresponding class 'Movie' (note capitalization on the first letter - since this is a PHP class). Also you need to write a repository class to work between your PHP class and is corresponding table, in this example the repository class is named 'MovieRepository':

``` php
// file: /src/Movie.php
Expand All @@ -50,13 +50,12 @@ This example assumes you have a MySQL DB table named 'movie', with columns 'id'


``` php
// file: /src/DvdRepository.php
// file: /src/MovieRepository.php
namespace <MyNameSpace>;

use Mattsmithdev\PdoCrudRepo\DatabaseManager;
use Mattsmithdev\PdoCrudRepo\DatabaseTableRepository;

class DvdRepository extends DatabaseTableRepository
class MovieRepository extends DatabaseTableRepository
{
// no methods needed if you've followed defaults
// all the 'magic' is done through relfection ...
Expand All @@ -70,12 +69,6 @@ This example assumes you have a MySQL DB table named 'movie', with columns 'id'

require_once __DIR__ . '/<PATH_TO_AUTLOAD>';

// the DatabaseManager class needs the following 4 constants to be defined in order to create the DB connection
define('DB_HOST', '<host>');
define('DB_USER', '<db_username>');
define('DB_PASS', '<db_userpassword>');
define('DB_NAME', '<db_name>');

// create a repository object
use <MyNameSpace>\MovieRepository;
$movieRepository = new MovieRepository();
Expand All @@ -95,6 +88,16 @@ This example assumes you have a MySQL DB table named 'movie', with columns 'id'
}
```

Finally, you need to have defined your DB connection credentialks in a file `.env` as follows:

```dotenv
MYSQL_USER=root
MYSQL_PASSWORD=passpass
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_DATABASE=evote
```

For more details see below. Also there is a full sample web application project on GitGub at:
[pdo-crud-for-free-repositories-example-project](https://github.com/dr-matt-smith/pdo-crud-for-free-repositories-example-project)

Expand All @@ -108,6 +111,7 @@ e.g.
title
category
price
vatRate

## ASSUMPTION 2: No constructor for your PHP classes.
due to the nature of PDO populating properties of objects when DB rows are converted into object instances
Expand Down Expand Up @@ -139,11 +143,15 @@ This property should be an `AUTO_INCREMENT` primary key in the database table sc



## ASSUMPTION 4: DB table name is singular, lowerCamelCase
This tool assumes your database table name is singular, lower case. E.g.
## ASSUMPTION 4: DB table name is singular and all lower case
This tool assumes your database table name is singular, all **lower case**. E.g.

- table name: `movie`
- entity class name: `Movie.php`
- entity class name: `Movie.php`

- table name: `moviecategory`
- entity class name: `MovieCategory.php`



## Step 1: Create your DB tables.
Expand Down Expand Up @@ -220,18 +228,11 @@ e.g. create repository class DvdRepository mapping from table `movie` to PHP cla

## Step 4: Now use the 'magically appearing' static DB CRUD methods.

e.g. to get an array of all dvd records from table 'movie' just write:
e.g. to get an array of all movie records from table 'movie' just write:

``` php
// the DatabaseManager class needs the following 4 constants to be defined in order to create the DB connection
define('DB_HOST', '<host>');
define('DB_USER', '<db_username>');
define('DB_PASS', '<db_userpassword>');
define('DB_NAME', '<db_name>');

$movieRepository = new MovieRepository();
$movies = $movieRepository->getAll();

$movies = $movieRepository->getAll();
```

NOTE: Can pass optional params to override defaults when creating Repository class:
Expand Down Expand Up @@ -305,7 +306,7 @@ e.g.
$deleteSuccess = $movieRepository->deleteAll();
```

## ->create($dvd)
## ->insert($movie)
this method adds a new row to the database, based on the contents of the provided object
(any 'id' in this object is ignored, since the table is auto-increment, so it's left to the DB to assign a new, unique 'id' for new records)
returns the 'id' of the new record (or -1 if error when inserting)
Expand All @@ -314,14 +315,14 @@ e.g.
``` php

// delete row in database table 'dvds' with id=12
$dvd = new Dvd();
$dvd->setTitle('Jaws II');
$dvd->setCategory('thriller');
$dvd->setPrice(9.99);
$movie = new Movie();
$movie->setTitle('Jaws II');
$movie->setCategory('thriller');
$movie->setPrice(9.99);

// create the new Dvd row
$dvdRepository = new DvdRepository();
$id = $dvdRepository->create($dvd);
// create the new Movie row
$movieRepository = new MovieRepository();
$id = $movieRepository->insert($movie);

// decision based on success/failure of insert
if ($id < 0){
Expand All @@ -331,16 +332,16 @@ e.g.
}
```

## ->update($dvd)
## ->update($movie)
This method adds a UPDATES an existing row in the database, based on the contents of the provided object
returns true/false depending on success of the deletion

e.g.

``` php
// update DB record for object 'dvd'
$dvdRepository = new DvdRepository();
$updateSuccess = $dvdRepository->update($dvd);
// update DB record for object 'movie'
$movieRepository = new MovieRepository();
$updateSuccess = $movieRepository->update($movie);
```
## ->searchByColumn($columnName, $searchText))
Expand All @@ -350,9 +351,9 @@ returns an array of objects that match an SQL 'LIKE' query
e.g.

``` php
// get all Dvds with 'jaws' in the title
$dvdRepository = new DvdRepository();
$jawsDvds = $dvdRepository->searchByColumn('title', 'jaws');
// get all Movies with 'jaws' in the title
$movieRepository = new MovieRepository();
$jawsMovies = $movieRepository->searchByColumn('title', 'jaws');
```

## ->dropTable()
Expand Down Expand Up @@ -475,7 +476,6 @@ Here is an example of a simple script to update a table schema and insert some i

```php
<?php
require_once __DIR__ . '/../config/db.php'; // defines the 4 DB constants
require_once __DIR__ . '/../vendor/autoload.php';

use Tudublin\Movie;
Expand All @@ -502,8 +502,8 @@ $m2->setPrice(9.99);
$m2->setCategory('entertainment');

// (3) insert objects into DB
$movieRespository->create($m1);
$movieRespository->create($m2);
$movieRespository->insert($m1);
$movieRespository->insert($m2);

// (4) test objects are there
$movies = $movieRespository->findAll();
Expand All @@ -517,7 +517,7 @@ OUTPUT:
--------------- DatabaseTableRepository->createTable() ----------------
NOTE:: Looking for a constant CREATE_TABLE_SQL defined in the entity class associated with this repository
-----------------------------------------------------------------------
<pre>/Users/matt/Documents/github/pdo-crud-for-free-repositories/db/migrateAndLoadFixtures.php:35:
<pre>/Users/matt/Documents/github/pdo-crud-for-free-repositories/db/movieMigrationAndFixtures.php:35:
array(2) {
[0] =>
class Tudublin\Movie#8 (4) {
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
}
],
"require": {
"php" : "~5.5|~7.0"
"php" : "~7.2.5",
"symfony/dotenv": "^5.0"
},
"require-dev": {
"phpunit/phpunit" : "4.*",
Expand All @@ -32,7 +33,6 @@
"autoload-dev": {
"psr-4": {
"Mattsmithdev\\PdoCrudRepoTest\\": "tests",
"Tudublin\\":"src"
}
},
"scripts": {
Expand Down
6 changes: 0 additions & 6 deletions config/dbConstants.php

This file was deleted.

56 changes: 39 additions & 17 deletions src/DatabaseManager.php
Original file line number Diff line number Diff line change
@@ -1,44 +1,46 @@
<?php
/**
* User: mattsmithdev
* Date: 18/02/2016
* Time: 11:58
*
* based on PDO tutorial at URL:
* http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/
*/


namespace Mattsmithdev\PdoCrudRepo;

use Symfony\Component\Dotenv\Dotenv;


/**
* Class DatabaseManager - make things easy to work with MySQL DBs and PDO
* @package Mattsmithdev
*/
class DatabaseManager
{
/**
* get host name from config constant
* host name
* @var string
*/
private $host;

/**
* host port number
* @var string
*/
private $host = DB_HOST;
private $port;

/**
* get DB username from config constant
* DB username
* @var string
*/
private $user = DB_USER;
private $user;

/**
* get DB password from config constant
* DB password
* @var string
*/
private $pass = DB_PASS;
private $pass;

/**
* get DB name from config constant
* DB name
* @var string
*/
private $dbname = DB_NAME;
private $dbname;

/**
* the DataBase Handler is our db connection object
Expand All @@ -54,8 +56,10 @@ class DatabaseManager

public function __construct()
{
$this->loadCredentialsFromDotEnv();

// DSN - the Data Source Name - requred by the PDO to connect
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
$dsn = 'mysql:host=' . $this->host . ':' . $this->port . ';dbname=' . $this->dbname;
try {
// Set options
$options = array(
Expand All @@ -71,6 +75,24 @@ public function __construct()
}
}

private function loadCredentialsFromDotEnv()
{
// load dotenv file
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/../../../../.env');

// extract values
$this->host = $_ENV['MYSQL_HOST'];
$this->port = $_ENV['MYSQL_PORT'];
$this->user = $_ENV['MYSQL_USER'];
$this->pass = $_ENV['MYSQL_PASSWORD'];
$this->dbname = $_ENV['MYSQL_DATABASE'];

if(!$this->host){
throw new \Exception("\n\n ********** missing MYSQL_HOST environment value - or perhaps mnissing .env file altogether ...\n\n");
}
}

public function getDbh()
{
return $this->dbh;
Expand Down
2 changes: 1 addition & 1 deletion src/DatabaseTableRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ public function searchByColumn($columnName, $searchText)
* @param Object $object
* @return integer
*/
public function create($object)
public function insert($object)
{
$db = new DatabaseManager();
$connection = $db->getDbh();
Expand Down

0 comments on commit 755b30a

Please sign in to comment.