0

There are different general types of recipes, and each general type has different methods. The database queries the ID provided in the URL to determine the type and a different class is used.

One option is:

$c['recipeFactory'] = function ($c) {
    return new RecipeFactory($this->get('pdo'));
};

$app->put('/recipes/{id:[0-9]+}', function (Request $request, Response $response, $args) {
    //Factory will query DB and create and return object
    $obj=$this->recipeFactory->create($args['id']);
    $obj->update($request->getParsedBody());
});

Seems like more often than not, a static method is used to implement a factory, so maybe I should do the following:

$app->put('/recipes/{id:[0-9]+}', function (Request $request, Response $response, $args) {
    $obj=RecipeFactory::create($args['id'], $this->get('pdo'));
    $rs=$obj->update($request->getParsedBody());
});

But then, I am not using the container, but the following will not work as $args['id'] not defined.

$c['recipeFactory'] = function ($c) {
    return new RecipeFactory($args['id'], $c->get('pdo')); 
};

Should static methods be used for the factory method?

How should the factory pattern be implemented with Slim Framework?

user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

0

How should the factory pattern be implemented with Slim Framework?

It depends, in the example you provided I would clearly go with your first solution.

Having an actual object and not a static factory methods has serveral benefits:

  • the factory can be mocked inside tests
  • it encapsulates the PDO-instance; the route must not know that the factory needs a PDO-instance
  • it is consistent, the PDO-instance is created by the container and no static factory is used for it

Should static methods be used for the factory method?

See Constructors vs Factory Methods.

jmattheis
  • 10,494
  • 11
  • 46
  • 58