Laravel 5中定制助手的最佳实践

墨星鹏
2023-12-01

本文翻译自:Best Practices for Custom Helpers in Laravel 5

I would like to create helper functions to avoid repeating code between views in Laravel 5: 我想创建辅助函数以避免在Laravel 5中的视图之间重复代码:

view.blade.php view.blade.php

<p>Foo Formated text: {{ fooFormatText($text) }}</p>

They're basically text formatting functions. 它们基本上是文本格式化功能。 Where and how can I create a file with these functions? 我在哪里以及如何使用这些功能创建文件?


#1楼

参考:https://stackoom.com/question/1uhbg/Laravel-中定制助手的最佳实践


#2楼

Create a helpers.php file in your app folder and load it up with composer: 在app文件夹中创建一个helpers.php文件,然后使用composer加载它:

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php" // <---- ADD THIS
    ]
},

After adding that to your composer.json file, run the following command: 将其添加到composer.json文件后,运行以下命令:

composer dump-autoload

If you don't like keeping your helpers.php file in your app directory (because it's not a PSR-4 namespaced class file), you can do what the laravel.com website does: store the helpers.php in the bootstrap directory . 如果您不喜欢将helpers.php文件保存在app目录中(因为它不是PSR-4命名空间类文件),您可以执行laravel.com网站的操作:将helpers.php存储在bootstrap目录中 Remember to set it in your composer.json file: 记得在composer.json文件中设置它:

"files": [
    "bootstrap/helpers.php"
]

#3楼

my initial thought was the composer autoload as well, but it didn't feel very Laravel 5ish to me. 我最初的想法是作曲家自动加载,但它对我来说并没有感觉非常Laravel 5ish。 L5 makes heavy use of Service Providers, they are what bootstraps your application. L5大量使用服务提供商,它们是引导你的应用程序的东西。

To start off I created a folder in my app directory called Helpers . 首先,我在app目录中创建了一个名为Helpers的文件夹。 Then within the Helpers folder I added files for functions I wanted to add. 然后在Helpers文件夹中我添加了我想要添加的函数的文件。 Having a folder with multiple files allows us to avoid one big file that gets too long and unmanageable. 拥有一个包含多个文件的文件夹可以让我们避免一个太长且无法管理的大文件。

Next I created a HelperServiceProvider.php by running the artisan command: 接下来,我通过运行artisan命令创建了一个HelperServiceProvider.php

artisan make:provider HelperServiceProvider

Within the register method I added this snippet register方法中,我添加了这个片段

public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}

lastly register the service provider in your config/app.php in the providers array 最后在providers数组中的config/app.php中注册服务提供者

'providers' => [
    'App\Providers\HelperServiceProvider',
]

now any file in your Helpers directory is loaded, and ready for use. 现在, Helpers目录中的任何文件都已加载,可供使用。

UPDATE 2016-02-22 更新2016-02-22

There are a lot of good options here, but if my answer works for you, I went ahead and made a package for including helpers this way. 这里有很多不错的选择,但如果我的回答对你有用,我就会继续这样做,包括帮助包。 You can either use the package for inspiration or feel free to download it with Composer as well. 您可以使用该软件包获取灵感,也可以随意使用Composer下载它。 It has some built in helpers that I use often (but which are all inactive by default) and allows you to make your own custom helpers with a simple Artisan generator. 它有一些我经常使用的内置帮助程序(但默认情况下都是非活动状态)并允许您使用简单的Artisan生成器创建自己的自定义帮助程序。 It also addresses the suggestion one responder had of using a mapper and allows you to explicitly define the custom helpers to load, or by default, automatically load all PHP files in your helper directory. 它还解决了一个响应者使用映射器的建议,并允许您显式定义要加载的自定义帮助程序,或者默认情况下,自动加载帮助程序目录中的所有PHP文件。 Feedback and PRs are much appreciated! 反馈和PR非常感谢!

composer require browner12/helpers

Github: browner12/helpers Github: browner12 /助手


#4楼

This is what is suggested by JeffreyWay in this Laracasts Discussion . 这是JeffreyWayLaracasts讨论中提出的建议。

  1. Within your app/Http directory, create a helpers.php file and add your functions. app/Http目录中,创建一个helpers.php文件并添加您的函数。
  2. Within composer.json , in the autoload block, add "files": ["app/Http/helpers.php"] . composer.json ,在autoload块中,添加"files": ["app/Http/helpers.php"]
  3. Run composer dump-autoload . 运行composer dump-autoload

#5楼

