Can you reformat the first part since it's hard to read?
PHP Pracitioner episode 16, making a router
Hello, i have been trying to grasp myself around this episode and i think i finally figured everything out, but not quite. In the lecture Jeffrey has a config file that looks like the code below
$app = [];
$app['config'] = require 'config.php';
require 'core/Router.php'; require 'core/Request.php'; require 'core/database/QueryBuilder.php'; require 'core/database/Connection.php'; $config = require 'config.php';
$app['database'] = new QueryBuilder( Connection::make($app['config']['database']) );
Can someone explain this last piece of code, having a hard time grasping why do we pass ['config']['database'].
Code for QueryBuilder:
class QueryBuilder {
protected $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
public function selectAll($table) {
$statement = $this->pdo->prepare("select * from {$table}");
$statement->execute();
return $statement->fetchAll(PDO::FETCH_CLASS);
}
}
Code for Connection class:
class Connection {
public static function make($config) {
try {
return new PDO(
$config['connection'] . ';dbname=' . $config['name'],
$config['username'],
$config['password'],
$config['options']
);
} catch (\Throwable $th) {
die($th->getMessage());
}
}
}
Thanks in advance
Ok, let's take this steps by steps, you are passing to Connection::make the parameter $app['config']['database'].
Let's look at the static function make, it accepts a $config variable and this variable is an associative array. Why is it an associative array ? Because, we have statements like $config['connection']. So$config must be equal to something like this:
array(
'connection' => 'mysql',
'name' => 'project',
'username' => 'ausername',
'password' => 'apassword',
'options' => []
)
So, we know what make expects. What about the parameter passed: $app['config']['database'].
We see in the code that:
$app['config'] = require 'config.php';
So, $app['config'] is equal to whatever is returned from the config file. Since once again in the parameter call, we are saying not only $app['config'] but $app['config']['database'], this means we are trying to access a database key in $app['config'], this means that config.php returns an associative array like this:
return array(
'database' => array()
);
Then if we group the pieces together, the first piece of code shows what Connection::make expects as a parameter, this second one above shows what must be in config.php. So to give to Connection::make the proper information through $app['config']['database'], the database key in config.php must have all that information, so here is our config.php:
return array(
'database' => array(
'connection' => 'mysql',
'name' => 'project',
'username' => 'ausername',
'password' => 'apassword',
'options' => []
)
);
Please or to participate in this conversation.