Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JoaoHamerski's avatar

How to get a DB facade instance after i use the method DB::connection()?

Here is my problem: I want to extend the DB facade to create my own methods, but i need to set a different connection using DB::connection, but when i do:

$DB = DB::connection('sqlite')

dd($DB);

It returns a Illuminate\Database\SQLiteConnection instance instead of a DB Facade instance , so, all my methods i created when extended the DB facade in my custom class are gone, how can i resolve that?

0 likes
5 replies
jlrdw's avatar

The base instance is getPdo (); But you can set another database instance if you want. I'm not 100% sure what you are trying to do. Once you set your connection all of the commands should be available.

I have done something similar with another PDO instance but I'm on a tablet right now not at my computer I will share some code later if you still need it.

JoaoHamerski's avatar

Sure, i have been trying it for about 4h with no success, i don't know more what to do.

The problem is that, i need some extra methods with DB facade methods, but i need to set different connections at the same times.

jlrdw's avatar
jlrdw
Best Answer
Level 75

Look over:

<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;
use PDO;

class DbPdo
{

    protected static $dbh = null;

    protected function __construct()
    {
        
    }

    protected function __clone()
    {
        
    }

    public static function dbh()
    {

        try {
            $dbh = DB::connection()->getPdo();
        } catch (PDOException $e) {
            throw new pdoDbException($e);
        }
        return $dbh;
    }

    /**
     * run raw sql queries
     * @param  string $sql sql command
     * @return return query
     */
    public static function raw($sql)
    {
        return self::dbh()->query($sql);
    }

    /**
     * method for selecting records from a database
     * @param  string $sql       sql query
     * @param  array  $array     named params
     * @param  object $fetchMode
     * @param  string $class     class name
     * @return array            returns an array of records
     */
    public static function select($sql, $array = array(), $fetchMode = PDO::FETCH_OBJ, $class = '')
    {
        $stmt = self::dbh()->prepare($sql);

        foreach ($array as $key => $value) {
            if (is_int($value)) {
                $stmt->bindValue("$key", $value, PDO::PARAM_INT);
            } else {
                $stmt->bindValue("$key", $value);
            }
        }

        $stmt->execute();

        if ($fetchMode === PDO::FETCH_CLASS) {
            return $stmt->fetchAll($fetchMode, $class);
        } else {
            return $stmt->fetchAll($fetchMode);
        }
    }

    public static function selectOne($sql, $array = array(), $fetchMode = PDO::FETCH_OBJ, $class = '')
    {
        $stmt = self::dbh()->prepare($sql);
        foreach ($array as $key => $value) {
            if (is_int($value)) {
                $stmt->bindValue("$key", $value, PDO::PARAM_INT);
            } else {
                $stmt->bindValue("$key", $value);
            }
        }

        $stmt->execute();

        if ($fetchMode === PDO::FETCH_CLASS) {
            return $stmt->fetch($fetchMode, $class);
        } else {
            return $stmt->fetch($fetchMode);
        }
    }

////    several other methods:

}

Take note of this part:

    public static function dbh()
    {

        try {
            $dbh = DB::connection()->getPdo();
        } catch (PDOException $e) {
            throw new pdoDbException($e);
        }
        return $dbh;
    }

It gives the instance

Note I don't use anymore

I used this for a while while converting to laravel code.

You call the methods as needed.

I also have this:

<?php

namespace App\Helpers;

require(__DIR__ . '/DbConnection.php');

use PDO;

class DbConn
{

    protected static $PDOdb = null;
    protected static $gp = true;

    protected function __construct()
    {
        
    }

    protected function __clone()
    {
        
    }

    public static function PDOdb($group = true)
    {
        self::$gp = $group;
        if (self::$PDOdb === null) {
            try {
                if (self::$gp === true) {
                    $opt = [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
                    ];
                }
                if (self::$gp === false) {
                    $opt = [
                        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"'
                    ];
                }
                $dsn = DBPDO_TYPE . ':host=' . DBPDO_HOST . ';dbname=' . DBPDO_NAME . ';charset=utf8';
                self::$PDOdb = new PDO($dsn, DBPDO_USER, DBPDO_PASS, $opt);
                return self::$PDOdb;
            } catch (PDOException $e) {
                throw new pdoDbException($e);
            }
        } else {
            return self::$PDOdb;
        }
    }
    
    public static function getPdo($group = true)
    {
        //return $this->get();
        return static::PDOdb($group);
    }

}

Especially for this:

PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"'

So I don't have to mess with full group by in laravel settings.

Usage:

    public function myTest2_good()
    {
        $sql = "SELECT dc_pets.ownerid, dc_pets.petowner, COUNT(petid) AS total FROM dc_pets ";
        $sql .= "WHERE dc_pets.ownerid IS NOT NULL AND dc_pets.ownerid < 5 ";
        $sql .= "GROUP BY dc_pets.ownerid ";

       $sth = conn::getPdo(false)->prepare($sql);
        $sth->execute();
        $quy = $sth->fetchAll(\PDO::FETCH_ASSOC);


        echo '<pre>';
        print_r($quy);
        echo '</pre>';
    }

Notice the

PDO::FETCH_ASSOC

The in-built pdo instance is

PDO::FETCH_OBJ
JoaoHamerski's avatar

But your DbPdo class is a Facade or you instantiate every time you want to use?

jlrdw's avatar

it's not a facade. I was merely showing how to make a custom instance of the root PDO instance. you can study more and work it into a facade, I just did a quick static class cause I rarely use it.

If you look in the vendor folder or search over the laravel API you will see that the root to making facades work is __callStatic() .

I believe Taylor, not positive but I think he likes the static looking calls and so do I, which is one of the main reasons behind facades.

I just decided to make a quick static class with static methods since I hardly use the class.

There's a chapter in the documentation on facades. But all a facade is doing is calling an instance call statically looking.

And every time you do a request laravel goes through everything all over again there is no such thing as a class that stays loaded.

I have in the past contributed to another framework and helped write a router.

Every time a class is called on in the router it's a new instance of the class being loaded.

For example let's say you have a method in a post controller to show users a list of post people have made. Every time a request is routed to that controller that initiates a new instance of that controller.

Don't worry though after a request is finished everything is automatically disposed of, all this happens behind the scenes and you don't have to worry about it.

I would suggest you take Jefferies video series on PHP oop.

1 like

Please or to participate in this conversation.