Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add external class in Laravel 5

There is a class in app/Libraries/TestClass.php with following content:

class TestClass {
      public function getInfo() {
           return 'test';
      }
}

Now, I would like to call getInfo() method from this external class in my Controller.

How can I do such thing?

like image 380
Hamed Kamrava Avatar asked Mar 02 '15 18:03

Hamed Kamrava


1 Answers

First you should make sure that this class is in the right namespace. The correct namespace here would be:

namespace App\Libraries;

class TestClass {

Then you can just use it like any other class:

$test = new TestClass();
echo $test->getInfo();

Don't forget the import at the top of the class you want to use it in:

use App\Libraries\TestClass;

In case you don't have control over the namespace or don't want to change it, add an entry to classmap in your composer.json:

"autoload": {
    "classmap": [
        "app/Libraries"
    ]
}

Then run composer dump-autoload. After that you'll be able to use it the same way as above except with a different (or no) namespace.

like image 197
lukasgeiter Avatar answered Nov 14 '22 22:11

lukasgeiter