How to handle dynamic classes in PHP?

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.

Emil Moe

Expert in Laravel and Vue backed with MySQL databases. Independent developer who does freelance and love to travel. Feel free to drop me a message.

- Emil

Write your comment…

traits is one way. you could use __call with an array inside that contains 'key' => function() { return 'bla' }

using so called virtual registers for compositions you can even set the the "this" reference inside the closures to point at the parent class.

another way could be using anonymous classes with reflections. problem ofc time complexity goes up. or you could generate classes with eval or like doctrine does it to file. github.com/nikic/php-ast but to keep it simple I would go for the function compositions with the magic __call it's rather easy.

just from the top of my head.

Show all replies

Emil Moe I would have to read up on it but the code I read there already shown a generative approach which is less flexible! But I build agnostic libraries and you are adding specific functionality for your problem, as far as I understood it, that's a good solution for your case.

This was more about my taste than anything else ! It's a good solution if it works ! It's solid it's analyzable ! it's controllable. :)

Reply to this…