How to pass the PDO to other objects in MVC OOP application

2

I'm developing a small framework for learning purposes, and one of the ways I found to pass the PDO object to be used in controllers / models was to use the following approach:

  

The constructor method of the parent Controller receives a PDO object, and this is   inherited by all "Child Controllers", who also inherit the   "loadModel" method, which returns an object already with the PDO that was passed as argument in the parent Controller.

.

DOUBT : Is this a good approach? otherwise, why? what are the advantages and disadvantages? and what would be a good alternative?

COMPLEMENT: I did some research and it looks like the appropriate pattern for this would be Factory, but I do not know what its implementation would look like in my code so it's available to all controllers, even those do not use a connection to the database.

If possible, sample code based on my code

connection.php

<?php

$options = array(
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::MYSQL_ATTR_FOUND_ROWS => true
    );

$connection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='. DB_CHARSET, DB_USER, DB_PASS, $options);

return $connection;

index.php

  

// has some validations and handling of route URLs (controller -   action) and sets the controller in the $ controller variable, and it receives,   through the constructor, the PDO object to be used within the method.

$obj = new $controller($connection);

controller.php (parent controller)

class Controller {

private $connection;

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

public function loadModel ($model) {
    return new $model($this->connection);
}

UserController.php (example controller)

class UserController extends Controller {

    function registration () {

            $useCRUD = $this->loadModel('userCRUD');

            $info = array('name' => 'Joao', 'age' => 25);

            $userCRUD->create($info);
        }

}

userCRUD.php It receives by the constructor the PDO object and does the CRUD interactions with the database.

    
asked by anonymous 19.10.2018 / 04:02

1 answer

1

How to create controllers with their dependencies

In MVC, a controller is instantiated and running automatically according to the route, to create the controllers I see two solutions: the use of factorys or the use of an IOC container. I will address the first solution.

Creating the objects

As I mentioned, factorys can be used to solve the problem, so they will be passed to a class that will run the controllers, because this class will get the controller checking if there is any factory for its creation.

The implementation of the factory would look something like this:

class UserControllerFactory
{
    // OBS: O método __invoke faz uma classe poder ser executada como uma função do PHP.
    public function __invoke()
    {    
         $userCrud = new UserCrud(PDOFactory::create());
         return new UserController($userCrud);
    }
}

Now the class that will run your controllers would look like this:

class ControllerInitializer
{

    private $factorys;

    public function __construct(
        array $factorys
    ){

        $this->factorys = $factorys;

    }

    public function init()
    {
        // $controllerName é onde estaria o nome do controller com base na rota.
        // $action é a action que será executada e que foi extraída da rota.

        if(isset($this->factorys[$controllerName])){
             $factory    = $this->factorys[$controllerName];
             $controller = $factory();
             $controller->$action();
        }else{
            // Caso o controller não seja encontrado você pode disparar uma exception para indicar um erro 404...
            // ou executar um controller padrão para página não encontrada.
        }

    }

}
    
20.10.2018 / 18:29