文档章节

From Apprentice To Artisan 翻译 08

zgldh
 zgldh
发布于 2014/12/09 00:14
字数 1100
阅读 4.7K
收藏 0

上一篇

As Organizer 作为管理工具

One of the keys to building a well architected Laravel application is learning to use service providers as an organizational tool. When you are registering many classes with the IoC container, all of those bindings can start to clutter your app/start files. Instead of doing container registerations in those files, create service providers that register related services.

想制作一个结构优美的Laravel应用的话,就要去学习如何用服务提供者来管理代码。当你在注册IoC绑定的时候,所有代码都杂乱的塞进了app/start路径下的文件里。 别再这样做了,使用服务提供者来注册这些吧。

Get It Started 万物之初

Your application's "start" files are all stored in the app/start directory. These are "bootstrap" files that are loaded based on the type of the request entering your application. Start files named after an environment are loaded after the global start.php file. Finally, the artisan.php start file is loaded when any console command is executed.

你应用的“启动”文件都储存在app/start目录下。根据不同的请求入口,系统会载入不同的启动文件。在全局的start.php文件加载后,系统会根据执行环境的不同来加载不同的启动文件。 此外,在执行命令行程序时,artisan.php文件会被载入。

Let's explore an example. Perhaps our application is using Pusher to push messages to clients via WebSockets. In order to decouple ourselves from Pusher, it will be benificial to create an EventPusherInterface, and a PusherEventPusher implementation. This will allow us to easily change WebSocket providers down the road as requirements change or our application grows.

咱们来考虑这个例子。也许我们的应用正在使用Pusher 来为客户推送消息。为了将我们的应用和Pusher解耦,我们要定义EventPusherInterface接口和对应的实现类PusherEventPusher。这样在需求变化或应用改进时,我们就可以随时轻松的改变推送服务提供商。

<!-- lang: php -->
interface EventPusherInterface{
    public function push($message, array $data = array());
}

class PusherEventPusher implements EventPusherInterface{
    public function __construct(PusherSdk $pusher)
    {
        $this->pusher = $pusher;
    }
    public function push($message, array $data = array())
    {
        // Push message via the Pusher SDK...
    }
}

Next, let's create an EventPusherServiceProvider:

接下来我们创建一个EventPusherServiceProvider

<!-- lang:php -->
use Illuminate\Support\ServiceProvider;

class EventPusherServiceProvider extends ServiceProvider {
    public function register()
    {
        $this->app->singleton('PusherSdk', function()
        {
            return new PusherSdk('app-key', 'secret-key');
        }
        
        $this->app->singleton('EventPusherInterface', 'PusherEventPusher');
    }
}

Great! Now we have a clean abstraction over event pushing, as well as a convenient place to register this, and other related bindings, in the container. Finally, we just need to add the EventPusherServiceProvider to our providers array in the app/config/app.php configuration file. Now we are ready to inject the EventPusherInterface into any controller or class within our application.

很好! 我们对事件推送进行了清晰的抽象,同时我们也有了一个很不错的地方进行注册、绑定其他相关的东西到容器里。最后一步只需要将EventPusherServiceProvider写入app/config/app.php文件内的providers数组里就可以了。现在这个应用里的EventPusherInterface已经被绑定到了正确的实现类上。

Should You Singleton? 要使用单例么?

You will need to evaluate whether to bind classes with bind or singleton. If you only want one instance of the class to be created per request cycle, use singleton. Otherwise, use bind.

用不用单例可以这样来考虑:如果在一次请求周期中该类只需要有一个实例,就使用singleton;否则就使用bind

Note that a service provider has an $app instance available via the base ServiceProvider class. This is a full Illuminate\Foundation\Application instance, which inherits from the Container class, so we can call all of the IoC container methods we are used to. If you preffer to use the App facade inside the service provider, you may do that as well:

