HomePHP Page 4 - Applying the Dependency Injection Pattern and Factory Methods in PHP 5
Creating persistent objects without a factory method - PHP
Welcome to the final part of a series on implementing factory methods in PHP 5. Composed of six approachable tutorials, this series uses numerous hands-on examples to teach you how to define specific methods within your own PHP programs. These methods return to client code instances from their originating classes, and from other classes as well.
As I expressed before, I’d like to conclude this tutorial by showing you how to build a couple of persistent objects (or more, if you want to) even though the factory method of the MySQL abstraction class has been removed.
To prove that, here’s another script that shows how to perform this task, assuming that the definitions of the corresponding sample classes have been previously included. Take a look at it:
// create instance of MySQL class and inject it into the user class constructor
$db = new MySQL('host', 'user', 'password', 'database');
// create first user object
$user1 = new User($db);
$user1->name = 'Susan Norton';
$user1->email = 'email@example.com';
// create second user object
$user2 = new User($db);
$user2->name = 'Mary Smith';
$user2->email = 'firstname.lastname@example.org'
As shown above, an instance of the MySQL class has been injected directly into the constructor of each persistent object. Naturally, the most important thing to stress here is that this was achieved without calling any factory method. Pretty neat, huh?
This example demonstrates how an adequate implementation of the Dependency Injection pattern allows you to pass an instance of a given class to other objects without using factories. Of course, this is valid only when the dependency is injected via a constructor or setter method, but if a dependency container is required, then coding a factory method that returns Singletons surely will be a good option.
It’s hard to believe, but we’ve come to the end of this series. Hopefully the experience has been educational for you, since you learned the basics of defining and implementing factory methods in PHP 5.
As you saw from the examples developed in the subsequent tutorials, a proper use of the Factory and Singleton patterns can be a powerful combination that allows you to write more robust and efficient applications. Think of them the next time that you need to build a truly killer PHP program.