Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a file in laravel controller?

I am creating a project with some additional functionality provided in form of a .php file API which contains some functions and some classes(out of which some class names are conflicting with Laravel built in class names) so, my question how should I include this file in my Laravel Controller to call functions in the file which using the classes of the file without referring Laravel classes and with less or no modification in .php API file?

Note* I am using Laravel-5.1

like image 849
Akshay Khale Avatar asked Oct 24 '25 14:10

Akshay Khale


1 Answers

If you have a custom file containing some classes/functions that need to be loaded for every request, you need to make sure it's added to the autoloader.

In your composer.json add the following in your autoload section:

"autoload": {
  "files": [
    "path/to/your/File.php"
  ]
}

This will make sure the file is loaded. Now what you need is a way to use those classes without conflicting with existing Laravel classes.

First, make sure you have a namespace declaration at the top of your included file - say namespace Your\Namespace. In order to avoid conflicts, you need to explicitly tell PHP which class you mean when you reference it in the code. You mentioned your file contains a Response class that also exists in Laravel. In order to be able to use both, you need to alias one of them:

use Illuminate\Http\Response as LaravelResponse;
use Your\Namespace\Response;

Now in your code you can refer to Laravel's Response class as LaravelResponse, and to your response by simply Response.

Location of the file is irrelevant, as long as it's in a folder accessible to Laravel and its patch is added to composer.json.

Keep in mind that storing multiple classes per file is discouraged as a bad practice. I strongly suggest that you split your fine into separate file per class + one additional file with global functions.

like image 168
jedrzej.kurylo Avatar answered Oct 27 '25 02:10

jedrzej.kurylo



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!