Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Database
- {
- /**
- * Database username
- *
- * @var string
- */
- protected $username;
- /**
- * Database password
- *
- * @var string
- */
- protected $password;
- /**
- * Database host
- *
- * @var string
- */
- protected $host;
- /**
- * Database name
- *
- * @var string
- */
- protected $name;
- /**
- * Database constructor;
- */
- public function __construct()
- {
- try {
- // iniate $c... I'm not sure how you're getting the value..
- $c = [
- 'settings' => [
- 'db' => [
- 'host' => '',
- 'dbname' => '',
- 'user' => '',
- 'pass' => '',
- ],
- ],
- ];
- $this->host = $c['settings']['db']['host'];
- $this->name = $c['settings']['db']['dbname'];
- $this->username = $c['settings']['db']['user'];
- $this->password = $c['settings']['db']['pass'];
- return $this->connect();
- }
- }
- /**
- * Connect to your database
- *
- * @return pdo
- */
- public function connect()
- {
- try{
- $pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->name,
- $this->username, $this->password);
- $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
- return $pdo;
- } catch (Exception $ex){
- return $ex->getMessage();
- }
- }
- }
- /**
- * My Database
- *
- * @class
- */
- protected $db;
- /**
- * Class constructor
- */
- public function __construct(Database $database){
- $this->db = $database;
- }
- // Database settings
- $config['db']['host'] = '127.0.0.1';
- $config['db']['username'] = 'root';
- $config['db']['password'] = '';
- $config['db']['database'] = 'test';
- $config['db']['charset'] = 'utf8';
- $config['db']['collation'] = 'utf8_unicode_ci';
- $container['db'] = function (Container $container) {
- $settings = $container->get('settings');
- $host = $settings['db']['host'];
- $dbname = $settings['db']['database'];
- $username = $settings['db']['username'];
- $password = $settings['db']['password'];
- $charset = $settings['db']['charset'];
- $collate = $settings['db']['collation'];
- $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
- $options = [
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_PERSISTENT => false,
- PDO::ATTR_EMULATE_PREPARES => false,
- PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
- PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset COLLATE $collate"
- ];
- return new PDO($dsn, $username, $password, $options);
- };
- protected $db;
- public function __construct(Container $container)
- {
- $this->db = $container->get('db');
- }
- public function internalUserDetails(Request $request, Response $response)
- {
- $this->db ...
- }
- $app->get('/', function (Request $request, Response $response, array $args) {
- $db = $this->get('db');
- // do something
- return $response;
- });
Add Comment
Please, Sign In to add comment