Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Reuse : Common Functions - Laravel

Tags:

php

laravel

I'm in the process of Developing APIs for a System whose front end is Android. App calls the API with lat and lon.

I am using Laravel for this and have developed some APIs already. I've also created separate controllers for each and is working correctly.

However 2 (Calculate Distance from Latitude and Longitude and return nearest ones in Ascending order) of the functions are used commonly almost in 3 or 4 Controllers: BusinessController , OfferController, OutletController. I thought it would be better to reuse the code passing parameters correspondingly.

Where should I place the common functions and how should they be invoked? Here is the code for controller.php

<?php namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

abstract class Controller extends BaseController {

    use DispatchesCommands, ValidatesRequests;

}

PS: I'm somewhat new to Laravel.

like image 526
Sharan Mohandas Avatar asked Jul 25 '26 18:07

Sharan Mohandas


1 Answers

In Laravel 5, the App folder is autoloaded. Create a folder or just a file somewhere in it:

<?php

namespace App; // Or App\Yourfolder

class YourSpecialClass
{
   // Your methods
}

And in your controller, just simply use App\YourSpecialClass;

like image 148
Iamzozo Avatar answered Jul 27 '26 20:07

Iamzozo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!