Joe Scotto
Joe Scotto

Reputation: 10877

Laravel Facades global Facade for each individual class?

The concept of Facades is something new to me and the structure that Laravel uses to organize it seems over cluttered.

app    
└───Facades
│   │   Facade.php
│   │
│   └───Classes
│       │   Facade.php
│       │

app/Facades/Facade.php

<?php
namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class Facade extends Facade
{
    protected static function getFacadeAccessor() {
        return 'Facade';
    }
}

app/Facades/Classes/Facade.php

<?php

namespace App\Facades\Classes;

use Illuminate\Support\Facades\Facade;

class Facade extends Facade
{
    // Logic Here
}

What I want to do is combine the two of these together so I just have files in app/Facades but it doesn't seem there is a way to do that because Laravel relies on having the structure shown.

Are there any options to get this into a single file so I don't have tons of duplications?

Upvotes: 0

Views: 305

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

You can prepend Facades when you are using the class' namespace. For instance, let's say you have a Foo class:

// app/Foo.php

namespace App;

class Foo
{
    public function bar() : string
    {
        return 'Hello world!';
    }
}

Then you can do this in your controller:


namespace App\Http\Controllers;

use Facades\App\Foo;

class TestController
{
    public function __invoke() : void
    {
        echo Foo::bar(); // Hello world!
    }
}

With this approach, you do not need to "duplicate" your files.

For more information about real time facades: https://laravel.com/docs/5.8/facades#real-time-facades

Upvotes: 1

Related Questions