To Static, or Not To Static

I read that article twice that you linked to. I have to admit most of it goes right over my head at this point. In theory I understand and see why classes full of static properties and methods are not good in the long run, and that dependencies (in my case: Database, Config and Prefs classes, so far) should be passed into an object’s constructor. But in practice, I’m having a difficult time figuring out how to do this with my obviously limited OOP experience and knowledge.

I also found the above article on that same website, but it’s WAY over my head. While I understand the concept of Dependency Injection, I don’t know how this should be implemented in real life. The other article you linked to mentions Factories that can be used to instantiate an object with its dependencies. But that seems like a massive amount of code bloat, creating a factory class for each class to be sure it has its dependencies loaded. I don’t see how this is an improvement or more efficient way of constructing the application, to be honest. Or I’m just not understanding how these factories work.

I did come up with a very simple idea for passing dependencies to each object: putting a list of objects the class depends on in an array and passing that to each class that needs them. Here’s a simple example:

class MyClass 
{
	private $config; 
	private $db; 
	private $prefs; 

	function __construct($params)
	{
		// some code that gets dependencies from $params array
		
		$this->config = $params['config'];
		$this->db = $params['db'];
		$this->prefs = $params['prefs'];
	}
}

// Instantiate core classes

$config = new Config; 
$db = new Database; 
$prefs = new Prefs(USER_ID); // pass user id stored in constant

// add core objects to $params array and pass to class

$params = array( 'config' => $config, 
                 'db'	  => $db, 
                 'prefs'  => $prefs); 

$test = new MyClass($params); 

Simple, but, I know that this is probably not a very good solution, because if I add a dependency in the future that a bunch of classes need, I have to alter the $params array and add the appropriate property to hold the dependent object in each class that needs it. But if I had factories, I’d basically have to do the same thing, altering the factories for each class so that they recognize and inject the new dependency. So I’m guessing I don’t get how factories work in this case.

Hoo boy, not really sure I’m making much sense. :slight_smile:

It’s times like this I want to give up on OOP (again) and jump back to familiar procedural coding so I can just get the work done. I’ve been using PHP for over 15 years, and have always had a hard time wrapping my head around OOP, and just when I think I’m starting to figure it out, I learn that I know even less than I thought.

Thanks very much for your input. Where do you think i should go from here, learn more about factories? Read more about dependency injection? Find a different job?