This is a classic task for dependency injection and lazy initialization! Dependency is a MySQL connection. Since it must first be available when the first request is executed, it does not need to be initialized at startup, but only then. This is called lazy initialization, and its implementation is extremely simple:
class DbStuff { private $__conn = NULL; protected function _getConn() { if ( is_null( $this->__conn ) { $this->__conn = ... ;
The required "refactoring" requires calling $this->_getConn() in each request method.
Aspect-oriented programming is not a tool to solve this problem, since connecting to the database is an inherent dependence of the request, and not its aspect. An automatic log of all executed queries was an aspect.
A trigger built around PHP __call() is also not a good choice; besides the fact that they knock out modern IDE checks - which look great fast, whether the module is in order - this would unnecessarily complicate the tests: protected $this->_getWhatever() can be easily overwritten in the test facade object obtained from the class so that check - return the layout or something else. With __call() , more code is required for the same purpose, which causes a risk of errors in the code, which exists only for testing (and should be absolutely free from errors)
source share