Search code examples
phplaravelilluminate-container

How to create database connection as instance of instance of Illuminate\Database\ConnectionInterface in Illuminate library?


I am developing a restful application in slim framework. I am using a session manager which uses database library of illuminate. It requires me to create a database connection using instance of Laravel's illuminate. But I am getting an error. Here is my code:

<?php
require 'lib/vendor/PHPMailer/PHPMailerAutoload.php';
require 'lib/init.php';
require 'lib/Slim/Slim.php';

date_default_timezone_set('UTC');

use lib\Slim\Middleware\SessionCookie;

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim([
    // cookie encryption (strongly recommend)
    'cookies.encrypt' => true,
    'cookies.secret_key' => 'put your secret key',
    // session config
    'sessions.driver' => 'database', // or database
    //'sessions.files' => __DIR__ . '/../sessions', // require mkdir
    'sessions.table' => 'sessions', // require create table
]);

$manager = new \Slim\Middleware\SessionManager($app);
$session = new \Slim\Middleware\Session($manager);

$manager->setDbConnection(mysql_connect('localhost', 'username', 'password', 'database'));

$app->add($session); 

$app->run();

This is the error I get:

Argument 1 passed to Illuminate\Session\DatabaseSessionHandler::__construct() must be an instance of Illuminate\Database\ConnectionInterface, resource given

If anyone can point me in the right direction, I would really appreciate it.

Thanks in advance.


Solution

  • You can review the source code for \Illuminate\Database here:
    https://github.com/illuminate/database

    Taylor has done a great job at providing documentation for using this module independently and creating a Database connection.use Illuminate\Database\Capsule\Manager as Capsule;

    $capsule = new Capsule;
    
    $capsule->addConnection([
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'root',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ]);