Is it possible to have my helper functions in a namespace?
My current setup (that I cannot make work) 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 am getting is Class "App\Helpers\HtmlDomParser" not found.
But that HtmlDomParser is not a class but a namespace.
Is the only correct setup to put the file_get_html()
function into the HtmlDomParser class? Laravel version: 8
CodePudding user response:
You didn't define a class "HtmlDomParser", only the namespace "App\Helpers\HtmlDomParser". To call the function in this namespace use the full qualified version:
App\Helpers\HtmlDomParser\file_get_html().
You may consult this page: https://www.php.net/manual/en/language.namespaces.rules.php
CodePudding user response:
You can do like this.
1- remove namespace from helper file.
app\Helpers\simple_html_dom.php:
<?php
function file_get_html(){
echo 'file_get_html() called';
}
2- your composer.json looks fine. just make sure you run below command after adding helper filein autoload section.
* composer du
* php artisan config:cache
3- call helper function directly without namespace in file app\Services\dde\dde_trait.php
namespace App\Services\dde;
trait ddeTrait{
public function parse(){
$finstat_content = file_get_html();
}
}