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

2020-05-1717:00:06后端程序开发Comments2,204 views字数 10820阅读模式

I would like to create helper functions to avoid repeating code between views in Laravel 5:我想创建辅助函数以避免在Laravel 5中的视图之间重复代码:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

view.blade.phpview.blade.php文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

They're basically text formatting functions.它们基本上是文本格式化功能。Where and how can I create a file with these functions?我在哪里以及如何使用这些功能创建文件?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html


#1楼

参考:中定制助手的最佳实践文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html


#2楼

Create a file in your app folder and load it up with composer:在app文件夹中创建一个文件,然后使用composer加载它:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

After adding that to your file, run the following command:将其添加到文件后,运行以下命令:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

composer dump-autoload

If you don't like keeping your file in your app directory (because it's not a PSR-4 namespaced class file), you can do what the website does: store the in the bootstrap directory .如果您不喜欢将文件保存在app目录中(因为它不是PSR-4命名空间类文件),您可以执行网站的操作:将存储在bootstrap目录中 。Remember to set it in your file:记得在文件中设置它:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

"files": [
    "bootstrap/"
]

#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大量使用服务提供商,它们是引导你的应用程序的东西。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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.拥有一个包含多个文件的文件夹可以让我们避免一个太长且无法管理的大文件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

Next I created a by running the artisan command:接下来,我通过运行artisan命令创建了一个 :文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

artisan make:provider HelperServiceProvider

Within the register method I added this snippetregister方法中,我添加了这个片段文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

lastly register the service provider in your config/ in the providers array最后在providers数组中的config/中注册服务提供者文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

now any file in your Helpers directory is loaded, and ready for use.现在, Helpers目录中的任何文件都已加载,可供使用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

UPDATE 2016-02-22更新2016-02-22文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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非常感谢!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

composer require browner12/helpers

Github: browner12/helpersGithub: browner12 /助手文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html


#4楼

This is what is suggested by JeffreyWay in this Laracasts Discussion .这是JeffreyWay在Laracasts讨论中提出的建议。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

#5楼

This is my file:这是我的文件:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

<?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 inside and add the string whatever inside the $helpers array.您应该创建一个文件夹,名为Helpersapp文件夹,然后创建文件名为内,添加字符串whatever在$助手里面阵列。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

Done!完成!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

I'm no longer using this option, I'm currently using composer to load static files like helpers.我不再使用此选项,我目前正在使用composer来加载像helper这样的静态文件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

You can add the helpers directly at:您可以直接在以下位置添加帮助:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

#6楼

Here's a bash shell script I created to make Laravel 5 facades very quickly.这是我创建的一个bash shell脚本,可以非常快速地创建Laravel 5外观。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

Run this in your Laravel 5 installation directory.在Laravel 5安装目录中运行它。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

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

Example:例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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目录。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

./app/MyApp/Facades/
./app/MyApp/Facades/Helper
./app/MyApp/Providers/

After it is done, it will display a message similar to the following:完成后,它将显示类似于以下内容的消息:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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

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

So update the Providers and Alias list in 'config/'所以更新'config / '中的Providers和Alias列表文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

Run composer -o dumpautoload运行composer -o dumpautoload文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

The "./app/MyApp/Facades/" will originally look like this:“./app/MyApp/Facades/”最初看起来像这样:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

<?php

namespace App\MyApp\Facades;


class Helper
{
    //
}

Now just add your methods in "./app/MyApp/Facades/".现在只需在“./app/MyApp/Facades/”中添加您的方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

Here is what "./app/MyApp/Facades/" looks like after I added a Helper function.添加辅助函数后,这就是“./app/MyApp/Facades/”的样子。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

<?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.此函数需要一个模式,并且可以接受可选的第二个布尔参数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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'作为函数调用的第二个参数)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

I use it to highlight the menu that is active.我用它来突出显示活动的菜单。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html

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}    -   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 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}
}

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}
}


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/:"
echo "----------------------------------"
serviceProviderPrompt
aliasPrompt
echo ""
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/19103.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/19103.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定