This article mainly introduces how to register Facades in Laravel, and analyzes in detail the principles, implementation methods, and precautions for registering Facades in Laravel, for more information about how to register Facades in Laravel, see the following section. We will share this with you for your reference. The details are as follows:
When registering a class as Fcade in Laravel, you can use the Ioc container. each time you use this class, the class is initialized only once, similar to the Singleton mode, and can call the class method like using static methods, the following describes how to register Facades in Laravel.
1. add the register method in Providers/AppServiceProvider. php of the project app directory. the code is as follows.
/** * Register any application services. * * @return void */public function register(){ $this->registerTestModel();}private function registerTestModel(){ $this->app->singleton('testmodel', function ($app) { $model = 'App\Models\Test'; return new $model(); }); $this->app->alias('testmodel', 'App\Models\Test');}
Register the Test class of the namespace App \ Models as the Singleton mode, and obtain the file location of the alias testmodel. this Test class app/Models/Test. php.
2. create a Facade class
Add a file to the app \ Facades directory in the project root directory, such as Test. php. the code is as follows. if the directory does not exist, you can create a new one.
<?phpnamespace App\Facades;use Illuminate\Support\Facades\Facade;class Test extends Facade{ /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'testmodel'; }}
By inheriting Facade and reloading the getFacadeAccessor method, return the alias of the class in the previously bound Singleton mode.
3. use Facade
After the preceding steps, you can use the Facade Test. the following example shows how to use the Facade in the controller.
<?phpnamespace App\Http\Controllers;use App\Facades\Test;use Illuminate\Routing\Controller;class TestController extends Controller{ public function __construct() { Test::show(); Test::show(); }}
Let's take a look at the content of the original class Test. php:
<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Model;class Test extends Model{ protected $table = 'tt'; public static $times = 0; public function __construct() { self::$times++; parent::__construct(); } public function show() { echo self::$times . '
'; }}
After registering the Facade, calling the show method is in the form of Test: show (). similar to the Singleton mode, it is not instantiated multiple times and the call is very simple.
PS: The above is only the method and step for registering Facade. in actual projects, you may need to further encapsulate the Model layer.