-1

I am new in learning MVC, I want to use private Model object stored inside View from outside class, like below example:

class Model{
 private $data
}

class View{
private $model
public function __construct($model) {
        $this->model = $model; 

    }
}

// outside
$m = New Model;
$v =  New View($m);
echo $v->m->data; // How to get it

i know setter/getter method, but it can can much more bigger MVC code.please help.

user5005768Himadree
  • 1,375
  • 3
  • 23
  • 61

1 Answers1

1

You would probably want to access the view from within the controller like this:

class Controller
{
    public function __construct($model, $view)
    {
        $this->model = $model;
        $this->view = $view;
    }

    public function show()
    {
        return $this->view->render($this->model->getData());
    }
}

$controller = new Controller();
$controller->show();

You want the controller to receive all of the dependencies that it has ideally in the constructor. That way it doesn't need to search for them. This is inversion of control or DI (dependency injection).

Timothy Fisher
  • 1,001
  • 10
  • 27
  • 1
    To be noted that you use DI (dependency injection) which the op should use too – Mihai Matei Jul 13 '18 at 07:27
  • @Timothy Fisher Thanks. However, if model class contains 10 methods, then do i need to write 10 wrapper function for each corresponding into controller class like in your example `public function show()`. is it correct MVC approach.I am new on MVC.Thank you very much. – user5005768Himadree Jul 13 '18 at 08:23
  • Not necessarily. Usually the model is just a layer that is used to access business logic and the database. You would have a method in your controller for each view you want to load. The model would simply be there to grab data to load into the view. – Timothy Fisher Jul 13 '18 at 17:40