>我有一个类,里面有一堆日期助手函数。我把它存储在app''Helpers''DateHelper.php
类
<?php
namespace App;
use DateTime;
class DateHelper {
public static function day_ago($date) {
if ($date) {
$ts = time() - strtotime(str_replace("-","/", $date ));
if($ts>31536000) $val = round($ts/31536000,0).' year';
else if($ts>2419200) $val = round($ts/2419200,0).' month';
else if($ts>604800) $val = round($ts/604800,0).' week';
else if($ts>86400) $val = round($ts/86400,0).' day';
else if($ts>3600) $val = round($ts/3600,0).' hour';
else if($ts>60) $val = round($ts/60,0).' minute';
else $val = $ts.' second';
if($val>1) $val .= 's';
return $val;
}
}
}
<小时 />作曲家.json
"autoload": {
"classmap": [
"database",
"app/Helpers"
],
"psr-4": {
"App''": "app/"
},
"files": ["app/Helper.php"]
},
然后,我run composer install
我得到了
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
> php artisan clear-compiled
> php artisan optimize
Generating optimized class loader
<小时 />别名
然后,我像这样添加到别名数组中:
'DateHelper' => 'app'Helpers'DateHelper',
<小时 />用
然后,我使用了它:
{{ DateHelper::day_ago($n->created_at) }}
<小时 />结果
现在,我不断Class 'DateHelper' not found
.
如何正确添加它?
你的别名是错误的。 别名是带有命名空间的完全限定类名,而不是它所在的目录。
'DateHelper' => 'App'DateHelper',
我建议遵循PSR-4标准。 这将节省时间并最大限度地减少混乱。
此外,这样就不会再发生这种情况,最好使用如下所示的语法......
'DateHelper' => App'DateHelper::class,
这样,您就可以绝对确定该类存在。
Laravel 中帮助程序文件的典型示例:
- 在
app
目录中创建一个helper.php
文件。 - 创建帮助程序函数
- 现在,将
helper.php
文件添加到composer.json
文件中。 - 做一个
composer dump-autoload
- 现在,您的帮助程序函数将在整个项目中可用。
创建目录,请为帮助程序文件设置命名空间。
"autoload": {
"classmap": [
"database",
],
"psr-4": {
"App''": "app/",
"Helpers''": "app/helpers/" //This is if you are using the directory
},
"files": ["helper.php"] //This is if it's just a php file.
},
即:
//app/helpers/helperClass.php
<?php namespace Helpers;
class helperClass{
public function showDate()
{
//return
}
}
在控制器中,使用帮助程序函数时,导入类。
即:
use Helpers/helperClass;
//If you've creates an alias for this, use it here.
use helperClass; //(This is from the config/app.php file)
如果是视图,请按如下方式使用它:{{ 'Helpers'helperClass::showDate() }}