您好我正在Symfony 3.1上创建API REST。
我遇到了序列化和对象的问题。
这是它返回给我的错误。
<?php
include_once('config.php');
if(isset($_POST['submit'])){
$username = $_POST['username'];
$pass = $_POST['pass'];
$sql = "select id from login where login_name = '".$username."' and login_password = '".$pass."' ";
$result = $conn->query($sql);
if($result->num_row > 0){
echo "connected";
}
}//EOF SUBMIT
?>
我读过的堆栈溢出链接没有任何结果。
这些是我为了尝试seialize my obtject而加入的文档。
以下是fill $ employees的代码:
A circular reference has been detected (configured limit: 1).
我试过这些东西:
第一次证明
$em = $this->getDoctrine()->getManager();
$dql = " SELECT e FROM BackendBundle:Employees e
INNER JOIN BackendBundle:Companies c
WITH e.idCompany = c.idCompany
WHERE c.idUser = ?1";
$query = $em->createQuery($dql);
$query->setParameter(1,$user);
$employees = $query->getResult();
第二次证据
在这些证据中,我默认在Symfony 3上使用了Serialzer,这是deseabe。为此,我修改了这些文件:
应用程序/配置/ config.yml
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers,$encoders);
$data = $serializer->serialize($employees, 'json');
这里非常重要的是我激活序列化器的最后一行。
应用程序/配置/ servces.yml
framework:
#esi: ~
#translator: { fallbacks: ["%locale%"] }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
engines: ['twig']
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
# http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
handler_id: session.handler.native_file
save_path: "%kernel.root_dir%/../var/sessions/%kernel.environment%"
fragments: ~
http_method_override: true
assets: ~
serializer:
enabled: true
enable_annotations: true
的src /的appbundle /控制器/ DefaultController.php
services:
get_set_method_normalizer:
class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
public: false
tags:
- { name: serializer.normalizer }
还有更多的证据证明你在阅读和它之间没有太大区别。
如果有人知道如何在Symfony 3上序列化一个对象,请在整个早上尝试使用同样的错误。
<?php
$serializer = $this->get('serializer');
$json = $serializer->serialize($employees,'json');
答案 0 :(得分:1)
您的问题是,序列化员工正在序列化他们的公司,这又是对Employees的引用,这是一个完美的循环引用。
你可以在Symfony的Serializer中处理这些循环引用,例如通过捕获CircularReferenceException或在setCircularReferenceHandler中使用自定义callable,并仅序列化未引用回原始实体的属性。
有关详细说明,请参阅Symfony's documentation。
答案 1 :(得分:0)
$normalizers->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
在创建ObjectNormalizer()的实例后添加此兄弟。 它对我来说很完美!