文档章节

From Apprentice To Artisan 翻译 12

zgldh
 zgldh
发布于 2015/01/10 23:36
字数 1710
阅读 2632
收藏 0

上一篇

Where To Put "Stuff" 东西都放哪儿?

When developing applications with Laravel, you may sometimes wonder where to put "stuff". For example, where should you put "helper" functions? Where should you put event listeners? Where should you put view composers? It may be surprising for you to know that the answer is: "wherever you want!" Laravel does not have many conventions regarding where things belong on the file system. However, as this answer is not often satisfactory, we'll explore some possible locations for such things before moving on.

当用 Laravel 开发应用时,你可能迷惑于应该把各种“东西”都放在哪儿。比如,辅助函数要放在哪里?事件监听器要放在哪里?视图组件要放在哪里?答案可能出乎你的意料——“想放哪儿都行!”Laravel 并没有很多在文件系统上的约定。不过这个答案的确不能让人满意,所以下面我们就这个问题展开讨论,一起探索这些“东西”究竟可以放在哪儿。

Helper Functions 辅助函数

Laravel ships with a file full of helpers functions (support/helpers.php). You may wish to create a similar file containing helper functions relevant to your own application and conding style. A great place to include these functions are the "start" files. Within your start/global.php file, which is included on every request to the application, you may simply require your own helpers.php file:

Laravel 有一个文件(support/helpers.php)里面都是辅助函数。你或许希望创建一个类似的文件来存储你自己的辅助函数。“start”文件是个不错的入口,该文件会在应用的每一次请求时被访问。在start/global.php里,你可以引入你自己写的helpers.php文件,就像这样:

<!-- lang:php -->
// Within app/start/global.php

require_once __DIR__.'/../helpers.php';
//译者注: 该helpers.php文件位于app目录下,需要你自己创建。你想放到别的地方也可以。

Event Listeners 事件监听器

Since event listeners obviously do not belongs in the routes.php file, and can begin to clutter the "start" files, we need another location to place this code. A great option is a service provider. As we've learned, service providers are not strictly for registering bindings in the IoC container. They can be used to do all sorts of work. By grouping related event registrations inside of a service provider, the code stays neatly tucked away behind the scenes of your main application code. View composers, which are a type of event, may also be neatly grouped within service providers.

事件监听器当然不该放到routes.php文件里面,若直接放到“start”目录下的文件里会比较乱,所以我们要找另外的地方来存放。服务提供者是个好地方。我们之前了解到,服务提供者可不仅仅是用来做依赖注入绑定,还可以干其他事儿。可以将事件监听器用服务提供者来管理起来,让代码更整洁,不至于影响到你应用的主要逻辑代码。视图组件其实和事件差不多,也可以类似的放到服务提供者里面。

For example, a service provider that registers events might look something like this:

例如使用服务提供者进行事件注册可以这样:

<!-- lang:php -->
<?php namespace QuickBill\Providers;
    use Illuminate\Support\ServiceProvider;
    class BillingEventsProvider extends ServiceProvider{
        public function boot()
        {
            Event::listen('billing.failed', function($bill)
            {
                // Handle failed billing event...
            });
        }
    }

After creating the provider, we would simply add it our providers array within the app/config/app.php configuration file.

创建好服务提供者后,就可以将它加入到app/config/app.php 配置文件的providers数组里。

Wear The Boot 注意启动流程

Remember, in the example above, we are using the boot method for a reason. The register method in a service provider is only intended for binding classes into container.

记住在上面的例子里面,我们在boot方法里进行编写是有原因的。register方法只能用来进行依赖注入绑定。

Error Handlers 错误处理

If your application has many customer error handlers, they may start to take over your "start" files. Again, like event handlers, these are best moved into a service provider. The service provider might be named something like QuickBillErrorProvider. Within the boot method of this provider you may register all of your custom error handlers. Again, keeps boilerplate code out of the main files of your application. An error handler provider would look something like this:

如果你的应用里面有很多自定义的错误处理方法,那你的“启动”文件可能会很臃肿。和刚才的事件监听器一样,错误处理方法也最好放到服务提供者里面。这种服务提供者可以命名为像QuickBillErrorProvider这种。然后你在boot方法里想注册多少错误处理方法都可以了。重申一下精神:让呆板的代码离你应用的业务逻辑越远越好。下方展示了这种服务提供者的一种可能的书写方法:

<!-- lang:php -->
<?php namespace QuickBill\Providers;
use App, Illuminate\Support\ServiceProvider;
class QuickBillErrorProvider extends ServiceProvider {
    public function register()
    {    
        //
    }

    public function boot()
    {
        App::error(function(BillingFailedException $e)
        {
            // Handle failed billing exceptions ...
        });
    }
}