    App::singleton('EventPusherInterface', 'PusherEventPusher');

Of course, service providers are not limited to registering certain kinds of services. We could use them to register our cloud file storage services, database access services, a custom view engine such as Twig, etc. They are simply bootstrapping and organizational tools for your application. Nothing more.

当然服务提供者的功能不仅仅局限于消息推送。像是云存储、数据库访问、自定义的视图引擎比如Twig等等都可以用这种模式来设置。服务提供者就是你的应用里的启动代码和管理工具,没什么神奇的。

So, don't be scared to create your own service providers. They are not something that should be strictly limited to distributed packages, but rather are great organizational tools for your own applications. Be creative and use them to bootstrap your various application components.

所以大胆的去创建你自己的服务提供者。并不是你非要发布个什么软件包才需要服务提供者,他们只是非常好的管理代码的工具。使用它们的力量去管理好应用中的各个组件吧。

下一篇

© 著作权归作者所有

zgldh

zgldh

粉丝 104
博文 36
码字总数 47009
作品 2
高级程序员
私信 提问
From Apprentice To Artisan 翻译 16

上一篇 Single Responsibility Principle 单一职责原则 Introduction 介绍 The "SOLID" design principles, articulated by Robert "Uncle Bob" Martin, are five principles that provide ......

zgldh
2015/03/17
2.7K
0
From Apprentice To Artisan 翻译 10

上一篇 Application Structure 应用结构 Introduction 介绍 Where does this class belong? This question is extremely common when building applications on a framework. Many develope......

zgldh
2014/12/29
1.3W
1
From Apprentice To Artisan 翻译 04

上一篇 Reflect Resolution 反射解决方案 One of the most powerful features of the Laravel container is its ability to automatically resolve dependencies via reflection. Reflection......

zgldh
2014/10/08
3.4K
0
From Apprentice To Artisan 翻译 03

上一篇 The IoC Container 控制反转容器 Basic Binding 基础绑定 Now that we've learned about dependency injection, let's explore inversion of control containers.IoC containers make......

zgldh
2014/09/08
6.4K
0
From Apprentice To Artisan 翻译 20

上一篇 Dependency Inversion Principle 依赖反转原则 Introduction 介绍 We have reached our final destination in our overview of the five SOLID design principles! The final princip......

zgldh
2015/03/19
2.2K
5

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 宇宙银河乱弹英雄传 —— @FalconChen

1Osc乱弹歌单(2020)请戳(这里) 【今日歌曲】 @巴拉迪维 :Axxis的单曲《Only God Knows》 最近只听摇滚,挖了好多以前没听过的歌,蛮好。#今日歌曲推荐# 《Only God Knows》- Axxis 手机...

小小编辑
今天
143
1
Safari Date() 函数对日期时间字符串(yyyy-MM-dd HH:mm:ss) 提示NaN的问题

今天发现一个奇怪的问题,在iPhone使用 safari 选择定时发布文章到OSC,选择时间后提示不是合法的时间,判断时间的代码如下: var d = new Date('2020-01-23 23:15'); if (isNaN(d)) {...

FalconChen
昨天
124
0
ActiveMQ学习之通讯协议

一、支持的通讯协议 ActiveMQ支持的client-broker通讯协议有:TCP、NIO、UDP、SSL、HTTP(S)、VM 其中配置Transport Connector的文件在ActiveMQ安装目录的conf/activemq.xml中的<TransportCon...

冥焱
昨天
91
0
应急广播户户通平台

一、平台概述 应急广播户户通平台为软硬一体化广播服务解决方案。实现了应急广播、视音频及图片文字信息、调频及数字广播FM、天气预报信息接收功能,以及视音频播放、智能机器人、电子日历等...

neocean
昨天
133
0
如何为Apache 2.2启用mod_rewrite

我已经在我的Vista机器上安装了新的Apache 2.2,一切正常,除了mod重写。 我没有注释 LoadModule rewrite_module modules/mod_rewrite.s 但是我的重写规则都没有,即使是简单的重写规则 Re...

javail
昨天
53
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部