将特征用于服务层:这是不好的做法吗? [英] Using traits for service layer: is it bad practice?

查看:67
本文介绍了将特征用于服务层:这是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,laravel程序员通常使用特征来在控制器中实现某种类型的依赖注入,并且laravel本身也使用许多特征来实现对我来说似乎是服务的东西。

I have noticed that it is common for laravel programmers to use traits to implement some kind of dependency injection in controllers and also laravel itself uses lots of traits to implement something that it seems to me, to be services.

我来自symfony,那里的框架本身并未广泛使用traits,由于这种原因,我发现使用trait时有点奇怪,我不太清楚设计。服务不应该在自己的类中定义吗?将特征用于服务是否可以接受?

I come from symfony where traits are not widely used from the framework itself and I find it a little bit odd as I find using trait for such a reason, not so clear design. Shouldn't services be defined in their own classes? Is it acceptable to use trait for services?

推荐答案

我注意到先前的回答尚未被接受,所以我想给自己2美分。

I noticed the previous answer was not yet accepted so I thought giving my own 2 cents.

同样来自Symfony 2环境,目前正在参与Laravel并为Symfony 3环境做准备,就像我过去一样,我也在阅读该主题。读到特质是邪恶的。以下链接具有一个可接受的答案,在我看来这不是一个很主观的答案,它做出了一些合理的假设,并且似乎构筑得很好: https://codereview.stackexchange.com/questions/74077/trait-accessing-variings-of-classes-using-it

Coming as well from a Symfony 2 environment, being involved with Laravel currently and preparing for a Symfony 3 environment I was reading up on the subject as well, as I used to read that traits are evil. The following link has an accepted answer that is in my opinion a not so badly subjective one, it makes some fair assumptions and it seems well constructed: https://codereview.stackexchange.com/questions/74077/trait-accessing-variables-of-classes-using-it

但是,我认为对您来说最大的不同可能是默认的Laravel使用的是ActiveRecord,而不是Symfony使用的Service / Repository层。我个人更喜欢后者,因为它不那么笨重,可以更轻松地实现SOLID,逻辑和数据通常已经解耦,从而使各层更易于交换。无论如何,这不是一个话题性很强的个人笔记。

However, I would think the biggest difference for you might be that the default Laravel is using ActiveRecord, in contrast with having the Service/Repository layers that are used by Symfony. I personally prefer the latter, it's less heavy, keeps it easier to be SOLID, logic and data are more often already decoupled, making the layers more easily swappable. Anyway, this is a not-so-on-topic and very personal note.

在Laravel工作了几个月后(相比之下,我为在sf2(和sf1)工作多年了,我并不是Laravel如何工作的专家。就我个人而言,我仍然不喜欢特质,因为如果您至少不使用它们,它们对我来说太神奇了。我通常认为可以通过其他设计模式更好地处理它。

After working in Laravel now for a couple of months (in comparison, I have worked for years in sf2 (and sf1)) I'm hardly an expert in how Laravel works. Personally I still dislike traits because they feel too magical to me, if you do not interface them at least. I often think it is better handled through other design patterns.

TL; DR :(基本上是链接要点)

TL;DR: (gist of the link basically)


  • 特征的一个好用例是水平缩放,它支持独立的操作,而不必在每次添加接口时都要实现它。 (通常这是非常简单的逻辑)

  • 一个不好的特征是使用超出其自身范围的信息(例如, main对象的属性或简单的全局状态)使用的特征,或执行/违反合同。

这篇关于将特征用于服务层:这是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