一个库是否应该调用另一个库,或者在Codeigniter和MVC中它是控制器的任务


Should one library call another or is it a task of controller in Codeigniter and in MVC in general

我必须使用Codeigniter在我的应用程序中做出一些设计决策。

我在控制器中有一个方法,调用一个库来创建PDF。此外,我有一些类,接受一个数字作为参数,并返回字符串(数字口头)。

我想知道在所有类之间传递数据的最佳实践是什么。这是控制器调用所有库(在步骤2和步骤3之间)并将所有准备好的数据提供给将创建PDF的模型的任务吗?或者这是Model自己的任务,通过加载和调用将数字转换为字符串的类来转换提供的原始数据。

在松散耦合、模块化和代码清晰度方面的最佳解决方案是什么?

这是个控制器:

class Payu extends CI_Controller
{
     public function raport($task_id)
     {
           /* (step 1) Load necessarty models */
           $this->load->model('MTasks');
           $this->load->model('mpdfinvoice');
           /* (step 2) task details from DB */
           $task_details = $this->MTasks->getTaskDetails($task_id);
           /* (step 3) create PDF that will be send */
           $this->mpdfinvoice->pdf($task_details);
           /* (step 4) compose an email with attached pdf */
           $this->email->from($this->config->item('noreply_email'));
           $this->email->to($task_details['email']);
           $this->email->attach('invoiceJustCreated.pdf');
           $this->email->subject('opłaciłes to zlecenie');
           $message = 'some message goes here';
           $this->email->message($message);
           $this->email->send();

     }
}

 This is a model that creates PDF file (called by controller)
 class mpdfinvoice extends CI_Model
 {
     public function pdf($task_details)
     {
          /* (step 1) load necesary library and helper */
          $this->load->library(array('fpdf' ));
          $this->load->helper('file');
          /* (step 2) set PDF page configuration*/              
          $this->fpdf->AddPage();
          $this->fpdf->AddFont('arialpl','','arialpl.php');
          $this->fpdf->SetFont('arialpl','',16);
          /* (step 3) show data on PDF page */              
          $this->fpdf->cell('','',$task_details['payment_amount'] ,1);
          /*  I want to have "payment amount" verbally here 
              So Should I load and call the convert class here or
              should I have this data already prepared by the controller
              and only output it ? */
     }
 }

尝试将codeigniter中的控制器视为数据粘合剂。控制器从客户端检索数据,对其进行标准化,并在使用提供的数据时触发适当的操作(重定向、触发库、视图、模型和助手)

在您的示例中,仅使用控制器从模型或用户输入中检索数据。然后将其传递给创建pdf的库。如果pdf创建成功,返回true让控制器知道它成功了。创建一个flashdata成功消息并重定向到一个输出视图的页面:

  1. 用户请求:pdf/download
  2. 控制器Pdf触发下载方法
  3. download触发模型并将数据推送到视图
  4. 视图及其数据将返回到变量
  5. $view变量将被推送到Pdf库
  6. 触发pdf创建
  7. 触发Pdf下载(可选)
  8. 控制器触发重定向到pdf/overview

我建议创建PDF或任何其他文件以及在模型中发生的值之间的所有转换,然后控制器决定从模型中获取哪些数据,以便将其传递给适当的视图,它将知道如何显示它。

控制器不应该被用来直接显示(输出)数据或访问数据库和创建文件。

此外,在任何情况下,模型都不应该用于输出数据。