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.
- you need service class (in case, it's concrete class behind facade). made inside
app/servicesfolder:
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.
- next, create facade. made inside
app/facadesfolder:
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() register service container. inside
appserviceprovidernamespace 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.
- for aliasing, mentioned apokryfos. register facade alias inside
config/app.php, find sectionaliases, add line:
'aliases' => [ // ... 'setting' => app\facades\setting::class, ], after can call facade this:
use setting; setting::method(); hope helps.
Comments
Post a Comment