mercredi 6 juillet 2016

Correct implementation of Factory pattern in PHP

I have a question about correct way of implementing factory pattern in PHP used for instantiating complex objects with their dependencies. Let's assume the factory class has a 'build' method, so that for example class User is created in following way:

$factory->build('User');

The class User needs to retrieve the user data from the repository (database), so it depends on Repository object - the constructor looks like:

public function __construct(Repository $repository);

This means that 'build' method of the factory needs to call something like this

$user = new User(new Repository());

Now let's assume I also need to instantiate HomeController object which displays content on the home page. It is retrieving a list of latest articles - to display them on the home page, so it needs repository object as well. So build method will call something like this:

$home = new HomeController(new Repository());

So it is clear now that we have two instances of Repository object, while in fact one instance would be probably enough in this case. So I was wondering if it is a good practise for factory pattern to actually register instantiated Repository object (store it in $registeredObjects array of Factory object) and return it from the table if it was instantiated before. So the object creation in build method would look then like so:

$user = new User($this->build('Repository'));  // Here Repository is created first time.
$home = new HomeController($this->build('Repository'));  //Here it is retrieved from list of already registered objects

Repository object act in fact as a singleton in this case. I am wondering whether this approach is correct or it is better to instantiate two independent Repository objects.

Aucun commentaire:

Enregistrer un commentaire