The Small Solution 简便做法

Of course, if you only have one or two simple error handlers, keeping them in the "start" files is a reasonable and quick solution.

当然如果你只有一两条简单的错误处理方法,那么都写在“启动”文件里面也是一种又快又好的简便做法。

The Rest 其他

In general, classes may be neatly organized using a PSR-0 structure within a directory of your application. Imperative code such as event listeners, error handlers, and other "registeration" type operations may be placed inside of a service provider. With what we have learned so far, you should be able to make an educated decision on where to place a piece of code. But, don't be hesitate to experiment. The beauty of Laravel is that you can make conventions that work best for you. Discover a structure that works best for your applications, and make sure to share your insights with others!

通常只要遵循 PSR-0(译者注:或 PSR-4)就可以保持类的整洁。命令式的代码比如事件监听器、错误处理器还有其他“注册”性质的操作都可以放在服务提供者里面。对于什么代码要放在什么地方这个问题,结合你目前为止学到的知识,应当可以给出一个有理有据的答案了。但永远不要害怕试验。Laravel 最美妙之处就是你可以做出最适合你自己的风格。去探索和发现最适合你自己应用的结构吧,别忘了和他人分享你的见解!

For example, as you probably noticed above, you might create a Providers namespace for all of your application's custom service providers, creating a directory structure like so:

例如你可能注意到我们上面的例子,你可以创建个Providers的命名空间来存放你自己写的服务提供者,目录就类似于这样:

<!-- lang:php -->
// app
    // QuickBill
        // Billing
        // Extensions
            //Pagination
                -> Environment.php
        // Providers
            -> EventPusherServiceProvider.php
        // Repositories
        User.php
        Payment.php

Notice that in the example we have a Providers and an Extensions namespace. All of your application's service providers could be stored in the Providers directory in namespace, and the Extensions namespace is a convenient place to store extensions made to core framework classes.

看上面的例子我们有ProvidersExtensions两个命名空间(译者注:分别对应两个同名目录)。你自己写的服务提供者可以放到Providers命名空间下。那个Extensions命名空间可以用来存放你对框架核心进行扩展的类。

下一篇

© 著作权归作者所有

共有 人打赏支持
zgldh
粉丝 95
博文 35
码字总数 46344
作品 2
高级程序员
私信 提问
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
0
4
From Apprentice To Artisan 翻译 17

上一篇 Open Closed Principle 开放封闭原则 Introduction 介绍 Over the life time of an application, more time is spent adding to the existing codebase rather than constantly addi......

zgldh
2015/03/18
0
0
From Apprentice To Artisan 翻译 08

上一篇 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 ......

zgldh
2014/12/09
0
0
From Apprentice To Artisan 翻译 02

上一篇 Taking It Further 更进一步 Let's consider another example to solidify our understanding. Perhaps we want to notify customers of charges to their account. We'll define tw......

zgldh
2014/08/22
0
1
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
0
0

没有更多内容

加载失败,请刷新页面

加载更多

爬虫教程」Python做一个简单爬虫,小白也能看懂的教程

俗话说“巧妇难为无米之炊”,除了传统的数据源,如历史年鉴,实验数据等,很难有更为简便快捷的方式获得数据,在目前互联网的飞速发展写,大量的数据可以通过网页直接采集,“网络爬虫”应运...

糖宝lsh
今天
1
0
KEIL MDK工程中的宏定义:字符,值,字符串

下图中定义了2个宏: 等效于文件中: #define MCU_FLASH_LESSTHAN_64K #define VERSION_INFO_hw 'a' // MDK :VERSION_INFO_hw="'a'" 即MDK中的VERSION_INFO_hw="'a'" 和 #define VERS......

SamXIAO
今天
0
0
集合的最优子集划分

问题描述:如何将一个个数为n的集合N划分为为若干个子集N1…Nk,其中1≤k≤n,计算出每个子集的最优结果R1…Rk,使得F(R1…Rk)为最优的结果。 这个问题可以分成3步解决: 求出集合所有子集 ...

laolin23
今天
0
0
JavaScript实现在线Markdown编辑器、转换HTML工具-toolfk程序员工具网

本文要推荐的[ToolFk]是一款程序员经常使用的线上免费测试工具箱,ToolFk 特色是专注于程序员日常的开发工具,不用安装任何软件,只要把内容贴上按一个执行按钮,就能获取到想要的内容结果。T...

toolfk
今天
3
0
Source Tree 在git 密码更新后,无法拉取代码的解决办法

背景: git 密码总是需要修改。在修改代码后,拉去代码, source tree 总提示access denied. 解决方法:重新修改git 仓库对应的密码。 for mac:应用程序 -》 钥匙串 -》 搜索 source tre...

Carlyle_Lee
今天
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部