侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Laravel之Contracts和Facades详解

Laravel  /  管理员 发布于 8年前   405

Contracts

Contracts其实就是倡导面向接口编程,来达到解耦的目的。而这些通用的接口已经由Laravel为你设计好了。就是这些Contracts.

那么Laravel如何知道我们需要使用哪个实现呢?

在Laravel默认的Contracts绑定中,在'Illuminate/Foundation/Application.php'有这样的定义:这就是绑定了默认的接口实现.

推荐:《laravel教程》

/**     * Register the core class aliases in the container.     *     * @return void     */    public function registerCoreContainerAliases()    {        $aliases = ['app'      => ['Illuminate\Foundation\Application', 'Illuminate\Contracts\Container\Container', 'Illuminate\Contracts\Foundation\Application'],'auth'     => 'Illuminate\Auth\AuthManager','auth.driver'          => ['Illuminate\Auth\Guard', 'Illuminate\Contracts\Auth\Guard'],'auth.password.tokens' => 'Illuminate\Auth\Passwords\TokenRepositoryInterface','blade.compiler'       => 'Illuminate\View\Compilers\BladeCompiler','cache'    => ['Illuminate\Cache\CacheManager', 'Illuminate\Contracts\Cache\Factory'],'cache.store'          => ['Illuminate\Cache\Repository', 'Illuminate\Contracts\Cache\Repository'],'config'   => ['Illuminate\Config\Repository', 'Illuminate\Contracts\Config\Repository'],'cookie'   => ['Illuminate\Cookie\CookieJar', 'Illuminate\Contracts\Cookie\Factory', 'Illuminate\Contracts\Cookie\QueueingFactory'],'encrypter'=> ['Illuminate\Encryption\Encrypter', 'Illuminate\Contracts\Encryption\Encrypter'],'db'       => 'Illuminate\Database\DatabaseManager','db.connection'        => ['Illuminate\Database\Connection', 'Illuminate\Database\ConnectionInterface'],'events'   => ['Illuminate\Events\Dispatcher', 'Illuminate\Contracts\Events\Dispatcher'],'files'    => 'Illuminate\Filesystem\Filesystem','filesystem'           => ['Illuminate\Filesystem\FilesystemManager', 'Illuminate\Contracts\Filesystem\Factory'],'filesystem.disk'      => 'Illuminate\Contracts\Filesystem\Filesystem','filesystem.cloud'     => 'Illuminate\Contracts\Filesystem\Cloud','hash'     => 'Illuminate\Contracts\Hashing\Hasher','translator'           => ['Illuminate\Translation\Translator', 'Symfony\Component\Translation\TranslatorInterface'],'log'      => ['Illuminate\Log\Writer', 'Illuminate\Contracts\Logging\Log', 'Psr\Log\LoggerInterface'],'mailer'   => ['Illuminate\Mail\Mailer', 'Illuminate\Contracts\Mail\Mailer', 'Illuminate\Contracts\Mail\MailQueue'],'auth.password'        => ['Illuminate\Auth\Passwords\PasswordBroker', 'Illuminate\Contracts\Auth\PasswordBroker'],'queue'    => ['Illuminate\Queue\QueueManager', 'Illuminate\Contracts\Queue\Factory', 'Illuminate\Contracts\Queue\Monitor'],'queue.connection'     => 'Illuminate\Contracts\Queue\Queue','redirect' => 'Illuminate\Routing\Redirector','redis'    => ['Illuminate\Redis\Database', 'Illuminate\Contracts\Redis\Database'],'request'  => 'Illuminate\Http\Request','router'   => ['Illuminate\Routing\Router', 'Illuminate\Contracts\Routing\Registrar'],'session'  => 'Illuminate\Session\SessionManager','session.store'        => ['Illuminate\Session\Store', 'Symfony\Component\HttpFoundation\Session\SessionInterface'],'url'      => ['Illuminate\Routing\UrlGenerator', 'Illuminate\Contracts\Routing\UrlGenerator'],'validator'=> ['Illuminate\Validation\Factory', 'Illuminate\Contracts\Validation\Factory'],'view'     => ['Illuminate\View\Factory', 'Illuminate\Contracts\View\Factory'],        ];

在我们自定义的接口实现时,我们可以在ServiceProvider中使用进行绑定:

$this->app->bind('App\Contracts\EventPusher', 'App\Services\PusherEventPusher');

Facades

Facades 为应用程序的服务容器中可用的类提供了一个「静态」接口。Laravel 「facades」作为在服务容器内基类的「静态代理」。很难懂?

我们打开项目目录下的config/app.php,然后找到

/*    |--------------------------------------------------------------------------    | Class Aliases    |--------------------------------------------------------------------------    |    | This array of class aliases will be registered when this application    | is started. However, feel free to register as many as you wish as    | the aliases are "lazy" loaded so they don't hinder performance.    |    */    'aliases' => [        'App'       => Illuminate\Support\Facades\App::class,        'Artisan'   => Illuminate\Support\Facades\Artisan::class,        'Auth'      => Illuminate\Support\Facades\Auth::class,        'Blade'     => Illuminate\Support\Facades\Blade::class,        'Bus'       => Illuminate\Support\Facades\Bus::class,        'Cache'     => Illuminate\Support\Facades\Cache::class,        'Config'    => Illuminate\Support\Facades\Config::class,        'Cookie'    => Illuminate\Support\Facades\Cookie::class,        'Crypt'     => Illuminate\Support\Facades\Crypt::class,        'DB'        => Illuminate\Support\Facades\DB::class,        'Eloquent'  => Illuminate\Database\Eloquent\Model::class,        'Event'     => Illuminate\Support\Facades\Event::class,        'File'      => Illuminate\Support\Facades\File::class,        'Gate'      => Illuminate\Support\Facades\Gate::class,        'Hash'      => Illuminate\Support\Facades\Hash::class,        'Input'     => Illuminate\Support\Facades\Input::class,        'Lang'      => Illuminate\Support\Facades\Lang::class,        'Log'       => Illuminate\Support\Facades\Log::class,        'Mail'      => Illuminate\Support\Facades\Mail::class,        'Password'  => Illuminate\Support\Facades\Password::class,        'Queue'     => Illuminate\Support\Facades\Queue::class,        'Redirect'  => Illuminate\Support\Facades\Redirect::class,        'Redis'     => Illuminate\Support\Facades\Redis::class,        'Request'   => Illuminate\Support\Facades\Request::class,        'Response'  => Illuminate\Support\Facades\Response::class,        'Route'     => Illuminate\Support\Facades\Route::class,        'Schema'    => Illuminate\Support\Facades\Schema::class,        'Session'   => Illuminate\Support\Facades\Session::class,        'Storage'   => Illuminate\Support\Facades\Storage::class,        'URL'       => Illuminate\Support\Facades\URL::class,        'Validator' => Illuminate\Support\Facades\Validator::class,        'View'      => Illuminate\Support\Facades\View::class,    ],

你是不是发现了什么?对,Facades其实就是在config/app.php中定义的一系列类的别名。只不过这些类都具有一个共同的特点,那就是继承基底 Illuminate\Support\Facades\Facade 类并实现一个方法:getFacadeAccessor返回名称。

自定义Facade

参考http://www.tutorialspoint.com/laravel/laravel_facades.htm

Step 1 −创建一个名为 TestFacadesServiceProvider的ServiceProvider ,使用如下命令即可:

php artisan make:provider TestFacadesServiceProvider

Step 2 − 创建一个底层代理类,命名为“TestFacades.php” at “App/Test”.

App/Test/TestFacades.php

<?phpnamespace App\Test;class TestFacades{   public function testingFacades(){      echo "Testing the Facades in Laravel.";   }}?>

Step 3 − 创建一个 Facade 类 called “TestFacades.php” at “App/Test/Facades”.

App/Test/Facades/TestFacades.php

<?phpnamespace app\Test\Facades;use Illuminate\Support\Facades\Facade;class TestFacades extends Facade{   protected static function getFacadeAccessor() { return 'test'; }}

Step 4 −创建一个ServiceProviders类,名为“TestFacadesServiceProviders.php” at “App/Test/Facades”.

App/Providers/TestFacadesServiceProviders.php

<?phpnamespace App\Providers;use App;use Illuminate\Support\ServiceProvider;class TestFacadesServiceProvider extends ServiceProvider {   public function boot() {      //   }   public function register() {     //可以这么绑定,这需要use App;    //  App::bind('test',function() {    //     return new \App\Test\TestFacades;    //  });          //也可以这么绑定,推荐。这个test对应于Facade的getFacadeAccessor返回值        $this->app->bind("test", function(){return new MyFoo(); //给这个Facade返回一个代理实例。所有对Facade的调用都会被转发到该类对象下。        });   }}

Step 5 − 在config/app.php注册ServiceProvider类

Step 6 − 在config/app.php注册自定义Facade的别名

使用测试:

Add the following lines in app/Http/routes.php.

Route::get('/facadeex', function(){   return TestFacades::testingFacades();});

Step 9 − Visit the following URL to test the Facade.

http://localhost:8000/facadeex去查看输出

以上就是Laravel之Contracts和Facades详解的详细内容,更多请关注其它相关文章!


  • 上一条:
    一种颗粒度很小的 Laravel 路由文件划分方式(翻译)
    下一条:
    关于 laravel 分页 seo浅谈
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • Laravel 11.14版本发布 - 新的字符串助手和ServeCommand改进(0个评论)
    • Laravel 11.12版本发布 - Artisan的`make`命令自动剪切`.php `扩展(0个评论)
    • Laravel的轻量型购物车扩展包:binafy/laravel-cart(0个评论)
    • Laravel 11.11版本发布 - 查看模型中的第三方关系:show(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-01
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客