2

I'm a little confused about how to use Illuminate Database in my project. I have found two ways to use it, but can't figure out which one is the best/right way.

Solution 1:

This is the content of my database.php:

require('vendor/autoload.php');

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([
    'driver'    => 'mysql',
    etc...
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();

I use it in my application like this

require_once('database.php');

use Illuminate\Database\Capsule\Manager as Capsule;                         

$users = Capsule::table('Users')->where('id', '>', 2)->get();

In this way I have to alias "use Illuminate\Database\Capsule\Manager as Capsule;" in every file where I need the connection.

Solution 2: I create a connection class with what I believe is a singleton.

class ConnectionFactory {

    private static $factory;
    private $db;

    public static function getFactory(){
        if (!self::$factory)
        self::$factory = new ConnectionFactory();
        return self::$factory;
    }

    public function getConnection() {

        if (!$this->db) {
           $capsule = new Capsule;
           $capsule->addConnection([
               'driver'    => 'mysql',
               etc...
           ]);
           $capsule->setAsGlobal();
           $capsule->bootEloquent();
           $this->db = $capsule->getConnection();
        }
    return $this->db;
    }
}

Then I use it in my application like this

$db = ConnectionFactory::getFactory()->getConnection();
$users = $db->table('Users')->where('id', '>', 2)->get();

Both methods works fine but which i s prefered? Is the first solution using the same connection every time?

Thx

sjosen
  • 551
  • 1
  • 6
  • 10

0 Answers0