PHP

  minte9
REMEMBERS




Last update:   29-10-2021

Registry Pattern

Allows any object to be used as Singleton, without it being written as Singleton.
 
class MyController extends MyBaseController
{
    public function listAction()
    {
        $articles = $this->articleModel->getArticles(); 
            // __get() called
    }
}

class MyBaseController
{
    private $register = array();

    public function __get($var) // Magic method
    {
        if (strstr($var, 'Model')) {

            $modelKey = substr($var, 0, -5);

            if (in_array($modelKey, $this->register)) {
                return $this->register[$modelKey];  // Look Here
            } else {
                eval('$model = new '. ucfirst($modelKey).'Model();');
                $this->register[$modelKey] = $model;
                return $model;
            }
        }
    }
}


class ArticleModel
{
    public function getArticles()
    {
        echo 'articles displayed';
    }
}


$test = new MyController();

$test->listAction(); // articles displayed

Questions    
Composer
        A B C D E F
🔔
1/1