adoado Posted October 30, 2011 Share Posted October 30, 2011 Hello everyone! Recently I have been reading up a lot on the notion of dependency injection, and it's making good sense. It's a very cool idea! I just wanted to run my current understanding though people here so I can get advice if it's the correct approach. Let's say I have many users that will access the forum. To control logging in, verification, registration, etc. it makes sense to encapsulate all these 'abilities' into a class, say, USER. Hence, USER contains mutator methods for all the required actions. Similarly, to retrieve a list of threads, posts, etc. (non-personal data), is it wise to have another class, FORUM, which manages all this? If so far is so good, then clearly both the above classes have the database engine as a dependency. So, from what I've read, making a container class that contains the database connection variable as a static field and instantiating USER and FORUM through this CONTAINER is the best way, injecting this static database connection along the way. So: A new user is created through CONTAINER, NewUSERClass(); USER gains it's database connection through a static variable in CONTAINER. Hence, it's dependency is injected. If that is correct also, here is where I am confused. Where should this static database connection be made? Or, should I verify the connection exists everytime a USER or FORUM class is instantiated through it? Similarly, let's say I have a class that contains SETTINGS (max password length, post title length, etc.) Should this be a separate class, or merely distributed into USER and FORUM? The latter is easy, but makes two very big classes. If not, there is too much coupling between classes (SETTINGS needs a database engine, USER needs settings AND a database engine, etc.) I have never been formally taught programming, so perhaps I am way off the mark here, but I'd appreciate any advice you might have! Thanks for reading! Adrian Quote Link to comment https://forums.phpfreaks.com/topic/250086-usage-of-dependency-injection-design-pattern/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.