Search code examples
architectureormkohanafactory-pattern

Why does Kohana's ORM use the factory pattern?


(Forgive me if this is not clear; I'm not quite sure what I'm asking.)

Why does the Kohana ORM module use a factory method to create instances of ORM classes, given that one must always pass factory() the name of the class that one wants to get back?

My understanding of the factory pattern is that it is used when the client code doesn't know beforehand the (concrete) type of the object that will result.

The Kohana guide does say that the following are both acceptable:

$user = ORM::factory('User');
// Or
$user = new Model_User();

But why use the first over the second?


Solution

  • The correct answer is simply 'chaining'.

    In PHP 5.4 you can now do (new Model_User)->save(), but in the past you would have to do this as two separate lines of code. So Model::factory('User')->save() wins. However this is no longer necessary.

    Notice I didn't mention ORM. Kohana uses this pattern quite a bit. But in some cases, like ORM, the factory method actually takes additional arguments which are sent to the constructor.

    By the way, there is a difference between a factory method and the factory pattern. Don't confuse them.