Question

I need to make a zend 2 web app but with zero knowledge in it.

In all the tutorials I've seen, they all set the file names of the views in the module.config.php, in laravel all you need to set is the route for the view, and you can set in the controller what file to give to that route.

So how do you turn this laravel code to zend 2 code:

$fileDirectory = isMobile() ? "viewfiledirectory/viewfile_mobile" : "viewfiledirectory/viewfile";

return View::make($fileDirectory);

Or if it there is no zend 2 equivalent of that, at least how do I make it like that, every file is hard coded in the template map, how would I be able to make the controller point to that route.

This is a big site, at least 8 pages(only one will be used depending on language set and depending on the user's device as well) per route, I can't just list all the files in the template map of the module.config.php, I want it to be like what I do in laravel.

Was it helpful?

Solution

In Zend Framework 2, you implement a view as a template file, which is a file having .phtml extension ("phtml" stands for PHP+HTML). View templates have such a name because they usually contain HTML code mixed with PHP code snippets used for rendering the web pages. Views typically live inside of the view subdirectory of the module.

In your controller, you use the ViewModel class for passing variables to the view template. The view model can also be used for setting the view template name (see an example below):

<?php
// IndexController.php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController {

  // The "index" action
  public function indexAction() { 

    // Pass two variables to view template
    $viewModel = new ViewModel(array('var1'=>$var1, 'var2'=>$var2));

    // Set view template name 
    $templateName= $this->isMobile() ? "index/viewfile_mobile" : "index/viewfile";
    $viewModel->setTemplate($templateName);

    // Return the view model
    return $viewModel;
  }  
}

If you need a basic explanation of views concept in Zend Framework 2, I would recommend you to read the Using Zend Framework 2 book.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top