I'm encountering a common issue in PHP (and most other languages) at the moment, where systems I'm designing need to be updated in multiple places to add new features, whereas I would like to have a core, where I can add new features, plugin's etc without having to touch the core code. An example would be a a navigation menu, where the menu loads it's items from directory or namespace X. My aim is so once I or another developer adds a new file, extends a MenuItem class, whichever it needs to be, the class loading the menu would discover this new file and display it, without ever having to touch the core menu loading code.The best I have come up with so far is:function get_menu_items() {    $menu_items = array();    $raw_files = scandir(DOCUMENT_ROOT . '/menu/menu_items');    foreach($raw_files as $file){        require_once($file);        $class_name = substr($file, 0, -4); // cut away the '.php'        $menu_items []= new $class_name();    }    return $menu_items;}But the above feels wrong as I shouldn't be checking a directory for existence of files for features! I imagine this is a common design pattern like wordpress would use for plugin discovery? I've been searching for a while but not been able to better the above! Any help would be greatly appreciated!!
How to discover a class in PHP dynamically much like a plug-in architecture
php
Even tho your solution works fine in principle, it's extremely slow because of using the File-system API and quite vulnerable I'd say. For example, in theory, I can use your upload profile photo form to inject a PHP file with .jpg extension and move it into your plug-ins directory and let your application load it for me.You might not notice the slow-ness of using the file-system api -- on a simple website/CMS with couple of online users at the same time, and no one might even try to attack your web application at all, however if you're looking for a Robust solution, I highly encourage you to come up with a solution that gives you Control over what files are being used/loaded by your script.As an example you can store all of the new plug-ins in a JSON file and use that file as a valid source of installed plug-ins for your script. In this way what you really need is to add the file to the directory and then just add a simple key/value pair to your JSON file. It won't really take that much time, however it will gives a lot piece of mind I'd say.A database-based solution could be a better idea if you need to let a none-technical person to choose between the plug-ins, however in your example it might be an overkill.