当前位置: 动力学知识库 > 问答 > 编程问答 >

laravel - Add your own helpers.php to composer.json

问题描述:

Following this topic Use a custom function everywhere in the website I need a bit of help to finish what has been started.

So I created a folder in the app folder: Customs

Then I created a helpers.php file that has the following code:

<?php

use Illuminate\Support\Str;

if (! function_exists('str_slug')) {

/**

* Generate a URL friendly "slug" from a given string.

*

* @param string $title

* @param string $separator

* @return string

*/

function my_slug($title, $separator = '-')

{

$title = str_replace('\'','_',$title);

return Str::slug($title, $separator);

}

}

I read that I now have to update my composer.json, and especially the autoload section which is basically:

"autoload": {

"classmap": [

"database"

],

"psr-4": {

"App\\": "app/"

}

},

I don't understand what I should do now... psr-4 already says that the whole app folder is autoloaded, no?

I also tried to put the full path to the helpers.php but it did not work either.

What am I doing wrong?

网友答案:

Your autoload should have something like that:

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

where files are your custom files. Also as is mentioned in Use a custom function everywhere in the website question I advice you to use traits for e.g. trait StringSluggify. It keeps OOP way.

网友答案:
  1. Create a folder inside of app/ called Helpers.
  2. Inside of app/Helpers create your custom class

    namespace App\Helpers;
    
    class FooHelper{
    
        public static function bar(){
            return 'bar';
        }
    }
    
  3. Run composer dump-autoload to update autoload.

Here you are now able to use your helper functions like:

$bar = \App\Helper\FooHelper::bar();

If your plan is attach a facade, then edit facades array in config/app.php like so:

'Foo' => \App\Helpers\FooHelper::class

Now you can call your functions like:

public function controllerFunction(){
    $bar = \Foo::bar();
}
网友答案:

use it in your view {{my_slug($collection->value)}} or in your controllers with the namespacing App\customs\my_slug($value) or by adding use \App\customs to the top of your controller and then my_slug($value)

分享给朋友:
您可能感兴趣的文章:
随机阅读: