【注意】最后更新于 December 6, 2019,文中内容可能已过时,请谨慎使用。
参照上一篇的文章laravel 的 Repository 模式 都已经注册了服务也可以使用 Facade
了
首先创建一个 Facade
文件,还是在 app/Repositories
这里,创建HelloFacade.php
名字无所谓,路径也是无所谓的,关键是能够正确引入文件就行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php
/**
* Created by PhpStorm.
* User: gpf
* Date: 2016/12/19
* Time: 下午10:48
*/
namespace App\Repositories;
use Illuminate\Support\Facades\Facade;
class HelloFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'Hello';
}
}
|
然后再在之前创建的namespace App\Providers\HelloProvider
中作出一些改动
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Repositories\Hello;
use App\Repositories\HelloRepository;
class HelloProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('App\Repositories\Hello','App\Repositories\HelloRepository');
$this->app->singleton('Hello',function(){
return new HelloRepository();
});
}
}
|
$this->app->singleton
就是为了去绑定facade 现在已经成功了一半了,接下来去配置文件中注册一下就能正常使用了
在config/app.php
中
1
2
3
4
5
6
7
8
9
10
|
'providers' => [
....
App\Providers\HelloProvider::class,
....
],
'aliases' => [
...
'Hello' => \App\Repositories\HelloFacade::class,
...
]
|
这样注册过后就能在文件中直接类似
1
2
3
|
use Hello;
Hello::say();
|
这一类的调用了
文章作者
GPF
上次更新
2019-12-06
(7ba517e)