skip to Main Content

It’s been a while since i dealt with PHP but i am doing a project from scratch and trying to create a simple MVC framework to display the work and maybe upgrade it in the future.

What i can’t seem to remember is how to implement 2 or more views together, for example, this is one of the controllers:

class Home extends Controller
{   

    public function index()
    {
        $model = new HomeModel;
        $result = $model->findAll();
        $data = $result;

        // Call the view
        $this->view('home', $data);
    }
}

But i would like to build this Home page with several views like: head, sidebar, table, user… all different views.

I tried creating a renderView function but didn’t do it.

function renderView($viewName, $data) {
    // Your view rendering logic goes here
    // You might include the view file and pass data to it
    ob_start();
    include $viewName . '.php';
    return ob_get_clean();
}

I also checked an old Magento structure but couldn’t understand it ( it’s been 4 years since the last time i tried PHP)

2

Answers


  1. Chosen as BEST ANSWER

    I was playing with this all morning and the best solutions for this case is to include each view within the controller, including the data each view requires


  2. What you are trying to do can be accomplished by passing an array of views into your function (I omitted $data since it wasn’t used) but this is the concept behind the thought:

    function renderViews($viewNames) {
        // Your view rendering logic goes here
        // You might include the view file and pass data to it
        ob_start();
        foreach($viewNames as $viewName){
            include $viewName . '.php';
        }
        return ob_get_clean();
    }
    

    Then just define your views:

    $viewNames = [];
    $viewNames[0] = 'thisFile';
    $viewNames[0] = 'thatFile';
    $viewNames[0] = 'otherFile';
    

    Then just pass the array through your function:

    ->renderViews($viewNames);
    

    Of course this is extremely incomplete .. You’ll want to make sure the array exists in your function and tell your program how to handle empty or invalid arrays etc etc .. Good programming starts with good error handling.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search