Best Practices for Laravel 4 Helpers and Basic Functions?

后端 未结 4 1673
有刺的猬
有刺的猬 2020-11-30 16:20

I\'m trying to understand the best place to put a global function in Laravel 4. For example, date formatting. I don\'t think making a facade is worth it as facades are too m

4条回答
  •  情歌与酒
    2020-11-30 16:46

    Laravel's helpers.php method is to add it to your "files" in composer.json (https://github.com/laravel/framework/blob/master/composer.json):

    "autoload": {
        "classmap": [
            ...
        ],
        "files": [
            "app/libraries/helpers.php"
        ],
    },
    

    What I do is to create small classes (a few methods per class, one line per method, everything extended from something and DRY, that's my goal),

    class ExtendedCarbon extends Carbon\Carbon {
    
        public function formatDDMMAAAA($date)
        {
            /// format and return
        }
    
    }
    

    save them to them in app/libraries and add to composer.json:

    "autoload": {
        "classmap": [
            ...
            "app/libraries",
            ...
        ],
    },
    

    Execute

    composer dump
    

    And then just use them wherever you need

    $formatted = (new ExtendedCarbon)->formatDDMMAAAA($date);
    

    Watch this video about refactoring: http://www.youtube.com/watch?v=DC-pQPq0acs

    By the way, I'm kind of sure it was just an example, but you might not need a helper to format dates, since all dates in Laravel are instances of Carbon (https://github.com/briannesbitt/Carbon) and it has loads of methods to format date and time.

提交回复
热议问题