ITPub博客

首页 > IT职业 > IT图书 > 无涯教程: Laravel 8 - 自定义函数介绍

无涯教程: Laravel 8 - 自定义函数介绍

IT图书 作者:daxuesheng 时间:2021-09-09 08:52:39 0 删除 编辑

我们已知laravel 8还为array,url,route,path等提供了辅助函数。但是,并非我们需要的所有函数。也许一些基本的辅助函数,例如我们项目中的日期格式。这是很多时候,我们需要创建自己的辅助函数,因此本章将讨论如何实现。

步骤1:创建helpers.php文件

在此步骤中,您需要在laravel项目中创建app/helpers.php,并将以下代码放入该文件中:

app/helpers.php

format($date_format);    
}
   
function productImagePath($image_name)
{
    return public_path('images/products/'.$image_name);
}

步骤2:在composer.json文件中添加文件路径

在这一步中,您必须放置helpers文件的路径,因此基本上打开composer.json文件,并将以下代码放入该文件中:

composer.json

...
  
"autoload": {
    "psr-4": {
        "App\": "app/",
        "Database\Factories\": "database/factories/",
        "Database\Seeders\": "database/seeders/"
    },
    "files": [
        "app/helpers.php" 
    ]
},
  
...

步骤3:运行命令

这是最后一步,您应该只运行以下命令:

composer dump-autoload

好的,现在您终于可以使用您的自定义帮助程序函数,如changeDateFormate()和productImagePath(),将为您提供如何使用自定义程序函数的示例。

在路由中使用:

Route::get('helper', function(){
    $imageName = 'example.png?imageView2/0/q/75|watermark/2/text/bGVhcm5may5jb20=/font/Y29uc29sYXM=/fontsize/400/fill/I0YxMTQxNA==/dissolve/100/gravity/SouthEast/dx/10/dy/10';
    $fullpath = productImagePath($imageName);
  
    dd($fullpath);
});
  
Route::get('helper2', function(){
    $newDateFormat = changeDateFormate(date('Y-m-d'),'m/d/Y');
  
    dd($newDateFormat);
});

输出:

"/var/www/me/laravel8/blog/public/images/products/example.png?imageView2/0/q/75|watermark/2/text/bGVhcm5may5jb20=/font/Y29uc29sYXM=/fontsize/400/fill/I0YxMTQxNA==/dissolve/100/gravity/SouthEast/dx/10/dy/10"
"09/14/2020"

在视图文件中使用:

$imageName = 'example.png?imageView2/0/q/75|watermark/2/text/bGVhcm5may5jb20=/font/Y29uc29sYXM=/fontsize/400/fill/I0YxMTQxNA==/dissolve/100/gravity/SouthEast/dx/10/dy/10';
$fullpath = productImagePath($imageName);
print_r($fullpath);
{{ changeDateFormate(date('Y-m-d'),'m/d/Y')  }}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4692/viewspace-2807104/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-05-22

  • 博文量
    176
  • 访问量
    24988