Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid manually passing my $registry container into constructor of every new class I make?

I've been doing MVC for several months now, and I store everything in my $registry object. When I create a new class, I only ever pass the registry usually, but I'm having to constantly pass the $this->registry when creating a new class.

e.g.

class something
{
   public function __construct($registry)
   {
      $this->registry = registry;
      $this->db = $registry->db;
      $this->user = $registry->user; // ......
   }

   public function something()
   {
      $class = new something_class($this->registry);
      $class->do();
   }
}

class something_class
{
   public function __construct($registry)
   {
      $this->registry = $registry;
   }

   public function do()
   {
     echo 'Doing something ....';
   }
}

My question is, how can I handle the passing of the registry to the new class behind the scenes (in this case when instantiating something_class) inside the registry class somehow? I'm absolutely convinced there is an easy way to do this, but I can't find anything related anywhere to what I'm looking for.

Here is my registry class:

<?php
class registry
{
    protected $vars = array();
    public function &__set($index, $value)
    {
        $this->vars[$index] = $value;
        return $value;
    }

    public function &__get($index)
    {
        return $this->vars[$index];
    }
}

1 Answers

This is all wrong. "Registry" is an anti-patter and what you are doing the is not dependency injection. You have found a way to fake global variables .. that's it.

As a start, please watch this lecture.

As for, how to correctly do what you want, there are two ways:

  • use a factory, that creates a class, using dependencies that you provided
  • use a dependency injection container, Auryn

To learn how you use a DI container, you will just have to consult the documentation. But I will explain the basics of factory, which is more of a DIY approach

A factory is an object, that is responsible for initializing other class. For example, you have a large set of classes, which require PDO as a dependency.

class Factory 
{
    private $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }


    public function create($name) {
        return new $name($this->pdo);
    }
}

If you use an instance of this class, it would let you create objects, which have the PDO already passed in as a dependency in a constructor:

$factory = new Factory(PDO($dsn, $user, $pass));
$user = $factory->create('User');
$document = $factory->create('Doc');

And as an added benefit, this setup would let bot the User class instance and the Doc class instance to share the same PDO object.

like image 82
tereško Avatar answered Dec 08 '25 17:12

tereško