This is my HelpersProvider.php file: 这是我的HelpersProvider.php文件:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    protected $helpers = [
        // Add your helpers in here
    ];

    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        foreach ($this->helpers as $helper) {
            $helper_path = app_path().'/Helpers/'.$helper.'.php';

            if (\File::isFile($helper_path)) {
                require_once $helper_path;
            }
        }
    }
}

You should create a folder called Helpers under the app folder, then create file called whatever.php inside and add the string whatever inside the $helpers array. 您应该创建一个文件夹,名为Helpersapp文件夹,然后创建文件名为whatever.php内,添加字符串whatever在$助手里面阵列。

Done! 完成!

Edit 编辑

I'm no longer using this option, I'm currently using composer to load static files like helpers. 我不再使用此选项,我目前正在使用composer来加载像helper这样的静态文件。

You can add the helpers directly at: 您可以直接在以下位置添加帮助:

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

#6楼

Here's a bash shell script I created to make Laravel 5 facades very quickly. 这是我创建的一个bash shell脚本,可以非常快速地创建Laravel 5外观。

Run this in your Laravel 5 installation directory. 在Laravel 5安装目录中运行它。

Call it like this: 像这样称呼它:

make_facade.sh -f <facade_name> -n '<namespace_prefix>'

Example: 例:

make_facade.sh -f helper -n 'App\MyApp'

If you run that example, it will create the directories Facades and Providers under 'your_laravel_installation_dir/app/MyApp'. 如果您运行该示例,它将在'your_laravel_installation_dir / app / MyApp'下创建FacadesProviders目录。

It will create the following 3 files and will also output them to the screen: 它将创建以下3个文件,并将它们输出到屏幕:

./app/MyApp/Facades/Helper.php
./app/MyApp/Facades/HelperFacade.php
./app/MyApp/Providers/HelperServiceProvider.php

After it is done, it will display a message similar to the following: 完成后,它将显示类似于以下内容的消息:

===========================
    Finished
===========================

Add these lines to config/app.php:
----------------------------------
Providers: App\MyApp\Providers\HelperServiceProvider,
Alias: 'Helper' => 'App\MyApp\Facades\HelperFacade',

So update the Providers and Alias list in 'config/app.php' 所以更新'config / app.php'中的Providers和Alias列表

Run composer -o dumpautoload 运行composer -o dumpautoload

The "./app/MyApp/Facades/Helper.php" will originally look like this: “./app/MyApp/Facades/Helper.php”最初看起来像这样:

<?php

namespace App\MyApp\Facades;


class Helper
{
    //
}

Now just add your methods in "./app/MyApp/Facades/Helper.php". 现在只需在“./app/MyApp/Facades/Helper.php”中添加您的方法。

Here is what "./app/MyApp/Facades/Helper.php" looks like after I added a Helper function. 添加辅助函数后,这就是“./app/MyApp/Facades/Helper.php”的样子。

<?php

namespace App\MyApp\Facades;

use Request;

class Helper
{
    public function isActive($pattern = null, $include_class = false)
    {
        return ((Request::is($pattern)) ? (($include_class) ? 'class="active"' : 'active' ) : '');
    }
}

This is how it would be called:
===============================

{!!  Helper::isActive('help', true) !!}

This function expects a pattern and can accept an optional second boolean argument. 此函数需要一个模式,并且可以接受可选的第二个布尔参数。

If the current URL matches the pattern passed to it, it will output 'active' (or 'class="active"' if you add 'true' as a second argument to the function call). 如果当前URL与传递给它的模式匹配,它将输出'active'(或'class =“active”',如果你添加'true'作为函数调用的第二个参数)。

I use it to highlight the menu that is active. 我用它来突出显示活动的菜单。

Below is the source code for my script. 以下是我的脚本的源代码。 I hope you find it useful and please let me know if you have any problems with it. 我希望你觉得它很有用,如果你有任何问题请告诉我。

#!/bin/bash

display_syntax(){
    echo ""
    echo "  The Syntax is like this:"
    echo "  ========================"
    echo "      "$(basename $0)" -f <facade_name> -n '<namespace_prefix>'"
    echo ""
    echo "  Example:"
    echo "  ========"
    echo "      "$(basename $0) -f test -n "'App\MyAppDirectory'"
    echo ""
}


if [ $# -ne 4 ]
then
    echo ""
    display_syntax
    exit
else
# Use > 0 to consume one or more arguments per pass in the loop (e.g.
# some arguments don't have a corresponding value to go with it such
# as in the --default example).
    while [[ $# > 0 ]]
    do
        key="$1"
            case $key in
            -n|--namespace_prefix)
            namespace_prefix_in="$2"
            echo ""
            shift # past argument
            ;;
            -f|--facade)
            facade_name_in="$2"
            shift # past argument
            ;;
            *)
                    # unknown option
            ;;
        esac
        shift # past argument or value
    done
