Blogger Information
Blog 40
fans 0
comment 1
visits 34255
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Laravel 添加自定义函数
景云
Original
1472 people have browsed it

1. 创建自定义辅助函数

我们把函数放在app/Support/Helpers/CustomHelper.php内(没有的文件夹创建即可)

  1. <?php
  2. if (! function_exists('test_function')) {
  3. function test_function() {
  4. //编写业务逻辑即可
  5. }
  6. }

2. 辅助函数文件载入

创建文件app/Support/Helpers/Helpers.php,并载入包含有自定义函数的文件:

  1. <?php
  2. $helpers = [
  3. 'CustomHelper.php'
  4. ];
  5. // 载入
  6. foreach ($helpers as $helperFileName) {
  7. include __DIR__ . '/' .$helperFileName;
  8. }

3. 在composer.json中自动载入Helpers.php文件

  1. /*composer.json*/
  2. {
  3. "autoload": {
  4. "classmap": [
  5. "database"
  6. ],
  7. "psr-4": {
  8. "App\\": "app/"
  9. },
  10. "files": [
  11. "app/Support/Helpers/helpers.php"
  12. ]
  13. }
  14. }

4. 重新编译autoload.php文件

运行如下命令:

  1. composer dump-autoload

可在VScode中使用款快捷键Ctrl+Shift+` 打开新终端,切换到项目目录,执行命令即可在任意地方调用自定义函数了(或使用CMD执行命令)



附:

Laravel内包含了很多非常好用的辅助函数,比如array_get()、array_first()、app_path()等等,具体可以查看文档,这些辅助函数为我们提供了很多简单易用的功能,提升了我们的开发效率。


学习路径:laravel5中添加自定义函数
原文是说在laravel5中添加自定义函数,我是在laravel7中使用,一样有效。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!