资讯专栏INFORMATION COLUMN

Laravel之Contracts和Facades

CoorChice / 1765人阅读

摘要:而这些通用的接口已经由为你设计好了。作为在服务容器内基类的静态代理。所有对的调用都会被转发到该类对象下。在注册类在注册自定义的别名使用测试去查看输出

Contracts

Contracts其实就是倡导面向接口编程,来达到解耦的目的。而这些通用的接口已经由Laravel为你设计好了。就是这些Contracts.
那么Laravel如何知道我们需要使用哪个实现呢?
在Laravel默认的Contracts绑定中,在"Illuminate/Foundation/Application.php"有这样的定义:这就是绑定了默认的接口实现.

  /**
     * Register the core class aliases in the container.
     *
     * @return void
     */
    public function registerCoreContainerAliases()
    {
        $aliases = [
            "app"                  => ["IlluminateFoundationApplication", "IlluminateContractsContainerContainer", "IlluminateContractsFoundationApplication"],
            "auth"                 => "IlluminateAuthAuthManager",
            "auth.driver"          => ["IlluminateAuthGuard", "IlluminateContractsAuthGuard"],
            "auth.password.tokens" => "IlluminateAuthPasswordsTokenRepositoryInterface",
            "blade.compiler"       => "IlluminateViewCompilersBladeCompiler",
            "cache"                => ["IlluminateCacheCacheManager", "IlluminateContractsCacheFactory"],
            "cache.store"          => ["IlluminateCacheRepository", "IlluminateContractsCacheRepository"],
            "config"               => ["IlluminateConfigRepository", "IlluminateContractsConfigRepository"],
            "cookie"               => ["IlluminateCookieCookieJar", "IlluminateContractsCookieFactory", "IlluminateContractsCookieQueueingFactory"],
            "encrypter"            => ["IlluminateEncryptionEncrypter", "IlluminateContractsEncryptionEncrypter"],
            "db"                   => "IlluminateDatabaseDatabaseManager",
            "db.connection"        => ["IlluminateDatabaseConnection", "IlluminateDatabaseConnectionInterface"],
            "events"               => ["IlluminateEventsDispatcher", "IlluminateContractsEventsDispatcher"],
            "files"                => "IlluminateFilesystemFilesystem",
            "filesystem"           => ["IlluminateFilesystemFilesystemManager", "IlluminateContractsFilesystemFactory"],
            "filesystem.disk"      => "IlluminateContractsFilesystemFilesystem",
            "filesystem.cloud"     => "IlluminateContractsFilesystemCloud",
            "hash"                 => "IlluminateContractsHashingHasher",
            "translator"           => ["IlluminateTranslationTranslator", "SymfonyComponentTranslationTranslatorInterface"],
            "log"                  => ["IlluminateLogWriter", "IlluminateContractsLoggingLog", "PsrLogLoggerInterface"],
            "mailer"               => ["IlluminateMailMailer", "IlluminateContractsMailMailer", "IlluminateContractsMailMailQueue"],
            "auth.password"        => ["IlluminateAuthPasswordsPasswordBroker", "IlluminateContractsAuthPasswordBroker"],
            "queue"                => ["IlluminateQueueQueueManager", "IlluminateContractsQueueFactory", "IlluminateContractsQueueMonitor"],
            "queue.connection"     => "IlluminateContractsQueueQueue",
            "redirect"             => "IlluminateRoutingRedirector",
            "redis"                => ["IlluminateRedisDatabase", "IlluminateContractsRedisDatabase"],
            "request"              => "IlluminateHttpRequest",
            "router"               => ["IlluminateRoutingRouter", "IlluminateContractsRoutingRegistrar"],
            "session"              => "IlluminateSessionSessionManager",
            "session.store"        => ["IlluminateSessionStore", "SymfonyComponentHttpFoundationSessionSessionInterface"],
            "url"                  => ["IlluminateRoutingUrlGenerator", "IlluminateContractsRoutingUrlGenerator"],
            "validator"            => ["IlluminateValidationFactory", "IlluminateContractsValidationFactory"],
            "view"                 => ["IlluminateViewFactory", "IlluminateContractsViewFactory"],
        ];

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

$this->app->bind("AppContractsEventPusher", "AppServicesPusherEventPusher");
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"       => IlluminateSupportFacadesApp::class,
        "Artisan"   => IlluminateSupportFacadesArtisan::class,
        "Auth"      => IlluminateSupportFacadesAuth::class,
        "Blade"     => IlluminateSupportFacadesBlade::class,
        "Bus"       => IlluminateSupportFacadesBus::class,
        "Cache"     => IlluminateSupportFacadesCache::class,
        "Config"    => IlluminateSupportFacadesConfig::class,
        "Cookie"    => IlluminateSupportFacadesCookie::class,
        "Crypt"     => IlluminateSupportFacadesCrypt::class,
        "DB"        => IlluminateSupportFacadesDB::class,
        "Eloquent"  => IlluminateDatabaseEloquentModel::class,
        "Event"     => IlluminateSupportFacadesEvent::class,
        "File"      => IlluminateSupportFacadesFile::class,
        "Gate"      => IlluminateSupportFacadesGate::class,
        "Hash"      => IlluminateSupportFacadesHash::class,
        "Input"     => IlluminateSupportFacadesInput::class,
        "Lang"      => IlluminateSupportFacadesLang::class,
        "Log"       => IlluminateSupportFacadesLog::class,
        "Mail"      => IlluminateSupportFacadesMail::class,
        "Password"  => IlluminateSupportFacadesPassword::class,
        "Queue"     => IlluminateSupportFacadesQueue::class,
        "Redirect"  => IlluminateSupportFacadesRedirect::class,
        "Redis"     => IlluminateSupportFacadesRedis::class,
        "Request"   => IlluminateSupportFacadesRequest::class,
        "Response"  => IlluminateSupportFacadesResponse::class,
        "Route"     => IlluminateSupportFacadesRoute::class,
        "Schema"    => IlluminateSupportFacadesSchema::class,
        "Session"   => IlluminateSupportFacadesSession::class,
        "Storage"   => IlluminateSupportFacadesStorage::class,
        "URL"       => IlluminateSupportFacadesURL::class,
        "Validator" => IlluminateSupportFacadesValidator::class,
        "View"      => IlluminateSupportFacadesView::class,

    ],

