Laravel 创建 Facades 实例
使用 Laravel 框架必不可少的会用到它很多强大的Facades,Facades 提供了一个“静态”接口到 IoC 容器类,官方的文档写的太过抽象,关于如何创建一个 Facades 有点晦涩,我来写个简单的创建 Facades 的过程,作为参考吧。
官方是这样说的
Creating a facade for your own application or package is simple. You only need 3 things:
An IoC binding.
A facade class. A facade alias configuration. A great place to register this binding would be to create a new service provider named PaymentServiceProvider, and add this binding to the register method. You can then configure Laravel to load your service provider from the app/config/app.php configuration file.
不按照这个来,下面一步一步来创建一个简单的 Facades。
创建一个 Test 类,app/my/Learn/Test.php
<?php
/**
* @author Ryan < yuansir@live.cn|yuanxuxu.com>
*/
namespace Learn;
class Test{
public function dosomething(){
echo 'this is TestClass dosomething';
}
}
当然这个类需要放在一个 Composer 知道如何去自动加载的目录,你可以需要建我这样的目录结构,为了可以自动加载这个类需要在composer.json中添加:
"autoload": {
......
"psr-0":{
"Learn":"app/my"
}
},
下面来创建一个 Facade class,app/my/Learn/Facades/TestClass.php
<?php
/**
* @author Ryan < yuansir@live.cn|yuanxuxu.com>
*/
namespace Learn\Facades;
use Illuminate\Support\Facades\Facade;
class TestClass extends Facade
{
protected static function getFacadeAccessor()
{
return 'test';
}
}
设置 FacadeAccessor 来告诉 Laravel 这个 Facade class 来查找$app[‘test’]. 然后创建一个新的名为 TestServiceProvider 服务提供器,并且将该绑定加入到 register 方法来连接 Facade。 app/my/Learn/TestServiceProvider.php
<?php
/**
* @author Ryan < yuansir@live.cn|yuanxuxu.com>
*/
namespace Learn;
use Illuminate\Support\ServiceProvider;
class TestServiceProvider extends ServiceProvider
{
public function register()
{
$this->app['test'] = $this->app->share(
function ($app) {
return new \Learn\Test();
}
);
$this->app->booting(
function () {
$aliases = \Config::get('app.aliases');
if(empty($aliases['TestClass'])){
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('TestClass','Learn\Facades\TestClass');
}
}
);
}
}
接下来你就可以配置 Laravel app/config/app.php 配置文件来加载该 ServiceProvider,
'providers' => array(
......
'Learn\TestServiceProvider'
),
注意,上面的$this->app->booting 方法不是必须的,如果不写这一段需要在 app/config/app.php 配置 alias,
'aliases' => array(
'TestClass' => 'Learn\Facades\TestClass',
),
到此就 OK 了,用一下TestClass::dosomething();已经执行了吧。
转载请注明: 转载自Ryan 是菜鸟 | LNMP 技术栈笔记
如果觉得本篇文章对您十分有益,何不 打赏一下
本文链接地址: Laravel 创建 Facades 实例
本作品采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可