jacopo beschi: yet another web guy

PHP and lazy loading

Created at: Sep/29/2014 jacopo beschi

Any if you ever heard of lazy loading? Lazy loading is a tecnique used for data caching in software engineering. The concept of lazy loading is really simple: if you already have loaded a resource one time, then you will not load a new one but instead just return the one you have already loaded. How can you do that in php? Here's a snippet. Imagine you want to load the current logged user:

<?php
class Authhentication {
    protected $current_user = null;

    public function currentUser(){
        if($this->current_user) return $this->user;

        // otherwise put here the code that actually load the user
        //...
        // and then set the user in your user variable;
        $this->user = ...;

        return $this->user;
    }
}

Here you are, by saving your loaded data in a field you can serve that data the next time you have a request. That's all for now, happy coding!

comments powered by Disqus