你是不是发现了什么?对,Facades其实就是在config/app.php中定义的一系列类的别名。只不过这些类都具有一个共同的特点,那就是继承基底 IlluminateSupportFacadesFacade 类并实现一个方法: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


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


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

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去查看输出

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/21517.html

相关文章

  • Laravel思维导图Laravel核心概念

    摘要:的核心概念包括服务容器服务提供者门面契约。所有服务提供者都需要继承类。可以为服务提供者的方法设置类型提示。方法将在所有其他服务提供者均已注册之后调用。同样会整理成思维导图的形式以方便记忆与回顾。 showImg(https://segmentfault.com/img/remote/1460000010771201); Laravel 的核心概念包括:服务容器、服务提供者、门面(Fac...

    wthee 评论0 收藏0
  • Laravel 深入核心系列教程

    摘要:前言年底了不太忙,最近一段时间也一直在研究,就想写篇关于比较深一点的教程系列啥的,于是就找到站长给开了写教程的渠道。优点的就是为艺术家创造的框架,它也是工程化的趋势。项目维护方便也是事实。如果有遇到问题可以直接在教程下面留言。 前言 年底了不太忙,最近一段时间也一直在研究laravel,就想写篇关于laravel比较深一点的教程系列啥的,于是就找到站长给开了写教程的渠道。由于第一次写,...

    wemall 评论0 收藏0
  • 最适合入门的 Laravel 初级教程 (一)

    摘要:最适合入门的初级教程一为什么选择曾经要跟白头到老没想到它升了个级就抛了锚把我等抛弃了痛定思痛重新审视了一遍框架是世界上最好的语言这个没有疑问吧如果有那绝对是个异教徒这是要被拖出去烧死的信仰的问题神圣不可侵犯那最好的语言中最流行的框架是哪个呢 最适合入门的 Laravel 初级教程 (一) 为什么选择 laravel 曾经要跟 thinkphp 白头到老;没想到它升了个级就抛了锚;把我等...

    klivitamJ 评论0 收藏0
  • laravel入门

    摘要:开发根目录测试分为单元测试和功能测试创建一个文件执行测试测试前清除配置缓存运行单个测试用例小提示在开发与进行交互的第三方扩展包时,最好选择注入契约而不使用。 参考https://laravelacademy.org/ 概念 单词 契约Contract 就是接口 repository 仓库(封装数据访问,可以搜索:repository模式) Container 容器 ServicePr...

    韩冰 评论0 收藏0
  • Laravel核心解读--完结篇

    摘要:过去一年时间写了多篇文章来探讨了我认为的框架最核心部分的设计思路代码实现。为了大家阅读方便,我把这些源码学习的文章汇总到这里。数据库算法和数据结构这些都是编程的内功,只有内功深厚了才能解决遇到的复杂问题。 过去一年时间写了20多篇文章来探讨了我认为的Larave框架最核心部分的设计思路、代码实现。通过更新文章自己在软件设计、文字表达方面都有所提高,在刚开始决定写Laravel源码分析地...

    laoLiueizo 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<