mercredi 28 octobre 2015

How to use external libraries in a project?

I use slim framework for a project and I use singleton design pattern for PDO database connection. I install libraries with composer and I have a autoloader.

here is my static PDO connection class.

<?php
namespace lib;
use lib\Config;
use PDO;

class Core {
    public $dbh; // handle of the db connexion
    public $mail;
    private static $instance;
    private function __construct() {
        // building data source name from config
        $dsn = 'mysql:host=' . Config::read('db.host') .
               ';dbname='    . Config::read('db.basename') .
               ';port='      . Config::read('db.port') .
               ';connect_timeout=15';
        // getting DB user from config                
        $user = Config::read('db.user');
        // getting DB password from config                
        $password = Config::read('db.password');
        $this->dbh = new PDO($dsn, $user, $password);
    }
    public static function getInstance() {
        if (!isset(self::$instance))
        {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }
}

And I have a separate config.php file which holds the configs(dbname, db username, db password) and I use $db = \lib\Core::getInstance(); where ever I want if I need.

Now, for example if I want to use PHPMailler library it has some options. When I need to use phpmailler in a route or a class I have to set all the settings first. then send the mail. Is it okay to use singleton design pattern like above and set everything like sender e-mail, smtp credentials etc..., hold settings in the config.php and then call only send object where ever I want. Is singleton design pattern good for this? I would like to have my config.php file which should hold all the options for any library I install and use these libraries in a class, function, route etc.. without having to set everything every time I use a library.

Is factory design pattern for this purpose or singleton design patter okay?

Thank you.

Aucun commentaire:

Enregistrer un commentaire