Search code examples
phplaravellaravel-5laravel-facade

Laravel class Auth


Hi can I ask about this in laravel framework

namespace Illuminate\Support\Facades;

/**
 * @see \Illuminate\Auth\AuthManager
 * @see \Illuminate\Contracts\Auth\Factory
 * @see \Illuminate\Contracts\Auth\Guard
 * @see \Illuminate\Contracts\Auth\StatefulGuard
 */
class Auth extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'auth';
    }
}

what does the return 'auth' exactly returning to the caller ? is it text 'auth' or an object ? and what is the reason why they only have one method in that class ? I apologize i am just learning oop.

Thank you in advance.


Solution

  • In this case as you see method getFacadeAccessor it's returning auth string.

    Facades are just "shortcuts" to use other classes but in fact you shouldn't use them everywhere if you don't need to.

    In Laravel you can bind objects/classes into Application. So you can write for example:

    $app->bind('something', function() {
       return new SomeObject();
    });
    

    Let's assume there is method doSomething in SomeObject class.

    Now you can use this method using:

    $app['something']->doSomething();
    

    But you can also create facade:

    class GreatClass extends Facade
    {
        /**
         * Get the registered name of the component.
         *
         * @return string
         */
        protected static function getFacadeAccessor()
        {
            return 'something';
        }
    }
    

    and now anywhere in your application you could use:

    GreatClass::doSomething();
    

    Answering your question this getFacadeAccessor is returning only the name the name of object that is used when bound to Application. To know how it's used you can look into the source of:

    /vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php

    The method you should look first is getFacadeRoot - because this method is returning the requested object.