Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel constants in class Facades

I have a class called Awesome and have used the ServiceProvider and the Facade to register it to the app. Now I can use it as Awesome::Things().

I want to add constants to this class, so I tried

<?php namespace Helper\Awesome;
class Awesome()
{
    public static $MOVIE = 'I love the Lego Movie!";
}

but when I call Awesome::$MOVIE, I get Access to undeclared static property: Helper\\Aesome\\Facades\\AwesomeFacade::$MOVIE

Can someone help?

like image 336
Kousha Avatar asked Oct 30 '14 19:10

Kousha


1 Answers

The short version is -- you don't really want to do that. Laravel facades aren't mean to be used like normal classes, and if your application uses them that way you'll likely confuse future developers.

Warning out of the way. When you create a "facade" in Laravel, you're actually creating a class alias. When you added Awesome to the alias list in app/config/app.php, at some point code like the following ran

class_alias('Helper\Aesome\Facades\AwesomeFacade','Awesome');

That means whenever you use a global non-namespaced class Awesome, PHP substitutes Helper\Aesome\Facades\AwesomeFacade. If you wanted to add constants, you'd need to add them to this class.

Laravel's able to pass through methods because of the base Facade class implements a __callStatic method that passes on your call to the actual service implementation object. Facades don't pass on static constant access. Additionally, PHP does not (appear to?) have similar magic methods for passing along requests for constants.

If you're curious about the in depth version of this answer, I'm currently writing a series on Laravel's object system, including some in-depth information about the facade implementation.

like image 93
Alan Storm Avatar answered Oct 03 '22 21:10

Alan Storm