Wednesday 23 January 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...