在Laravel 5中的多个函数中使用相同的代码

时间:2015-04-07 13:16:43

标签: php function laravel

我有这个代码,我想在我的Controller的每个功能中使用前10-15行,如何在没有复制粘贴的情况下进行操作?

public function fac(){
    $homebanking=Auth::user();
    $cliente=$homebanking->cliente();
    $nome=$cliente->nome;

    $id=$cliente->id;
    //dd($cliente->contas()->get());
    $i=0;
    $contas=$cliente->contas();
    foreach ($cliente->contas()->get() as $conta){
        $idcontas[$i]=($conta->id);
        $i=$i+1;
    }

    $homebanking=Auth::user();
    $cliente=$homebanking->cliente();
    $nome=$cliente->nome;

    return view('hbpages.fac',compact('nome'));
}

public function presta(){
    $homebanking=Auth::user();
    $cliente=$homebanking->cliente();
    $nome=$cliente->nome;

    $id=$cliente->id;
    //dd($cliente->contas()->get());
    $i=0;
    $contas=$cliente->contas();
    foreach ($cliente->contas()->get() as $conta){
        $idcontas[$i]=($conta->id);
        $i=$i+1;
    }

    $homebanking=Auth::user();
    $cliente=$homebanking->cliente();
    $nome=$cliente->nome;

    return view('hbpages.presta',compact('nome'));
}

1 个答案:

答案 0 :(得分:0)

我不是完全确定你在这里做了什么,但你可以随时将大部分代码添加为新功能,并使用前两个$this->进行调用,如果你正在寻找快速抽象:

public function fac()
{
    $nome = $this->allTheStuff();

    return view('hbpages.fac',compact('nome'));
}

public function allTheStuff()
{
    $homebanking=Auth::user();
    $cliente=$homebanking->cliente();
    $nome=$cliente->nome;

    $id=$cliente->id;

    $i=0;
    $contas=$cliente->contas();
    foreach ($cliente->contas()->get() as $conta){
        $idcontas[$i]=($conta->id);
        $i=$i+1;
    }
    $homebanking=Auth::user();
    $cliente=$homebanking->cliente();

    return $cliente->nome;
}