Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

Best Practices for Laravel 4 Helpers and Basic Functions?

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?

What are the best practices for something like this and how do I make it available to Blade templates?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

  • 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.

About your options, quoted from the global.php file

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...