thruster/view-bundle

Thruster ViewBundle Bundle

0.3 2018-05-04 15:25 UTC

This package is auto-updated.

Last update: 2024-09-14 02:53:19 UTC


README

Latest Version Software License Build Status Code Coverage Quality Score Total Downloads

The Thruster ViewBundle Bundle. A simple addition to Symfony to provide ability to define views for simple data mappings similar to Elixir Phoenix Views.

安装

通过 Composer

$ composer require thruster/view-bundle

启用 Bundle

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new Thruster\Bundle\ViewBundle(),
        // ...
    );
}

用法

视图的工作方式与 Symfony 控制器类似,所有视图类 都应该 存放在 Bundle/View/ 文件夹中。 一些实际示例

视图

<?php
// src/AppBundle/View/DefaultView.php

namespace AppBundle\View;

use Thruster\Bundle\ViewsBundle\View\View;
use AppBundle\Entity\User;

class DefaultView extends View
{
    public function welcome($name)
    {
        return [
            'msg' => 'Hello, ' . $name
        ];
    }
    
    public function me(User $user)
    {
    	  return [
    	    'name' => $user->getName(),
    	    'email' => $user->getEmail()
    	  ];
   	 }
   	 
   	 public function friend(User $friend)
   	 {
   	 	  $friend = $this->renderOne([$this, 'me'], $friend);
   	 	  // Also possible just $this->me($friend);
   	 	  
   	 	  unset($friend['email']);
   	 	  
   	 	  $friend['items'] = $this->renderMany('AppBundle:Item:public_view', $friend->getItems());
   	 	  
   	 	  return $friend;
   	 }
   	 
   	 public function friends(array $friends)
   	 {
   	 	  return [
   	 	      'data' => $this->renderMany([$this, 'friend'], $friends)
   	 	  ];
   	 }
}

控制器

<?php

namespace AppBundle\Controller;

use Thruster\Bundle\ViewsBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->jsonView('welcome', 'guest');
    }
    
    public function meAction()
    {
    	return $this->jsonView('AppBundle:Default:me', $this->getUser());
    }
    
    public function friendAction($id)
    {
    	$friend = $this->getRepository('AppBundle:User')->find($id);
    	
    	$data = $this->view('AppBundle\View\DefaultView::friend', $friend);
    	
    	return new JsonReponse($data);
    }
    
    public function friendsAction()
    {
    	$friends = $this->getRepository('AppBundle:User')->findAll();
    	
    	return $this->jsonView('friends', $friends);
    }    
}

测试

$ composer test

贡献

请参阅 CONTRIBUTINGCONDUCT 了解详细信息。

许可证

请参阅 许可证文件 了解更多信息。