10

I need to handle different types of DB depending on the client.

I created a Facade called MyDBFacade where I can call my own functions.

For example:

MyDBFacade::createDBUser("MyUser"); // will create a DB user whatever I'm using Postgres or SQL Server

Is there a possibility to extends the framework Facade DB:: in a way I could add my own functions and then call DB::createUser("MyUser") ?

Any clue or idea would be appreciate.

Thanks in advance, have a nice day.

Michaël
  • 1,120
  • 1
  • 15
  • 30

2 Answers2

9

Let's say that you define your custom facade in app/Facades/MyDBFacade.php

<?php

namespace App\Facades;

use Illuminate\Support\Facades\DB;

class MyDBFacade extends DB
{
    // ...
}

You just need to change single line in config/app.php, from

'DB' => Illuminate\Support\Facades\DB::class,

to

'DB' => App\Facades\MyDBFacade::class,

And it all should work now.

Paul
  • 3,186
  • 1
  • 19
  • 22
  • One quick note, from within the `Facade` "extension" class you are creating, it would appear that you cannot call the original `Facade` by name. Instead, you must use the current classname, or because of this, perhaps more semantically clear would be using `self::`. – Chad Dec 10 '19 at 23:29
  • @Paul can we define non static methods in `MyDBFacade` class & use as static methods ? – mssb Jun 01 '21 at 02:19
  • Hey! I don't really know, haven't been using Laravel since about the time I wrote this. I recommend to try ;) – Paul Jun 01 '21 at 15:35
2

You can create / extend your Facade like this:

<?php namespace YourNameSpace\Facades;

class MyDBFacade extends Illuminate\Support\Facades\DB {

        /**
         * Create your custom methods here...
         */
        public static function anyMethod($active)
        {
            /// do what you have to do
        }

}

And then replace (or add it as a new one) to your app/config/app.php:

'aliases' => array(
  'MyDBFacade'   =>  'YourNameSpace\Facades\MyEventFacade::class',
),

Remember to execute composer dump-autoload at the end.

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45