Reputation: 21
I want to write my own classes in Laravel that I can use in my controllers. I'm trying this with facades.
This is my folder structure:
app
classes
facades
serviceproviders
I autoloaded them in composer.json
"app/facades",
"app/classes",
"app/serviceproviders"
My class (app/classes/DateRange.php)
<?php namespace myMethods;
class DateRange {
public function doSomething()
{
echo 'Doing something!';
}
}
My facade (app/facades/DateRangeFacade.php)
<?php namespace myMethods\Facades;
use Illuminate\Support\Facades\Facade;
class DateRangeFacade extends Facade {
protected static function getFacadeAccessor() { return 'DateRange'; }
}
My Serviceprovider (app/serviceproviders/DateRangeServiceProvider.php)
<?php namespace myMethods;
use Illuminate\Support\ServiceProvider;
class DateRangeServiceProvider extends ServiceProvider {
public function register()
{
$this->app['DateRange'] = $this->app->share(function($app)
{
return new DateRange;
});
$this->app->booting(function()
{
$loader = AliasLoader::getInstance();
$loader->alias('DateRange', 'myMethods\Facades\DateRangeFacade');
});
}
}
Also added 'myMethods\DateRangeServiceProvider' to providers array in app.php
Opening the site, it displays 'Class 'myMethods\AliasLoader' not found'. Found a solution on stackoverflow to put a '\' before AliasLoader:: but that doesn't help.
What am I doing wrong ? Thanks in advance.
Upvotes: 1
Views: 1898
Reputation: 87739
You have to use or namespace all the things:
<?php namespace myMethods;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class DateRangeServiceProvider extends ServiceProvider {
public function register()
{
$this->app['DateRange'] = $this->app->share(function($app)
{
return new DateRange;
});
$this->app->booting(function()
{
$loader = AliasLoader::getInstance();
$loader->alias('DateRange', 'myMethods\Facades\DateRangeFacade');
});
}
}
This is required (and you cannot simply use \AliasLoader) because AliasLoader is not an Alias in Laravel, it's a class, so you need to tell PHP exactly where it is.
Upvotes: 2