我怎样才能让我的特质扩展到一个班级
I understand that by definition, a trait cannot extend a class, however I'm wondering if there's some kind of workaround.
My situation:
I created the package revisionable, which in its first incarnation was a class that you extended from your model which itself extended Laravels base Eloquent class, however over time there were plenty of requests to change this into a trait, so people could use
revisionable, and be able to extend their own base class.
Currently, the only that I can think to allow for both an extendable class, and a trait, is to offer both as a whole files, which means I'm repeating the entire code in two files which could easily lead to trouble down the road.
I'm wondering if anybody knows of some solution where I can have one file that is god, and the other file relies on it.
Rules
- The existing class cannot use a trait, as existing users of the package on php 5.3 will not have access to traits.
据我所知,根据定义,特质不能扩展一个类,但是我想知道是否有某种解决方法 。 p>
我的情况: h2>
我创建了包可修改,它的第一个版本是你从你的模型扩展的类,它本身扩展了Laravels基础Eloquent类,但是随着时间的推移,有很多要求将其变成一个特征,所以人们可以使用 code>可修改,并且能够扩展自己的基类。 p>
目前,我唯一可以考虑允许扩展类和特性, 是提供两个整体文件,这意味着我在两个文件中重复整个代码,这很容易导致麻烦。 p>
我想知道是否有人知道 一些解决方案,我可以有一个文件是上帝,另一个文件依赖它。 p>
规则
- 现有的类不能使用特征,因为php 5.3上的软件包的现有用户将无法访问特征。 li>
ul> \ n div>
There's absolutely no way to accomplish what you want.
Since Laravel itself (in 4.2) has now abandoned PHP 5.3, it's time to move on too.
Tag a new release that drops the class, add a PHP 5.4 requirement to your composer.josn
file, and add this information to your docs.
Anyone still stuck on 5.3 can always just composer require
your previous version.
Php 5.3 is a problem. Back in when it was popular, the programming style was all about include/require files into another files. If you can split your functionality into functions that may be included in trait and in class - it may be a solution. But it depends of the functionality.
Modern way would be decoupling and dependency injections, in other words think units and unittesting.
Problem of a trait as well as the problem of the child-class is that you cannot unittest the pure functionality of what you have done without touching the parent class functionality. You cannot mock parent class, you can only mock injected class, right?
Think modern. Create a class, inject Eloquent object there. And then use this class in traits and some parent class for laravel models.
And forgive Taylor for the fact that you cannot mock the Eloquent. He may be able to fix it in new versions of Laravel. But you'll have to move to PHP7 because it is a requirement for latest laravel releases.