我正在使用 JMS Serializer对于 PHP 项目,偶然发现了一个问题。
看代码
<?php
use JMS\Serializer\Annotation as Serializer;
/**
* @Serializer\ExclusionPolicy("all")
*/
class Order
{
/**
* @var int
* @Serializer\Type("integer")
* @Serializer\Expose
*/
private $id;
/**
* @var Product[]
* @Serializer\Type("array<Product>")
* @Serializer\Expose
*/
private $products;
/**
* @var float
* @Serializer\Type("float")
* @Serializer\Expose
*/
private $total;
private $someInternalProperty;
function __construct($products)
{
$this->id = rand(0, 100);
$this->products = $products;
$this->total = rand(100, 1000);
$this->someInternalProperty = 'Flag';
}
}
/**
* @Serializer\ExclusionPolicy("all")
*/
class Product
{
/**
* @var int
* @Serializer\Type("integer")
* @Serializer\Expose
*/
private $id;
/**
* @var string
* @Serializer\Type("string")
* @Serializer\Expose
*/
private $name;
private $price;
private $description;
function __construct($id, $name, $price, $description)
{
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->description = $description;
}
}
$order = new Order([
new Product(
1,
'Banana',
10,
'Yellow'
),
new Product(
2,
'Tomato',
12,
'Red'
)
]);
$serializer = \JMS\Serializer\SerializerBuilder::create()
->setPropertyNamingStrategy(new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()))
->build();
print_r(
$serializer->serialize(
$order,
'json',
\JMS\Serializer\SerializationContext::create()
->setSerializeNull(true)
)
);
这里我展示了我的代码的简化示例。我用它来存储订单更改的历史记录。在更新之前和之后,我将这个序列化模型保存到数据库中。好的。
现在我想用所有属性序列化产品的模型,以便在客户端工作。所以我的第一个想法是使用组。我需要为 $id 和 $name 属性设置“Group({'history', 'edit'})”以及所有其他“Group({'edit'})”。好的,它适用于产品序列化,但它会破坏第一个解决方案。现在我的“订单历史记录”存储了不必要的信息,例如 $price 和 $description。
是否有一些正确的方法来指定产品模型的默认组,如果未隐式指定序列化组(如订单的历史示例),将使用该默认组?或通过某种其他方式使这两种类型的序列化可用,而无需将组移动到 Order 的模型中(因为实际上在这种情况下应该重构的模型不止一个)。
最佳答案
对不起。我发现如果我使用“默认”组,一切正常。
<?php
require_once __DIR__ . '/../../../app/Autoload.php';
use JMS\Serializer\Annotation as Serializer;
/**
* @Serializer\ExclusionPolicy("all")
*/
class Order
{
/**
* @var int
* @Serializer\Type("integer")
* @Serializer\Expose
*/
private $id;
/**
* @var Product[]
* @Serializer\Type("array<Product>")
* @Serializer\Expose
*/
private $products;
/**
* @var float
* @Serializer\Type("float")
* @Serializer\Expose
*/
private $total;
private $someInternalProperty;
function __construct($products)
{
$this->id = rand(0, 100);
$this->products = $products;
$this->total = rand(100, 1000);
$this->someInternalProperty = 'Flag';
}
}
/**
* @Serializer\ExclusionPolicy("all")
*/
class Product
{
/**
* @var int
* @Serializer\Expose
* @Serializer\Type("integer")
* @Serializer\Groups({"Default", "edit"})
*/
private $id;
/**
* @var string
* @Serializer\Expose
* @Serializer\Type("string")
* @Serializer\Groups({"Default", "edit"})
*/
private $name;
/**
* @Serializer\Expose
* @Serializer\Groups({"edit"})
*/
private $price;
/**
* @Serializer\Expose
* @Serializer\Groups({"edit"})
*/
private $description;
private $hiddenProperty;
function __construct($id, $name, $price, $description)
{
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->description = $description;
$this->hiddenProperty = 42;
}
}
$product1 = new Product(
1,
'Banana',
10,
'Yellow'
);
$order = new Order([
$product1,
new Product(
2,
'Tomato',
12,
'Red'
)
]);
$serializer = \JMS\Serializer\SerializerBuilder::create()
->setPropertyNamingStrategy(new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()))
->build();
print_r([
$serializer->serialize(
$order,
'json',
\JMS\Serializer\SerializationContext::create()
->setSerializeNull(true)
->setGroups(['Default'])
),
$serializer->serialize(
$product1,
'json',
\JMS\Serializer\SerializationContext::create()
->setSerializeNull(true)
->setGroups(['edit'])
),
]);
结果如下:
Array
(
[0] => {"id":86,"products":[{"id":1,"name":"Banana"},{"id":2,"name":"Tomato"}],"total":644} // Here I have short model for history
[1] => {"id":1,"name":"Banana","price":10,"description":"Yellow"} // And here I have expanded model for other purpose.
)
我喜欢 JMS 序列化器 :)
关于php - JMS 序列化程序。创建 2 种具有 "one-to-many"关系的模型序列化方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22145198/
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport: