Posts Tagged ‘mvc’

MVC in ZF2

16/02/2013

ZF2 file structure

config
  autoload
  application.config.app 

data
  cache

module
  Application
   Module.php 
   config
      module.config.pgp
    src
      Application
        Controller
          IndexController.php
     view
       application
         index
           index.phtml 
        error
        layout 

public
  images
  js
  css
  .htaccess
  index.php 

vendor
  zendframework

application.config.app 

array(
  ‘modules’ =>array( //list of modules you want to use
    ‘Application’
  ) ,
  ‘module_listener_options’ =>array( //modules options as autoloading and paths
    ‘config_glob_paths’ => array(
      ‘config/autoload/{,*.}{global,local}.php’,
    ),
    ‘module_paths’=>array(
      ‘./module’,
      ‘./vendor’,
    )
  );
); 

ZendServiceManager

ServiceManager is a Service Locator where you register services and later retrive them by configuration.

Types of services: explicit services, invokables to instatiate, factory returing object, aliases, unknown services, scoped containers, shared or not.

module/Application/Module.php

namespace Application;

use ZendMvcModuleRouteListener;
use ZendMvcMvcEvent;

class Module
{
  public function getConfig(){
    return include __DIR__ . ‘/config/module.config.php’;
  }

module/Application/config/module.config.php 

return array(
  ‘router’=>array(
    ‘routes’=>array(
      ‘home=>array(
        ‘type’=>’ZendMvcRouterHttpLiteral’, //You can use Segment type
        ‘options’=>array(
          ‘route’=>’/’,
          ‘defaults’=>array(
            ‘controller’=>’ApplicationControllerIndex’,
            ‘action’=>’index’,
          ),
        ),
      ),
    ),
  ),
  ‘controllers’=>array(
    ‘invocables’=>array(
      ‘ApplicationControllerIndex’=>’ApplicationControllerIndexController’
    )
  ),
  ‘view_manaer’=>array(
   ‘display_not_found_reason’=>true,
   ‘display_exceptions’=>true,
    ‘doctype’=>’HTML5’,
    ‘not_found_template’=>’error/404’,
    ‘exception_template’=>’error/index’,
    ‘template_map’=>array(
      ‘layout/layout’=>__DIR__.’/../view/layout/layout.phtml’,
      ‘application/index/index’=>__DIR__.’/../view/application/index/index.phtml’,
      ‘error/404’=>__DIR__.’/../view/error/404.phtml’,
      ‘error/index’=>__DIR__.’/../view/error/index.phtml’,
    ),
    ‘template_stack_path’=>array(
      __DIR__.’/../view’,
    ),
  ),
/* … */
); 

module/Application/src/Application/Controller/IndexController.php

namespace ApplicationController;

use ZendMvcControllerAbstractActionController;
use ZendViewModelViewModel;

class IndexController extends AbstractActionController
{
  public function indexAction(){
    return ViewModel();
  }

The ViewModel will return view/application/index/index.phtml contents.

Source Zend webinar.

Anuncis