0

I have a basic MVC framework set up.
Problem is I have to pass the registry in the view to the Controller in order to call the database which is set in the registry. This does not seem to be the proper way.

Question how can I get the database instance in my model directly?

init.php:

$registry = new registry;

$registry->db = db::getInstance();

basecontroller:

protected $registry;
function __construct($registry) {
    $this->registry = $registry;
}

RegoController class:

Class regoController Extends baseController {

    var $folder = 'rego';

    public function index() 
    {
        $this->registry->template->show($this->folder.'/index');
    }

    public function view(){
        $this->registry->template->show($this->folder.'/view');
    }

    ....

I have access to the db in this regoController as it extends the baseController.

my rego class (where I need the db instance):

class rego  {

    private $registry;
    private function __construct($registry) {
        $this->registry = $registry;
    }

    public static function getAllData($registry,$order){
        $sql = "SELECT * FROM rego_details ORDER BY ".$order." ASC";
        $db =  $registry->db;
        $stmt = $db->prepare($sql);
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results;
    }

As you can see the registry is passed as parameter in the function. This does not seem right.
Should I just extend the regoClass or ...?

tereško
  • 58,060
  • 25
  • 98
  • 150
stomperDev
  • 19
  • 6
  • You have a `RegoClass` which does the stuff it should do and then you use an `RegoRepositoryInterface` with `SQLRegoRepository` implementation to actually communciate with data layer. Then you can use the interface for typehinting which now provides you the abiliaty to change your data layer without affecting your logic. – Code Spirit Jul 03 '20 at 13:57
  • 1
    Don't use registry pattern. It's basically just glorified global state (same as singletons, btw). Instead you should try using dependency injection whenever possible. Also, `var` is not the recommended way to define class attributes since 5.0 was released (15+ years ago) ... you might be learning PHP from veeeeeery outdated books. – tereško Jul 03 '20 at 18:14
  • @tereško: haha, you are right. I developed years ago with PHP and moved to another technologies. Now, I am trying to improve on an old project of mine. Will have to start setting up MVC from scratch again I am afraid. Thanks for the feedback. – stomperDev Jul 04 '20 at 16:41
  • In that case you should look up "DI container" libraries and also start using namespaces. – tereško Jul 04 '20 at 19:37

0 Answers0