Laravel 4帮助程序和基本功能的最佳实践? [英] Best Practices for Laravel 4 Helpers and Basic Functions?
问题描述
我试图了解在Laravel 4中放置全局函数的最佳位置.例如,日期格式.我不认为制作外观是值得的,因为外观过于模块化.我已经阅读了有关创建库文件夹并在其中存储类的文章,但是对于一个简单的函数来说,这似乎很多. Blade模板中不应该有这样的工具"吗?
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 modular. I've read articles about creating a library folder and storing classes there but that also seems like a lot for a simple function. Shouldn't a 'tool' like this be available in Blade templates?
针对此类问题的最佳做法是什么?如何使它可用于Blade模板?
What are the best practices for something like this and how do I make it available to Blade templates?
推荐答案
丑陋,懒惰和糟糕的方法:在bootstrap/start.php
的末尾,添加include('tools.php')
并将函数放在该新文件中.
The ugly, lazy and awful way: At the end of bootstrap/start.php
, add an include('tools.php')
and place your function in that new file.
干净的方法:创建一个库.这样,只有在您实际使用它时,它才会自动加载.
The clean way: Create a library. That way it'll be autoloaded ONLY when you actually use it.
- 在
app
文件夹内创建一个libraries
文件夹 - 创建您的库文件,在其中创建一个类,然后向其中添加静态函数
- 选项1 :编辑
start/global.php
,将app_path().'/libraries'
添加到ClassLoader::addDirectories(
数组. - 选项2 :编辑
composer.json
,将"app/libraries"
添加到autoload
数组中.运行composer dump-autoload
- 从视图中调用类和静态函数.
- Create a
libraries
folder inside yourapp
folder - Create your library file, create a class in it, and add static functions to it
- Option 1: Edit
start/global.php
to addapp_path().'/libraries'
to theClassLoader::addDirectories(
array. - Option 2: Edit
composer.json
to add"app/libraries"
to theautoload
array. Runcomposer dump-autoload
- Call your class and static functions from your views.
关于您的选择,引自global.php
文件
About your options, quoted from the global.php
file
除了使用Composer外,您还可以使用Laravel类加载器 加载您的控制器和模型.这对于保持所有 无需更新Composer,即可在全局"名称空间中使用您的类.
In addition to using Composer, you may use the Laravel class loader to load your controllers and models. This is useful for keeping all of your classes in the "global" namespace without Composer updating.
您可以组合使用这两个选项,其中Laravel类加载器将自动在注册目录中搜索类(选项1 ,更容易),而Composer会保留所有类的记录,但仅在您更新后(选项2 ,可能会提高性能).
You can combine both options, where the Laravel class loader will automatically search for classes in the registered directories (Option 1, easier) and Composer will keep record of all the classes but only after you update it (Option 2, might improve performance).
这篇关于Laravel 4帮助程序和基本功能的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!