简体   繁体   中英

@include equivalent for controllers in Laravel

I have various controller functions where I have a large chunk of code (for an API call) which repeats in other functions a lot of time. Is there a @include equivalent to just copy/paste the codes in my controller. This will be much easier to read and follow through.

In my controller, something like this

    public function store () 
    {
       if ($company->name = 'XYX')
       {
           @include('xyzcontrollercode') 
       }

       if ($company->name = 'DEF')
       {
           @include('defcontrollercode') 
       }
   }

The includes - 'xyzcontrollercode' will have a large chunk of logic which will implement once the 'if' condition matches.

Any way to achieve this kind of functionality for controllers?

You can create a general controller and inherit from it.

For example:

class GeneralController extends Controller
{
    public function operation(){
        // do some things ...
    }
}

class HomeController extends GeneralController
{
    public function store(){
        // do some things ...

        if ($company->name == 'XYX')
        {
            $this->operation(); 
        }

        // do something ...
    }
}

Or you can use dependency injection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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