【问题标题】:MVC Model: Where to place variable in my code that deals with databaseMVC 模型:在处理数据库的代码中放置变量的位置
【发布时间】:2015-12-11 15:53:35
【问题描述】:

我试图在我的代码中找到正确的位置来放置数据库读取代码,以及将数据库中读取的数据传递给接收对象的正确方法。下面是我的代码。注意$metaData 变量。那就是有问题的变量(它从 DB 接收数据,然后将其传递给接收对象)。

class Controller
{
    // generages PDF with data placed in specific areas of PDF
    public function generateOutline($outputData)
    {
        // PDF library engine
        $pdfEngine = new PdfEngine();

        // Doctrine ORM Database Connector
        $em = DoctrineConnector::getEntityManager();

        // object containing metadata describing where to place data for $outputData
        $metaData = $em->getRepository(Metadata::class)->findAll();

        //method that places $outputData as described by $metaData
        $pdfEngine->generateOutline($metaData, $outputData);
    }
}

// part of View, because PDF is displayed to us
class PdfEngine
{

    public function generateOutline(Metadata $metaData, array $data)
    {
        $this->placeTextOnPdf($metaData, $data);
    }
}

问题...

我无法确定在哪里放置 $metaData 构造。 你看。 .. $metaData 是从数据库中读取的一个变量(在我的代码中)

我可以将数据库放入视图中吗?并不真地。视图不应该关心数据库的细节。

我可以将数据库放入控制器吗?不是真的应该是“瘦控制器,胖模型”

我是否可以将其放入模型中?模型在哪里呢,我在哪里放我的代码?

【问题讨论】:

  • $metaData 应该保持在原来的位置。我看不出这是个问题。
  • 也许.....在那之前$metaData 在视图中 (PdfEngine)。我把它移到外面,然后把它传递给 View。我担心控制器不能像我在这里那样直接从数据库中读取。数据库读取必须在某个模型中完成。
  • 也许这个问题更适合 codereview.stackexchange.com
  • 据我所知,您并没有直接从数据库中读取。您正在使用 Doctrine,总体而言,它确实包装了对数据库的调用。然而,你没有错。它放在那里不太好,你可以把它移到模型上。
  • 什么是模型,它在我的代码中的什么位置?

标签: php model-view-controller model database-connection


【解决方案1】:

我最终做了这样的事情..

class Controller
{
    public function generateOutline($input)
    {
        $data = $this->inputFilter->getOutlineRequestData($input);

        //leaving around some existing processing code
        //may have to find a better place for it later
        $processor = (new OutlineProcessorFactory())->getProcessor($input['line']);
        $output = $processor->processInput($data);

        //encapsulated my code in a "service" layer
        $this->pdfService->renderPdf($output);
    }
}

class PdfService()
{
     function renderPdf($output);
     {    
        $pdfEngine = new PdfEngine();
        $em = DoctrineConnector::getEntityManager();
        $metaData = $em->getRepository(Metadata::class)->findAll();
        $pdfEngine->generateOutline($metaData, $outputData);
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2014-06-20
    • 2014-02-24
    • 1970-01-01
    相关资源
    最近更新 更多