How can I create a method that builds different objects based on a variable?

2

I have several models:

class ModeloA {
    public function __construct(){} 
}

class ModeloB {
    public function __construct($param1, $param2){} 
}

And a controller to which I inject the models:

$controller = new Controller($modelInstance);

I need to determine which of the models I'm going to pass to the controller and for that I need a function that is able to build a ModelA or ModelB object depending on a variable, that variable would be the name of the controller ($ controllerName):

public function modelBuilder($controllerName) {
   // Construir objeto ModeloA o ModeloB en funcion de $controllerName
}

  // Para luego poder hacer
 $controller = new $controllerName($modelInstance);
    
asked by Serux 15.04.2018 в 14:48
source

1 answer

1

I do not know if it will work for you like this:

class modelo_X
{

    public $mensaje;

    public function __construct()
    {
        $this->mensaje = 'Modelo: modelo_X';
    }
}


class modelo_Y
{
    public $mensaje;

    public function __construct()
    {
        $this->mensaje = 'Modelo: modelo_Y';
    }
}

class controller
{
    public $modelo;

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

}

class controlador_X extends controller
{

    public function __construct($modelo)
    {
        parent::__construct($modelo);
        echo $this->modelo->mensaje;
    }
}

class controlador_Y extends controller
{

    public function __construct($modelo)
    {
        parent::__construct($modelo);
        echo $this->modelo->mensaje;
    }
}

function modelBuilder($nombreControlador)
{

    $dic = [
        'controlador_X' => 'modelo_X',
        'controlador_Y' => 'modelo_Y',

    ];

    return new $dic[$nombreControlador];
}

$nombreControlador = 'controlador_X';
$modelo = modelBuilder($nombreControlador);
$controller = new $nombreControlador($modelo);

echo '<br>';

$nombreControlador = 'controlador_Y';
$modelo = modelBuilder($nombreControlador);
$controller = new $nombreControlador($modelo);
echo '<br>';
  

Model: model_X

     

Model: model_Y

Simply, given a controller name, it instantiates the model that has been assigned to it in the associative array that functions as a dictionary.

    
answered by 16.04.2018 / 13:28
source