用Trait来导入Util函数能否作为一种解决方法?
一般对于Util方法,不外乎下面几种方法,以及我的一点看法:
- 依赖注入(好,但麻烦,且Util似乎与注入对象的主业关系不大)
- 弄一个包含Util方法的Container,然后注入(比上面那个只好一点点)
- 静态方法(static is evil)
PHP 5.4 引入了 Trait,一般来说,用它作为 Interface 的默认实现似乎受众比较多。
用 Trait 来导入 Util 函数肯定是可行的,但这种解决方法是否违背 OOP 原则?是否最佳或者“优雅”呢?我举个例子:
<code>Trait FormatDatetimeTrait { proteted function formatDatetime($datetime, $style) { return date($style, $datetime); } } </code>
好了,这个方法干的活儿似乎多余————这不是我们讨论的重点,这只是个例子。在其他类中使用这个 Trait:
<code>Class FooBar { use FormatDatetimeTrait; /** Other stuff **/ protected function getDate() { return $this->formatDatetime($this->time, $this->timeStyle); } } </code>
我想这里 Trait 的引用还是有好处的:
- 依赖关系明了,虽然和类的主业关系不大,但毕竟用到它了
- 导入的方法可以改名(formatDatetime as formatTime)
- 客户类可以在导入函数基础之上扩展
那么,作为一种代码重用的工具,这么使用 Trait 都有那些缺点呢?是否违背 OOP 原则,或者违背它的设计初衷呢?
也欢迎有其他语言 Trait 使用经验的朋友提出宝贵意见 :-)。
回复内容:
一般对于Util方法,不外乎下面几种方法,以及我的一点看法:
- 依赖注入(好,但麻烦,且Util似乎与注入对象的主业关系不大)
- 弄一个包含Util方法的Container,然后注入(比上面那个只好一点点)
- 静态方法(static is evil)
PHP 5.4 引入了 Trait,一般来说,用它作为 Interface 的默认实现似乎受众比较多。
用 Trait 来导入 Util 函数肯定是可行的,但这种解决方法是否违背 OOP 原则?是否最佳或者“优雅”呢?我举个例子:
<code>Trait FormatDatetimeTrait { proteted function formatDatetime($datetime, $style) { return date($style, $datetime); } } </code>
好了,这个方法干的活儿似乎多余————这不是我们讨论的重点,这只是个例子。在其他类中使用这个 Trait:
<code>Class FooBar { use FormatDatetimeTrait; /** Other stuff **/ protected function getDate() { return $this->formatDatetime($this->time, $this->timeStyle); } } </code>
我想这里 Trait 的引用还是有好处的:
- 依赖关系明了,虽然和类的主业关系不大,但毕竟用到它了
- 导入的方法可以改名(formatDatetime as formatTime)
- 客户类可以在导入函数基础之上扩展
那么,作为一种代码重用的工具,这么使用 Trait 都有那些缺点呢?是否违背 OOP 原则,或者违背它的设计初衷呢?
也欢迎有其他语言 Trait 使用经验的朋友提出宝贵意见 :-)。
Trait 属于静态模板(虽然可以被使用的类改写),不具备继承特性,所以不能用于继承关系比较复杂的场景。比如:
<code>有一个 BaseTrait,被两个 UtilTraitA, UtilTraitB 都 use 了,然后呢,在一个类里面,要同时用到这两个 UtilTrait,这时问题来了,由于他们两个都使用同一个BaseTrait,BaseTrait 里面的方法就被重复导入了,这种冲突直接报错,并且无法解决。 </code>
Trait 的设计就是语法糖,具备类似继承的特征,但是和继承不一样。
所以,Util 方法全部改写为 Trait 虽然一开始可行,但必定会遇到使用时的冲突,因为如果使用了 Util Trait,其他 User Trait 再使用 Util Trait,那么使用这些 User Trait 的类极易产生导入冲突。
那么,Trait 应该怎么用?当模版用!解决少量代码重复的语法糖。绝对不可以把它用作继承体系的一部分,并且要注意方法命名,尽量避免和其他类产生冲突。
最后,Trait 不可以 implement interface,PHP 这么设计还是有道理的。
原讨论: https://coding.net/u/fwolf/pp/25934
楼主,对于Trait的用途php官方文档说的很详细,你应该再仔细读读。
自 PHP 5.4.0 起,PHP 实现了代码复用的一个方法,称为 traits。
Traits 是一种为类似 PHP 的单继承语言而准备的代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用方法集。Traits 和类组合的语义是定义了一种方式来减少复杂性,避免传统多继承和混入类(Mixin)相关的典型问题。
Trait 和一个类相似,但仅仅旨在用细粒度和一致的方式来组合功能。Trait 不能通过它自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用类的成员不需要继承。
http://php.net/manual/zh/language.oop5.traits.php

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
