如何获取教义实体属性的类型

时间:2014-12-04 11:44:48

标签: php symfony doctrine-orm

实际上我有一个学说实体,我需要动态填充它的属性。

我希望能够做到这样的事情:

$entity = new Entity();
$reflect = new ReflectionClass($entity);
// $fields is an array whihch contain the entity name as the array key and the value as the array value
foreach ($fields as $key => $val)
{
    if (!reflect->hasProperty($key)) {
        var_dump('the entity does not have a such property');
        continue;
    }
    if ( the type of $key is string ) {
          // convert $value to utf8
    } elseif ( the type of $key is integer) {
          // do something else
    } //....etc
}

我该怎么做?

4 个答案:

答案 0 :(得分:11)

找到the solution thanks to @Yoshi。我希望它能帮助

use Doctrine\Common\Annotations\AnnotationReader;

$docReader = new AnnotationReader();
$entity = new Entity();
$reflect = new ReflectionClass($entity);
// $fields is an array whihch contain the entity name as the array key and the value as the array value
foreach ($fields as $key => $val)
{
    if (!reflect->hasProperty($key)) {
        var_dump('the entity does not have a such property');
        continue;
    }
    $docInfos = $docReader->getPropertyAnnotations($reflect->getProperty($key));
    if ( $docInfos[0]->type === 'string' ) {
          // convert $value to utf8
    } elseif ( $docInfos[0]->type === 'integer' ) {
          // do something else
    } //....etc
}

答案 1 :(得分:0)

您可以使用gettype

$entity = new Entity();
$reflect = new ReflectionClass($entity);
// $fields is an array whihch contain the entity name as the array key and the value as the array value
foreach ($fields as $key => $val)
{
    if (!reflect->hasProperty($key)) {
        var_dump('the entity does not have a such property');
        continue;
    }
    if ( gettype($key) === "integer" ) {
          // convert $value to utf8
    } elseif ( gettype($key) === "string") {
          // do something else
    } //....etc
}

答案 2 :(得分:0)

尽管它是旧的,但是当我们需要一个布尔值字段在某些情况下始终设置为true的变通方法时,这篇文章真的很有用-谢谢smarber和yoshi。我们的解决方法是检测布尔字段(在这种情况下为PATCH),并使用相应的setter传播值。 (当然,如果不需要这样做会很好。)

/*
 * @PATCH("/entity/{name}")
 */
public function patchEntityAction(Request $request, $entity)
{
    ...

    $form->handleRequest($request);

    $manager = $this->getDoctrine()->getManager();

    // handle booleans
    $metadata      = $manager->getClassMetadata($bundle_entity);
    $entity_fields = $metadata->getFieldNames();
    foreach ($entity_fields as $field) {
        $type = $metadata->getTypeOfField($field);
        if ($request->request->has("$field") && $type == 'boolean') {
            $setter = 'set' . ucfirst($field);
            $entity->$setter(!!$request->request->get("$field"));
        }
    }

    $manager->persist($entity);
    $manager->flush();

    ...

}

参考:https://api.symfony.com/3.4/Symfony/Component/HttpFoundation/Request.html

答案 3 :(得分:0)

如果您在实体字段中以任意顺序几乎没有不同的注释。
注意:此代码未检测到相关实体(ManyToOne,OneToMany等)。

public void main(FileInfo fileInfo, String put, String get, Message message, boolean isRetry) {
        URLConnection urlconnection = null;
        try {

            File file = new File(fileInfo.filePath);
            URL url = new URL(put);
            urlconnection = url.openConnection();
            urlconnection.setDoOutput(true);
            urlconnection.setDoInput(true);

            if (urlconnection instanceof HttpURLConnection) {
                ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
                ((HttpURLConnection) urlconnection).setFixedLengthStreamingMode((int) fileInfo.fileSize);
                ((HttpURLConnection) urlconnection).setRequestProperty("Content-type", fileInfo.fileMimeType);
                ((HttpURLConnection) urlconnection).setRequestProperty("Content-length", String.valueOf(fileInfo.fileSize));
                ((HttpURLConnection) urlconnection).setRequestProperty("host", XMPP_SERVER);
                ((HttpURLConnection) urlconnection).connect();
            }

            BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

            long transferred = 0;
            int i = 0;
            byte[] buffer = new byte[4096];
            while ((i = bis.read(buffer)) > 0) {

                bos.write(buffer, 0, i);
                transferred += i;
                int progress = (int) ((transferred * 1000.0f) / fileInfo.fileSize);
                if (fileUploadListener != null) {
                    fileUploadListener.onProgressChanged(message, progress);

                }
            }


            bis.close();
            bos.close();

            InputStream inputStream;
            int responseCode = ((HttpURLConnection) urlconnection).getResponseCode();
            if ((responseCode >= 200) && (responseCode <= 202)) {

                inputStream = ((HttpURLConnection) urlconnection).getInputStream();
                int j;
                while ((j = inputStream.read()) > 0) {
                    System.out.println(j);
                }

                if (responseCode == 200) {
                    if (fileUploadListener != null)
                                           fileUploadListener.onAttachmentFileUpload(generateImageUploadResponse(false, get), message, isRetry);
                } else {

                    if (fileUploadListener != null)
                        fileUploadListener.onAttachmentFileUpload(generateImageUploadResponse(true, ""), message, isRetry);
                }
            } else {
                inputStream = ((HttpURLConnection) urlconnection).getErrorStream();

                if (fileUploadListener != null)
                    fileUploadListener.onAttachmentFileUpload(generateImageUploadResponse(true, ""), message, isRetry);
            }
            ((HttpURLConnection) urlconnection).disconnect();

        } catch (Exception e) {
            e.printStackTrace();

            if (fileUploadListener != null)
                fileUploadListener.onAttachmentFileUpload(generateImageUploadResponse(true, ""), message, isRetry);
        }
    }