Laravel 4 Helpers 和基本函数的最佳实践? [英] Best Practices for Laravel 4 Helpers and Basic Functions?

查看:17
本文介绍了Laravel 4 Helpers 和基本函数的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解在 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 your app folder
  • Create your library file, create a class in it, and add static functions to it
  • Option 1: Edit start/global.php to add app_path().'/libraries' to the ClassLoader::addDirectories( array.
  • Option 2: Edit composer.json to add "app/libraries" to the autoload array. Run composer 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 Helpers 和基本函数的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