Let's say I have 3 PHP classes: ShedBuilder, HouseBuilder and TableBuilder and the following code:
$worker_1 = new ShedBuilder(); // I only know how to build a shed
$worker_2 = new HouseBuilder(); // I only know how to build a house
$worker_3 = new TableBuilder(); // I only know how to build a table
$worker_1->build();
$worker_2->build();
$worker_3->build();
I want worker_1, worker_2, and worker_3 classes to each share the same toolset for the job, for example, I want all 3 workers to use the tools available, in this case a hammer, screwdriver, nails, etc. But worker_1 will build a shed, worker_2 will build a house, worker_3 builds a table.
What's the best way to set the toolset once and then have each of the 3 workers know how to access the tools they need for the job?
I thought about having Shed/Table/House builder each extend from a parent class, Builder, but that means that when I instantiate each I have to give them each the toolset:
$toolset = new Toolset();
$toolset->addTool('hammer');
$toolset->addTool('screwdriver');
$toolset->addTool('nails');
$worker_1 = new ShedBuilder($toolset);
$worker_2 = new HouseBuilder($toolset);
$worker_3 = new TableBuilder($toolset);
I'd rather instantiate the tools once and then have all 3 workers/classes know about the toolset and build each of their items, respectively.
What's the best way to implement what I'm trying to do in PHP?
What you have already, instantiating a Toolset
and providing $toolset
to each of the worker classes in their constructors, is called Dependency Injection, and it is actually the preferred way of handling this task most of the time.
It is possible to accomplish it by creating a singleton Toolset
object, however that is unnecessary when dependency injection handles it in a tidy and easily testable way.
I think using a parent class for those 3 builder classes, and in the parent class using static variable for toolset will do. Check this page for usage of static variable.