Hi Aurimas,

That's my blog post, and using an identity map definitely can improve
performance, especially when you need to fetch the same object multiple
times in a request. For example, if PHP is generating a page with 20
comments and 10 of them are by the same person, you don't want to make a
round-trip to the database each time you want to show the commentor's
username.

As for loading models from a view helper, what I would do is write a view
helper that acts as a proxy to a data mapper (or some other type of model
loader). The view helper itself wouldn't know about the identity map,
because you want to move that logic as far down the stack as possible. That
means your data mapper will be the only object using the identity map
directly.

With that in mind, you'll need a way to get the mapper from within the view
helper. DI can help, but since view helpers are lazy-loaded you might want
to pull the dependencies from a static resource instead (like the front
controller or registry).

I've also used an identity map to keep track of mapper instances in order to
make them behave more like singletons (without making them singletons).
Basically I would have a static factory method that loads the mappers but
also stores them in a static array in case it is fetched again. Something
like this:

class My_DataMapper_Manager
{
    protected $_mappers = array();

    public static function getMapper($class)
    {
        if (!isset(self::$_mappers[$class])) {
            self::$_mappers[$class] = new $class();
        }
        return self::$_mappers[$class];
    }
}

Of course you'll have to adjust this if you want to inject dependencies into
the mappers (like a DB connection) but otherwise its goal is reduce the
number of duplicate instances to 0 without introducing the problems that
singletons have (e.g. testing).

--
Hector


On Wed, Jun 9, 2010 at 3:08 PM, Aurimas Likas <[email protected]> wrote:

> Now I'm thinking about the best way to access models from the view helpers
> in terms of performance.
>
> I dont like the idea of creating the same model instance througout all view
> helpers. Its an overhead. One developer pointed me to use Dependency
> Injection Container.. dont know where and how to start (maybe you could
> provide some pointers to blog post or so). Do you use DIC for that?
>
> Today I found in the Virgens blog a post about Identity Maps 
> here<http://www.virgentech.com/blog/2010/02/building-identity-map-php.html>.
> Maybe these could be used? Share your experience on this topic ;-) Thanks in
> advance!
>
> --
> Aurimas Likas
> tel. +37067730631
> e-mail: [email protected]
> URLs: http://magento.lt
>

Reply via email to