On Wed, Jul 17, 2013 at 9:44 AM, Björn Rylander <[email protected]> wrote:
> I'm a little confused regarding the "proper" ZF2 pattern for object
> instantiation. I had come to the conclusion that all objects should be
> instantiated with factories. But looking at the Album tutorial I can see
> that the Album object and the AlbumForm object are directly instantiated in
> the AlbumController::addAction(). So, what is the ZF2 pattern for
> instantiating objects? Is there a rule when factories should be used or not
> used?

The rules of thumb are:

- will I need the same instance, OR
- will I need an instance using non-trivial instantiation (e.g.,
wanting to tie into existing initializers), OR
- will I need to be able to substitute an extending class/alternate
implementation

If the answer is any of the above is "yes," it's likely a service, and
should be managed by the ServiceManager.

In the tutorial, the form is only used in one location, and has a very
specific set of rules. Tthe Album object is a result of querying the
database; we provide a _prototype_ instance that the result set can
hydrate when results are available.

If the object is a result of calculation, or a one-off, direct
instantiation is fine, and encouraged.

--
Matthew Weier O'Phinney
Project Lead            | [email protected]
Zend Framework          | http://framework.zend.com/
PGP key: http://framework.zend.com/zf-matthew-pgp-key.asc

--
List: [email protected]
Info: http://framework.zend.com/archives
Unsubscribe: [email protected]


Reply via email to