我们已知laravel 8还为array,url,route,path等提供了辅助函数。但是,并非我们需要的所有函数。也许一些基本的辅助函数,例如我们项目中的日期格式。这是很多时候,我们需要创建自己的辅助函数,因此本章将讨论如何实现。
步骤1:创建helpers.php文件
在此步骤中,您需要在laravel项目中创建app/helpers.php,并将以下代码放入该文件中:
app/helpers.php
<?php function changeDateFormate($date,$date_format){ return \Carbon\Carbon::createFromFormat('Y-m-d', $date)->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') }}