NYCPHP Meetup

NYPHP.org

[nycphp-talk] How to make a model/database accessible to different parts/classes of the application

Dell Sala dell at sala.ca
Wed Aug 29 20:40:24 EDT 2007


> [...] my second attempt was to create a singleton, but the problem  
> is that my model needs configuration data in order to be  
> instantiated correctly. So whenever I would call the getInstance 
> (...) method I need to have the model's configuration data  
> available as I can't always be sure that the getInstance method has  
> been called before and an instance of the model class already exists.

> [...] I wanted to create a Registry class, add my model to it and  
> access it from whatever method I want. This however makes unit  
> testing harder and has all the site effects which global variables  
> have.

Sounds like you might find some answers in reading about Dependency  
Injection. I've come across this recently, and it's helped my  
thinking around some of these issues. http://www.martinfowler.com/ 
articles/injection.html I think the key here is the concept of the  
"container". It's like a class configuration registry.

There was also a good article about Dependency Injection in a recent  
php|architect issue:
http://www.phparch.com/issue.php?mid=82

The idea of implementing a generic container seemed a little overkill  
for most of what I was doing. I've found myself using static methods  
to configure a class (rather than a singleton), and I place my  
configuration code in a bootstrap file. For example, the bootstrap  
file might look something like:

require_once 'Proj/SomeModel.php';

Proj_SomeModel::configure(array(
    'option1' => 'some value',
    'option2' => 'another value',
));

The boostrap could either be a global one, or one that could be  
required only when I knew I was going to work with the model. The  
model object would then access these static config values within the  
constructor when instantiating itself. Using a model becomes a simple  
as:

require_once 'model-bootstrap.php';

$model = new Proj_SomeModel();

Don't know if this is helpful, or just rehashing things you've  
already tried. Care to share more details about what you've tried so  
far?

-- Dell






More information about the talk mailing list