PHP的特质–任何实际示例/最佳实践? [英] Traits in PHP – any real world examples/best practices?

查看:94
本文介绍了PHP的特质–任何实际示例/最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特质是PHP 5.4的最大新增功能之一.我了解语法并了解特性背后的思想,例如将水平代码重用于日志,安全性,缓存等常见内容.

Traits have been one of the biggest additions for PHP 5.4. I know the syntax and understand the idea behind traits, like horizontal code re-use for common stuff like logging, security, caching etc.

但是,我仍然不知道如何在项目中利用特质.

However, I still don't know how I would make use of traits in my projects.

是否有任何已经使用trait的开源项目?关于如何使用特征构造体系结构的任何好的文章/阅读材料?

Are there any open source projects that already use traits? Any good articles/reading material on how to structure architectures using traits?

推荐答案

我个人的观点是,编写简洁的代码时,特质的应用很少.

My personal opinion is that there is actually very little application for traits when writing clean code.

与其使用特征将代码入侵到类中,不如通过构造函数或setter传递依赖项:

Instead of using traits to hack code into a class it is better to pass in the dependencies via the constructor or via setters:

class ClassName {
    protected $logger;

    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }
    // or
    public function setLogger(LoggerInterface $logger) {
        $this->logger = $logger;
    }
}

我发现比使用特征更好的主要原因是,通过消除与特征的硬耦合,您的代码更加灵活.例如,您现在可以简单地传递另一个记录器类.这使您的代码可重用和可测试.

The main reason why I find that better than using traits is that your code is much more flexible by removing the hard coupling to a trait. For example you could simply pass a different logger class now. This makes your code reusable and testable.

这篇关于PHP的特质–任何实际示例/最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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