0

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.
duellsy
  • 8,497
  • 2
  • 36
  • 60

2 Answers2

2

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.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

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.

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191