Sign in
Log inSign up

How to handle dynamic classes in PHP?

Emil Moe's photo
Emil Moe
·Apr 21, 2017

I am building a collection of packages for myself for current and future projects that will allow me to reuse code and work faster but also deliver a lot higher quality over time and well tested.

Now I want to make extensions to my extensions, but I want it to be with a minimum of configuration. I have already made a package for basic user stuff like CLI: creating a user & changing password, a login form, etc.

I want to extend that with roles and permissions, but this would require me to add additional methods to the user class which is located in my User-extension, on the same time I don't want to have to modify my user package when I install the permission package.

As changing classes at runtime are not very supported in PHP I have thought a little about if I should make a magic __call in my user class, which means it supports extension. Could I have an observer that I from permission add to like this


Package::extend(Packages\User::class, Packages\Permission::class, 'hasPermission');

Or do you have better ideas? I haven't tested out yet if my theory works.

The user class would have a trait called Extendable that will look for extended methods when no one are found in it's own file.