Dynamically loading traits from subdir?>

Hii there,

I’m trying to load all traits in a directory into my class.
My class currently looks like this:

<?php
namespace App\View;

class Shortcode {
  // Load all shortcodes
  use Shortcode\TestShortcode;

  // other code
}

And my Shortcode/TestShortcode.php looks like this:

<?php
namespace App\View\Shortcode;

trait TestShortcode { 
  protected static function renderTest(array $params){
    return "hello world!";
  }
}

Now I want it to dynamically load all the traits that are in the View/Shortcode directory instead of having to use the use Shortcode\...Shortcode; all the time.
I am not able to use __construct() for this, as I don’t use the new Shortcode() call (instead I use the Shortcode::method() way).

Any ideas?

That’s essentially attaching traits at runtime, which is afaik not possible without ugly hacks. Best thing is probably using a composite trait.

But I would consider why if all the traits are loaded all the time they are split up in the first place. Might be an indicator for code-smell.

I split up the code so I can keep stuff nicely organized and compact (so I can keep, for example, the code that has to do with the “disclaimer” shortcode seperated from the “img” shortcode).

I wanted to load the traits at run time because I’m just lazy and keep forgetting to load the trait into my code manually :slight_smile: