Other Handlers 其他处理函数

We can improve many other types of "handlers" using this same approach to decoupling. By restricting all handlers to being simple translation layers, you can keep your heavy business logic neatly organized and decoupled from the rest of the framework. To drive the point home further, let's examine a route filter that verifies that the current user of our application is subscribed to our "premium" pricing tier.

使用类似的方式,我们可以改进和解耦很多其他类型的“处理函数”。将这些处理函数限制在转换层的状态,你可以将你庞大的业务逻辑和框架解耦,并保持整洁的代码结构。为了巩固这种思想,我们来看看一个路由过滤器。该过滤器用来验证当前用户是否是交过钱的高级用户套餐。

Route::filter('premium', function()
{
    return Auth::user() && Auth::user()->plan == 'premium';
});

On first glance, this route filter looks very innocent. What could possibly be wrong with a filter that is so small? However, even in this small filter, we are leaking implementation details of our application into the code. Notice that we are manually checking the value of the plan variable. We have tightly coupled the representation of "plans" in our business layer into our routing / transport layer. Now, if we change how the "premium" plan is represented in our database or user model, we will need to change this route filter!

猛一看这路由过滤器没什么问题啊。这么简单的过滤器能有什么错误?然而就是是这么小的过滤器,我们却将我们应用实现的细节暴露了出来。要注意我们在该过滤器里是写明了要检查plan变量。这使得将“套餐方案”在我们应用中的代表值(译者注:即plan变量的值)暴露在了路由/传输层里面。现在我们若想调整“高级套餐”在数据库或用户模型的代表值,我们竟然就需要改这个路由过滤器!

Instead, let's make a very simple change:

让我们简单改一点儿:

Route::filter('premium', function()
{
    return Auth::user() && Auth::user()->isPremium();
});

A small change like this has great benefits and very little cost. By deferring the determination of whether a user is on the premium plan to the model, we have removed all implementation details from our route filter. Our filter is no longer responsible for knowing how to determine if a user is on the premium plan. Instead, it simply asks the User model. Now, if the representation of premium plans changes in the database, there is no need to update the route filter!

小小的改变就带来巨大的效果,并且代价也很小。我们将判断用户是否使用高级套餐的逻辑放在了用户模型里,这样就从路由过滤器里去掉了对套餐判断的实现细节。我们的过滤器不再需要知道具体怎么判断用户是不是高级套餐了,它只要简单的把这个问题交给用户模型。现在如果我们想调整高级套餐在数据库里的细节,也不必再去改动路由过滤器了!

Who Is Responsible? 谁负责?

Again we find ourselves exploring the concept of responsibility. Remember, always be considering a class' responsibility and knowledge. Avoid making your transport layer, such as handler, responsible for knowledge about your application and business logic.

在这里我们又一次讨论了责任的概念。记住,始终保持一个类应该有什么样的责任,应该知道什么。避免在处理函数这种传输层直接编写太多你应用的业务逻辑。

译者注:本文多次出现 transport layer, translation layer,分别译作传输层和转换层。其实他们应当指代的同一种东西。

results matching ""

    No results matching ""