如何检查symfony2中是否已存在某个文件?

时间:2015-08-13 07:26:30

标签: php symfony

我正在研究symfony2,目前我想检查文件是否存在。我的场景看起来像这样,我有两个文件excel文件和docx文件。如果一个人的交易有excel个文件,则docx文件自动不适用于她或他。反之亦然。我怎么能在symfony2中做到这一点?网上有很多,但我不知道如何在我的情况下这样做,非常感谢:)。

更新 控制器:

public function documentType ($doc_type) {
   $em = $this->getDoctrine()->getEntityManager();
   $result = $em->getRepository('SupplierBundle:SupplierTransactionDetails')->findDocumentType('xlsx');
   $result1 = $em->getRepository('SupplierBundle:SupplierTransactionDetails')->findDocumentType('docx');
   // statement that will know if the file exists for that certain user if so the other document type will be not applicable for that user. Example: that user have docx file already then the xlsx will be N/A and vice versa

} 

存储库:

public function findDocumentType ($doc_type) {
   $em = $this->getEntityManager();
   $query = $em->createQuery(
       'SELECT a, b, c FROM SupplierBundle:SupplierTransaction Details a
        JOIN a.supplierTransaction b
        JOIN b.supplierDocType c
        WHERE c.docType LIKE :doc_type'
   )->setParameter('doc_type', $doc_type);

   return $query->getResult();
}

2 个答案:

答案 0 :(得分:3)

你可以使用普通的PHP。例如:

$xls = 'sheet.xlsx';
$doc = 'document.docx';

if (file_exists($xls)) {
    // User has an XLSX file
    echo 'Download your sheet <a href="sheet.xlsx">here</a>.';
} elseif (file_exists($doc)) {
    // User has a DOCX file
    echo 'Download your document <a href="document.docx">here</a>.';
}

答案 1 :(得分:2)

如果您想以Symfony2的方式进行,可以使用Filesystem类,它具有exists()功能。在控制器中,实例在服务容器中自动可用:

$em = $this->getDoctrine()->getManager();
$xlsx = $em->getRepository('SupplierBundle:SupplierTransactionDetail')->findDocumentType‌('xlsx');
$docx = $em->getRepository('SupplierBundle:SupplierTransactionDetail')->findDocumnetType‌('docx');

return [
        'xlsx' => $xlsx instanceof SupplierTransactionDetail && $this->get('filesystem')->exists($xlsx->getFile()) ? $xlsx->getFile() : null,
        'docx' => $docx instanceof SupplierTransactionDetail && $this->get('filesystem')->exists($docx->getFile()) ? $docx->getFile() : null,
    ];

在你的树枝模板中:

{% if xlsx is not empty %}
    {{ xlsx }}
{% endif %}

{% if docx is not empty %}
    {{ docx }}
{% endif %}