php - How to create aliases in laravel? -


i want create aliases in laravel auth can use in view

auth::user().

for example, want return data setting table , want use

setting::method()->value. in view , use setting in controllers.

what should create facades or service providers? provide me procedures. tried using service providers confused how call database there.

this long answer, using laravel 5.4.

  1. you need service class (in case, it's concrete class behind facade). made inside app/services folder:

namespace app\services;  use illuminate\database\databasemanager;  class setting {     protected $db;      public function __construct(databasemanager $db)     {         $this->db = $db;     }      public function method()     {         return;     } } 

as see, inject database inside concrete class. magic of laravel ioc. automatically resolve dependency concrete class.

  1. next, create facade. made inside app/facades folder:

namespace app\facades;  use illuminate\support\facades\facade;  class setting extends facade {     /**      * registered name of component.      *      * @return string      */     protected static function getfacadeaccessor()     {         return 'setting';     } } 

notice setting string returned getfacadeaccessor. need register service name later container (ioc). magic behind facade is, it's automatically call (proxy) static method instance method of concrete class, in case can call:

service::method() 
  1. register service container. inside appserviceprovider

    namespace app\providers;

    use app\services\setting; use illuminate\support\serviceprovider;

    class appserviceprovider extends serviceprovider { // ...

    /**  * register application services.  *  * @return void  */ public function register() {     // ...      $this->app->singleton(setting::class);     $this->app->alias(setting::class, 'setting'); } 

    }


in service provider, declare setting service singleton service. means, can use setting service in place without re-initialize class, in words using same instance across file. last, tell container setting service has alias, name setting, container can figure out concrete class behind app/facade/setting.

  1. for aliasing, mentioned apokryfos. register facade alias inside config/app.php, find section aliases , add line:

'aliases' => [      // ...      'setting' => app\facades\setting::class,  ], 

after can call facade this:

use setting;  setting::method(); 

hope helps.


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -