Laravel-在服务提供商中需要php脚本 [英] Laravel - require php script in a service provider

查看:47
本文介绍了Laravel-在服务提供商中需要php脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Laravel并不陌生,并在SO上使用此答案为我的助手功能实现了服务提供商. >

建议:

在新生成的注册功能中 HelperServiceProvider.php添加以下代码

require_once app_path('Helpers/AnythingHelper.php');

但是, Laravel文档指出,注册方法仅应为用于将东西绑定到容器中:

如前所述,在register方法中,您仅应 将东西绑定到服务容器中.你绝对不要尝试 注册任何事件侦听器,路由或其他任何内容 register方法中的功能.

就我而言,该应用程序按原样运行,但在register函数中需要一条语句,因此我的问题更多是关于最佳做法",而不是使代码正常工作.

问题:

这是一种好的/可以接受的方法(在register方法中使用require语句),还是我应该将require语句移到boot方法中?

解决方案

如果仅在此处放置方法(而非类),则为推荐方法:

  1. 在任意位置创建文件
  2. composer.json中,请确保将此文件添加到autoload内的files键中,如下所示:

    "autoload": {
        // here other autoload things
    
        "files": ["app/Helpers/AnythingHelper.php"]
    },
    

  3. 运行composer dump-autoload`

对于类,显然应该使用标准的PSR-4自动加载

I am quite new to Laravel and implemented the service provider for my helper functions using this answer on SO.

It recommended to:

in the register function of your newly generated HelperServiceProvider.php add following code

require_once app_path('Helpers/AnythingHelper.php');

However, Laravel docs state that register method should only be used to bind things into the container:

As mentioned previously, within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method.

In my case the app works as it is, with require a statement in the register function, so my question is more about 'best practices' rather than making the code work.

Question:

Is this a good/acceptable approach (require statement in a register method), or should I rather move require statement to the boot method?

解决方案

Recommended approach if you put here only methods (not classes):

  1. Create file anywhere you want
  2. In composer.json make sure you add this file to files key inside autoload like this:

    "autoload": {
        // here other autoload things
    
        "files": ["app/Helpers/AnythingHelper.php"]
    },
    

  3. Run composerdump-autoload`

For classes obviously you should use standard PSR-4 autoloading

这篇关于Laravel-在服务提供商中需要php脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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