3

I want to include an external PHP file into my service provider, that file is in a different folder. Like my file is in folder1 and this folder is at same level as laravel is.

   C:\xampp\htdocs\registration\php\file.php //this is file
   C:\xampp\htdocs\_problem_sharing\app\AppServiceProvider

This is how I am trying right now

include_once "/../../../registration/php/user_info.php";
StealthTrails
  • 2,281
  • 8
  • 43
  • 67
  • Going two level back: `include_once "../../registration/php/user_info.php";` should be enought. Also, don't prepend the relative path with `/`. – Bogdan Dec 29 '15 at 21:13
  • its still looking the file under Providers directory @Bogdan – StealthTrails Dec 29 '15 at 22:03
  • What's the error that you're getting? – Bogdan Dec 29 '15 at 22:28
  • `FatalErrorException in AppServiceProvider.php line 14: Class 'App\Providers\UserInfo' not found` where UserInfo is my class name in the file that I am trying to include. @Bogdan this happens when I try to make class object `$this->userInfo = new UserInfo();` – StealthTrails Dec 29 '15 at 22:31
  • Since the provideo is in it's own namespace `App\Providers`, you should either put this at the top of your provideor class file `use UserInfo`, or whenever using the class inside the code prepend it with a backslash which puts it in the global namespace (for ex: `new \UserInfo()`). If the problem persists, please post the contents of your provider. – Bogdan Dec 29 '15 at 22:39
  • @Bogdan please refer to this [gist](https://gist.github.com/waqasraza123/3e16e23904e31d419722) – StealthTrails Dec 29 '15 at 22:50

1 Answers1

1

Is really simple to do this. Because everything in Laravel 5 is autoloaded using PSR-4, within the app/ directory. So, for example, if this file you want to include have a class.

You need to create the directory, e. g.: app/CustomStuff/CustomDirectory/ Into this directory, create the file: app/CustomStuff/CustomDirectory/SomeClass.php

Into the SomeClass.php file, you just need:

<?php 
namespace App\CustomStuff\CustomDirectory;

class Someclass {}

Now, you can access this class using the namespace within your classes:

use App\CustomStuff\CustomDirectory\SomeClass;
Vitor Villar
  • 1,855
  • 18
  • 35
  • 1
    i do not want to copy that file into laravel's directory – StealthTrails Dec 29 '15 at 20:58
  • I think that's not possible, you have to copy the file into Laravel – Vitor Villar Dec 29 '15 at 21:02
  • 1
    @VitorLuis Of course it's possible, you can load any file from anywhere in the filesystem as long as you have permission to read it, you just need to use `include` or `require`, or if you want to you autoload it using Composer, you need [to configure](http://stackoverflow.com/questions/28253154/how-to-i-use-composer-to-autoload-classes-from-outside-the-vendor) `composer.json`. – Bogdan Dec 29 '15 at 21:09
  • You could symlink the file into laravel, this will ensure the file is tracked by git as well. – user2094178 Dec 30 '15 at 01:23