繁体   English   中英

如何在Laravel5的另一个控制器中使用一个控制器作为服务

[英]How to use a controller inside another controller in Laravel5 as service

我有一个发票控制器,它看起来像这样

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Event;
use App\Employee;
use App\Invoice;
use Mail;
use View;

class ViewinvoiceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex($order_id)
    {
       $id=$order_id;

        $invoicedata=Invoice::where('Id',$id)->get();


    $html22 =  View('viewinvoice')->with(array('invoicedata'=>$invoicedata ))->render();

     require_once(app_path().'/libs/html2pdf/html2pdf.class.php');


      $html2pdf = new \HTML2PDF('P','A4','en',true,'UTF-8',array(0, 0, 0, 0));

      // $html2pdf->pdf->SetDisplayMode('fullpage');

      $html2pdf->WriteHTML($html22);

     $html2pdf->Output('Invoice.pdf');


    }

}

我想在其他像这样的控制器中使用此控制器

class CollectionController extends Controller
    {

        public function __construct(){

    $this->middleware('role:collector'); // replace 'collector' with whatever role you need.
      }
       public function getInvoice($order_id){
       //Here I have to write the logic of getting the invoice from the invoiceController 
}

}

我搜索了一下,发现一种方法是编写获取发票的服务,

我可以将其作为服务的普通类,但是我不知道laravel 5中的正确方法是什么

任何建议

如果您认为某些功能需要在多个Controller或多个位置中触发,则可以根据设计标准在另一个Controller中使用Controller,这就是Jobs

在此处阅读有关Laravel Jobs的更多信息。 作业可以同步或异步运行,这取决于您的应用程序。

您可以将此特征放置在App\\Services并使用ViewinvoiceTrait.php名称保存文件

<?php
namespace App\Services;

use App\Invoice;
use View;

trait ViewinvoiceTrait {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex($order_id) {
        $id = $order_id;

        $invoicedata = Invoice::where('Id', $id)->get();


        $html22 = View('viewinvoice')->with(array('invoicedata' => $invoicedata))->render();

        require_once(app_path() . '/libs/html2pdf/html2pdf.class.php');


        $html2pdf = new \HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(0, 0, 0, 0));

        // $html2pdf->pdf->SetDisplayMode('fullpage');

        $html2pdf->WriteHTML($html22);

        return $html2pdf->Output('Invoice.pdf');
    }

}

并像在控制器中那样使用它

use App\Services\ViewinvoiceTrait;

class CollectionController extends Controller
    {

     use ViewinvoiceTrait;

     public function __construct(){
        $this->middleware('role:collector'); // replace 'collector' with whatever role you need.
     }

     public function getInvoice($order_id){
          $data = $this->getIndex($order_id);
     }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM