aequasi/view-model-bundle

用于添加ViewModel功能的Symfony2工具包

4.0.2 2016-11-07 19:42 UTC

This package is auto-updated.

Last update: 2024-09-05 18:20:58 UTC


README

用于添加ViewModel功能的Symfony2工具包

此工具包不再接受任何支持。

要求

需要

安装

在项目根目录下

composer require aequasi/view-model-bundle ~4.0.0

在你的 app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Aequasi\Bundle\ViewModelBundle\AequasiViewModelBundle(),
    );
    // ...
}

用法

要创建一个ViewModel,创建一个新的类,实现ViewModelInterface。该命名空间中还有一些其他类,可以帮助你轻松创建自己的ViewModel。强烈建议扩展AbstractViewModel。该命名空间中还有两个类扩展了抽象类

  • HtmlViewModel - 设置内容类型为 text/html,不执行任何复杂的视图构建操作
  • JsonViewModel - 设置内容类型为 application/json,不执行任何复杂的视图构建操作

示例

<?php

namespace Acme\DemoBundle\View\Index;

use Aequasi\Bundle\ViewModelBundle\View\Model\HtmlViewModel;

class IndexViewModel extends HtmlViewModel
{
  protected $template = 'AcmeDemoBundle:Index:index.html.twig';

  public function buildView($data)
  {
    // Do some stuff with data, and then return what you want in the view
    return $data; // Does this by default in the ViewModel
  }
}

你不必遵循相同的命名空间结构,但这可以使结构更清晰。此ViewModel将是IndexController的indexAction的ViewModel。

使用ViewModel

在你的操作中使用@ViewModel 注解,或者你可以使用 @ViewModelFactory 注解

namespace Acme\DemoBundle\Controller;

use Aequasi\Bundle\ViewModelBundle\Annotation\ViewModel;
use Aequasi\Bundle\ViewModelBundle\Service\ViewModelService;
use Aequasi\Bundle\ViewModelBundle\Controller\ViewModelControllerInterface;

class IndexController
{

  /**
   * @var ViewModelService
   */
  private $view;

  /**
   * @ViewModel("Acme\DemoBundle\View\Model\Index\IndexViewModel")
   * OR
   * @ViewModel("@some.service.name")
   * @ViewModelFactory("@service.id", {"argumentOne", "argumentTwo"}) // You can also use a class name. The arguments are for you to decide what view model to use
   */ 
  public function indexAction()
  {
    $this->view = $this->container->get('aequasi.view_model.service.view');
    
    $this->getView()->add('someParameter', 'someValue');
    return $this->getView()->render(/*$templatName, $response*/);
    
    // You can also not return anything and it will create the response for you
    // It will also let you return an array that gets set as your view parameters
    return array('someParameter', 'someValue');
  }
  
  public function setView(ViewModelService $service)
  {
    $this->view = $service;
  }
  
  public function getView()
  {
    return $this->view;
  }
}
ViewModelFactory必须实现ViewModelFactoryInterface,并且create方法必须返回一个ViewModelInterface