Laravel Steps

Laravel 添加辅助函数

2018-11-01  本文已影响0人  AnnaJIAN

写一个创建自己的辅助函数的例子

创建helpers.php 文件,添加自己的函数

bootstrap/helpers.php
<?php
    function route_class()
    {
        echo 'here';
        return str_replace('.', '-', Route::currentRouteName());
    }
?>
php artisan tinker
>>> route_class()

PHP Fatal error: Call to undefined function route_class() in Psy Shell code on line 1

报错找不到这个函数,这是因为我们还没有引入这个 helpers.php 文件,我们可以使用 composer 的 autoload 功能来自动引入:

打开 composer.json 文件,并找到 autoload 段,将其修改为:

    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
            "bootstrap/helpers.php"
        ]
    },
09:37:31@Localhost🤓composer dumpautoload
Generating optimized autoload files
09:38:00@Localhost🤓php artisan tinker
Psy Shell v0.9.9 (PHP 7.2.10 — cli) by Justin Hileman
>>> route_class();
here⏎
=> ""
>>>

其他地方直接调用这个函数就可以了

<div id="app" class="{{ route_class() }}-page">
上一篇 下一篇

猜你喜欢

热点阅读