Laravel: Custom functions using namespaces
P粉561323975
P粉561323975 2024-03-27 23:28:51
0
2
462

Is it possible to put my helper functions in a namespace?

My current setup (which I can't get working) is:

app\Helpers\simple_html_dom.php:

<?php

namespace App\Helpers\HtmlDomParser;

function file_get_html(){
  echo 'file_get_html() called';
}

composer.json

"autoload": {
        "files": [
            "app/Helpers/simple_html_dom.php",
            "app/Helpers/common.php"
        ],
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        }
    },

app\Services\dde\dde_trait.php

<?php

namespace App\Services\dde;
use App\Helpers\HtmlDomParser;

trait ddeTrait{
  public function parse(){
    $content = HtmlDomParser::file_get_html();
  }
}

The error I receive is The class "App\Helpers\HtmlDomParser" cannot be found.

But HtmlDomParser is not a class, but a namespace.

Is the only correct setting to put the file_get_html() function into the HtmlDomParser class? Laravel version: 8

P粉561323975
P粉561323975

reply all(2)
P粉826429907
You can do like this.

1- remove namespace from helper file.

app\Helpers\simple_html_dom.php:

P粉055726146

You did not define the class "HtmlDomParser", only the namespace "App\Helpers\HtmlDomParser". To call functions in this namespace, use the fully qualified version:

App\Helpers\HtmlDomParser\file_get_html().

You can check this page: https://www.php .net/manual/en/language.namespaces.rules.php

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template