Wednesday, January 23, 2019

php - share method between controllers Laravel 5.2




In several controllers i have to use the same method to show results as table with column sorting functionality:



 public function showSearchResults(Request $req){

$query=Service::where('title', $req->search);

// Columns sorting
if ($req->has('order')){
$order= $req->order=='asc' ? 'asc' : 'desc';
$order_inverse=$req->order=='asc' ? 'desc' : 'asc';

} else {
$order='desc';
$order_inverse='asc';
}

...


$url=$req->url().'?'.http_build_query($req->except('sortby','order','page'));
$results=$query->with('type')->paginate(15)->appends($req->all());



return View::make('services.search_results')
->with('results', $results)
->with('url',$url)
->with('sortby', $sortby)
->with('order', $order)
->with('order_inverse', $order_inverse);

}



What is the best approach to avoid DRY in such case?


Answer



Sharing methods among Controllers with Traits



Step 1: Create a Trait





namespace App\Traits;

trait MyTrait
{
protected function showSearchResults(Request $request)
{
// Stuff
}
}



Step 2: use the Trait in your Controller:




namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Traits\MyTrait; // <-- you'll need this line...


class MyController extends Controller
{
use MyTrait; // <-- ...and also this line.

public function getIndex(Request $request)
{
// Now you can call your function with $this context
$this->showSearchResults($request);
}

}


Now you can use your Trait in any other controller in the same manner.



It is important to note that you don't need to include or require your Trait file anywhere, PSR-4 Autoloading takes care of file inclusion.



You can also use Custom Helper classes as others have mentioned but I would recommend against it if you only intend to share code among controllers. You can see how to create custom helper classes here.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...