As it stands right now there's not a great/easy way to do this in Laravel 5 (possibly by design). The two approaches you can take are
Create a new class in the App
namespace
By default Laravel 5.0 looks for App\
prefixed classes in the app/
folder, so something like this should work
#File: app/Helpers/Myclass.php
<?php
namespace App\Helpers;
class Myclass
{
}
and then create your class with
$object = new App\Helpers\Myclass;
This approach, however, relies on you creating classes in the App\
namespace, and there's some ambiguity around if the App\
namespace is owned by Laravel, or is owned by the developer of the application.
Create your own Namespace and Register as PSR-4
autoloader
A better, but more complicated, approach would be to create classes in your own namespace, and then tell Laravel about this namespace by registering a new PSR autoloader.
First, you'd create the class definition
#File: application-lib/Myclass.php
<?php
namespace Pulsestorm;
class Myclass
{
}
Notice we've created a new folder off the root folder to hold our classes named application-lib
. You could name this folder anything you like, because in the next step, you're going to add a section to your composer.json
file's autoloader section
#File: composer.json
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/",
"Pulsestorm\\": "application-lib/"
}
},
The section we've added is this
"Pulsestorm\\": "application-lib/"
The key to the object (Pulsestorm\
) is your namespace. The value (application-lib
) is the folder where composer should look for class definition files with the specified namespace.
Once you've added this to composer.json
, you'll need to tell Composer to regenerate it's autoload cache files with the dumpautoload
command
$ composer dumpautoload
Generating autoload files
After doing the above, you should be able to instantiate your class with
$object = new Pulsestorm\Myclass;
The "real" right way to do this would be to create a generic composer package for your helper class, and then require
that composer package into your laravel project. That may, however, be more work than you care to take on for a simple library helper.