【问题标题】:Laravel helpers - removing the facadeLaravel 助手 - 移除门面
【发布时间】:2018-04-05 10:13:52
【问题描述】:
我有一个名为 \App\Helpers 的文件,其中包含几个函数,用于检查用户是否是管理员
@if(\Helper::isAdmin())
do something
@endif
我可以向用户模型添加一个方法并获取
$user->isAdmin()
这有点整洁。但是,有没有什么办法呢
@if(isAdmin())
do something
@endif
【问题讨论】:
标签:
laravel-5
methods
static-methods
helpers
【解决方案1】:
是的,您可以通过创建一个包含一些全局函数的文件来做到这一点,例如,在您的 composer.json 文件中添加一个条目,如下所示:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"helpers/functions.php"
]
},
注意files 部分。然后在您的项目根目录中创建一个顶级目录helpers,并在其中创建functions.php 文件并声明您的全局函数,例如:
// helpers/functions.php
if (! function_exists('isAdmin')) {
function isAdmin()
{
// You can entirely rewrite the logic here or
// you can use your existing Helper::isAdmin()
return \Helper::isAdmin();
}
}
最后别忘了运行composer dump-autoload。顺便说一句,如果你在Larave 5.5.x,那么你可以使用 larave'ls new Blade::if() Directives described here。