سؤال

I am quite new to 'modern' php, as my day job is spent working on a 10 year old codebase. I am trying to upskill myself, and I'm writing a demo app just to try implement some of the newer and better practices now used in php.

I am trying to keep dependencies low with separation of concern in my classes. But I thought it would be nice to have some sort of debugging class globally available that would output messages etc when I set a debug flag to on. eg

class Blah {
    function getBlah($config) {
        Debugger::message('start call to getBlah()');
        if(empty($config['some_arg'])) {
            Debugger::error('$config[some_arg] not passed to getBlah()');
            return false;
        }
        Debugger::message('end call to getBlah()');
    }
}

(This is obviously a very contrived example, but I am trying to show the Debugger class I am talking about being used.)

Other than the problem of Debugger becoming a dependency of this Blah class, it just feels like the 'old' php I am used to. I know I could pass the Debugger class to the Blah class instead of assuming it's there, but I would need to do this to all new classes.

It all just feels wrong, I am assuming there is a much better way to handle something like this I just don't know yet. Any suggestions.

PS I am aware of all the new frameworks and components that are better than me, and how I should be using them. I understand and agree, I'm just trying to build something from the ground up myself as a learning activity.

هل كانت مفيدة؟

المحلول 2

Just had an idea: What about traits? I could create the Debugger as a trait instead of a class. Then any class I want to use the debugger in, I simply add a use Debugger; statement to.

I think that seems less complicated and less overhead than a full scale DI in this instance.

نصائح أخرى

Use a DI container which you instantiate and will look for the scope for you. Then you bootstrap that. Its a common way to ensure DI and you dont need to repeat yourself. Its not a framework its a small component that you can download. I would suggest using Laravel's Illuminate container for ease of usage

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top