If you place the class somewhere inside your app directory you will have to give it a correct namespace and Laravel will be able to find it automatically.
example: If you place your UploadHandler.php at app/External/UploadHandler.php you could add this at the top of your UploadHandler.php
namespace App\External;
and then you could use it in a Controller (or Model or whatever) like this:
public function test() {
$uploadHandler = new \App\External\UploadHandler();
}
The other possibility (if you are writing your own extension) is for you to create a ServiceProvider. The ServiceProviders register all the parts of your application at the beginning and you need to reference it in config/app.php . Then you can write a facade class (check out documentation here http://laravel.com/docs/5.0/facades) and also register that in app/config.php
After that you could access your class like this:
UploadHandler::initialize();
Basically it all depends on the location of your UploadHandler.php and the correct namespace setting. :)
thanks @ftiersch
I'm interested to make it as ServiceProviders. Could you elaborate the steps I have to take. Where can I call
UploadHandler::initialize();
is it in controller/model or whatever?
This is what I do so you're relatively flexible here:
Create a directory somewhere. For example in packages/infacq/UploadHandler/src
Add your UploadHandler.php to that directory
Add UploadHandlerServiceProvider.php to that folder with this class
<?php namespace Infacq\UploadHandler; use Illuminate\Support\Facades\App; use Illuminate\Support\ServiceProvider; class UploadHandlerServiceProvider extends ServiceProvider { public function boot() { } public function register() { App::bind('infacq-upload-handler', function() { return new \Infacq\UploadHandler\UploadHandler(); }); } }This registers your services - in this case the UploadHandler(). Make sure that your UploadHandler class has the namespace Infacq\UploadHandler;
Add Facades\UploadHandler.php to your src directory with the following class
<?php namespace Infacq\UploadHandler\Facades; use Illuminate\Support\Facades\Facade; class UploadHandler extends Facade { protected static function getFacadeAccessor() { return 'infacq-upload-handler'; } }Register ServiceProvider and Facade in config/app.php in the 'providers' and 'aliases' arrays (just look how it's done and write the correct namespace / classnames from #3 and #4 :))
Open composer.json and look for "psr-4". Add the following line to the array:
"Infacq\UploadHandler\": "packages/infacq/UploadHandler/src",
This tells PHP where to find your files when you use a certain class. Run the console command composer dump-autoload afterwards.
Now you should be good to go and be able to use UploadHandler::initialize() everywhere inside your app. :)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community