如何在整个项目中编写一个可访问的类? [英] How can I write an accessible class in the whole of project?
问题描述
我使用Laravel框架,这是我的当前目录:
I use Laravel framework and this is my current directory:
如您所见,有一个名为 Log
(我选择的类)的类.现在,我需要使其全球化.我的意思是我想使它在任何地方都可以访问,并能够在以下文件中使它的对象(实例):
As you see, there is a class named Log
(the one I've selected). Now I need to make it global. I mean I want to make it accessible in everywhere and be able to I make a object (instance) of it in following files:
-
classe
文件夹中的所有文件 - 所有控制器 的
-
web.php
文件 - 所有视图文件
- All files of
classe
folder - All controller
web.php
file of- All file of views
无论如何,我希望能够对此有所了解并在各处调用它的方法,如下所示:
Anyway I want to be able to make a instande of it and call its methods everywhere like this:
$obj = new Log();
$obj->insert($message);
我该怎么做?
推荐答案
您可以将其放入 helpers.php
中,并将其添加到 composer.json
中,以加载帮助文件:
Put it in helpers.php
and add this to composer.json
to load the helpers file:
"autoload": {
....
"files": [
"app/someFolder/helpers.php"
]
},
然后,您将可以在全局范围内使用此帮助程序:
Then you'll be able to use this helper globally:
log('User added');
在视图中:
{{ log('User added') }}
更新
@stack,您对JSON使用了错误的语法(注释中的屏幕截图),这是正确的一种:
@stack, you're using wrong syntax for JSON (screenshot in comments), here's correct one:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/helpers.php"
]
},
这篇关于如何在整个项目中编写一个可访问的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!