fi
echo Facade Name = ${facade_name_in}
echo Namespace Prefix = $(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
echo ""
}


function display_start_banner(){

    echo '**********************************************************'
    echo '*          STARTING LARAVEL MAKE FACADE SCRIPT'
    echo '**********************************************************'
}

#  Init the Vars that I can in the beginning
function init_and_export_vars(){
    echo
    echo "INIT and EXPORT VARS"
    echo "===================="
    #   Substitution Tokens:
    #
    #   Tokens:
    #   {namespace_prefix}
    #   {namespace_prefix_lowerfirstchar}
    #   {facade_name_upcase}
    #   {facade_name_lowercase}
    #


    namespace_prefix=$(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
    namespace_prefix_lowerfirstchar=$(echo ${namespace_prefix_in} | sed -e 's#\\#/#g' -e 's/^\(.\)/\l\1/g')
    facade_name_upcase=$(echo ${facade_name_in} | sed -e 's/\b\(.\)/\u\1/')
    facade_name_lowercase=$(echo ${facade_name_in} | awk '{print tolower($0)}')


#   Filename: {facade_name_upcase}.php  -  SOURCE TEMPLATE
source_template='<?php

namespace {namespace_prefix}\Facades;

class {facade_name_upcase}
{
    //
}
'


#  Filename: {facade_name_upcase}ServiceProvider.php    -   SERVICE PROVIDER TEMPLATE
serviceProvider_template='<?php

namespace {namespace_prefix}\Providers;

use Illuminate\Support\ServiceProvider;
use App;


class {facade_name_upcase}ServiceProvider extends ServiceProvider {

    public function boot()
    {
        //
    }

    public function register()
    {
        App::bind("{facade_name_lowercase}", function()
        {
            return new \{namespace_prefix}\Facades\{facade_name_upcase};
        });
    }

}
'

#  {facade_name_upcase}Facade.php   -   FACADE TEMPLATE
facade_template='<?php

namespace {namespace_prefix}\Facades;

use Illuminate\Support\Facades\Facade;

class {facade_name_upcase}Facade extends Facade {

    protected static function getFacadeAccessor() { return "{facade_name_lowercase}"; }
}
'
}


function checkDirectoryExists(){
    if [ ! -d ${namespace_prefix_lowerfirstchar} ]
    then
        echo ""
        echo "Can't find the namespace: "${namespace_prefix_in}
        echo ""
        echo "*** NOTE:"
        echo "           Make sure the namspace directory exists and"
        echo "           you use quotes around the namespace_prefix."
        echo ""
        display_syntax
        exit
    fi
}

function makeDirectories(){
    echo "Make Directories"
    echo "================"
    mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
    mkdir -p ${namespace_prefix_lowerfirstchar}/Providers
    mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
}

function createSourceTemplate(){
    source_template=$(echo "${source_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create Source Template:"
    echo "======================="
    echo "${source_template}"
    echo ""
    echo "${source_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}.php
}

function createServiceProviderTemplate(){
    serviceProvider_template=$(echo "${serviceProvider_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create ServiceProvider Template:"
    echo "================================"
    echo "${serviceProvider_template}"
    echo ""
    echo "${serviceProvider_template}" > ./${namespace_prefix_lowerfirstchar}/Providers/${facade_name_upcase}ServiceProvider.php
}

function createFacadeTemplate(){
    facade_template=$(echo "${facade_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create Facade Template:"
    echo "======================="
    echo "${facade_template}"
    echo ""
    echo "${facade_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}Facade.php
}


function serviceProviderPrompt(){
    echo "Providers: ${namespace_prefix_in}\Providers\\${facade_name_upcase}ServiceProvider,"
}

function aliasPrompt(){
    echo "Alias: '"${facade_name_upcase}"' => '"${namespace_prefix_in}"\Facades\\${facade_name_upcase}Facade'," 
}

#
#   END FUNCTION DECLARATIONS
#


###########################
## START RUNNING SCRIPT  ##
###########################

display_start_banner

init_and_export_vars
makeDirectories 
checkDirectoryExists
echo ""

createSourceTemplate
createServiceProviderTemplate
createFacadeTemplate
echo ""
echo "==========================="
echo "  Finished TEST"
echo "==========================="
echo ""
echo "Add these lines to config/app.php:"
echo "----------------------------------"
serviceProviderPrompt
aliasPrompt
echo ""
 类似资料: