Lavarel - 模块间复用代码

文章目录

    代码复用在项目中早晚会遇到,这不在用 Laravel 给博客增加 Feed 订阅功能 就到了需要将生成网页 description 的函数提取出来,在文章显示与 Feed 生成的两个 Controller/Template 间复用。

    定义一个类

    <?php // Code within app\Utils.php
    
    namespace App;
    
    class Utils {
        public static function genDescription($content) {
            return someMethod($content);
        }
    }
    

    在 config/app.php 中添加 alias,否则无法在 template 中使用

    'Utils' => App\Utils::class,
    

    Controller 中使用

    use Utils;
    
    $description = Utils::genDescription($content);
    

    在 Template 中使用

    {{ Utils::genDescription($content) }}