I'm having a little problem with creating a facade model class with Laravel. I have followed http://laravel.com/docs/facades but I guess I'm missing something.
I have created a folder in app/models
called foo
. In that folder I have two files.
First file (Foo.php):
<?php
namespace Mynamespace;
class Foo {
public function method() {
}
}
?>
Second file (FooFacade.php):
<?php
use Illuminate\Support\Facades\Facade;
class Foo extends Facade {
protected static function getFacadeAccessor() { return 'foo'; }
}
?>
Then I added Foo => 'Mynamespace\Foo'
to the aliases
array in app/config/app.php
and ran composer update
and composer dump-autoload
.
Now when I try to run Foo::method()
I get Non-static method Mynamespace\Foo::method() should not be called statically
. What am I doing wrong?
Create a folder called facades
in your app
folder (app/facades
).
Add the facade folder to your composer autoload.
"autoload": {
"classmap": [
...
"app/facades"
]
},
Create a Facade file in that folder (FooFacade.php
) and add this content:
<?php
use Illuminate\Support\Facades\Facade;
class MyClass extends Facade {
protected static function getFacadeAccessor() { return 'MyClassAlias'; } // most likely you want MyClass here
}
Create a model in app/models
(MyClass.php
).
<?php
namespace MyNamespace;
use Eloquent; // if you're extending Eloquent
class MyClass extends Eloquent {
...
}
Create a new service provider (you can create a folder in app called serviceproviders
and add it to composer autoload) (app/models/MyClassServiceProvider.php
).
<?php
use Illuminate\Support\ServiceProvider;
class MyClassServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register() {
$this->app->bind('MyClassAlias', function(){
return new MyNamespace\MyClass;
});
}
}
Here you can add new binding if you want another facade (don't forget to create a facade file if so).
Add the service provider to the providers
array in config/app.php
.
'providers' => array(
...
'MyServiceProvider'
)
Run composer dump
so we can access our new classes.
You can now access MyClassAlias::method()
as a facade.