Symfony2 Doctrine是否支持“私有/隐藏”实体字段?

时间:2013-12-05 16:35:43

标签: php mongodb symfony doctrine-orm doctrine

我正在寻找一个功能,在 自动神奇地从文档中删除字段

让我们说,我有一个User Document,可以使用RESTful api匿名查询。当然,我想删除危险字段,例如passwordsecret等。

文件:

// src/Acme/StoreBundle/Document/User.php
namespace Acme\StoreBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class Product
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\String
     */
    protected $name;

    /**
     * @MongoDB\Float
     * @Hidden            // This field is "private"
     */
    protected $password;
}

控制器:

// src/Acme/StoreBundle/Controller/UserController.php
namespace Acme\StoreBundle\Controller;

class UserController extends RestController
{
    public function putUserAction(Request $request)
    {
        ...
        // Get the user by the username
        $user = $userManager->findUserByUsername('joe_schmoe');

        $user->removeHiddenFields(); // Just an example implementation

        ...
        // Returns the user object as JSON (I know how to do that, JFYI)
    }
}

1 个答案:

答案 0 :(得分:5)

查看jms serializer及其exclusion strategies

/**
 * The following annotations tells the serializer to skip all properties which
 * have not marked with @Expose.
 *
 * @ExclusionPolicy("all")
 */
class MyObject
{
    private $foo;
    private $bar;

    /**
     * @Expose
     */
    private $name;
}