Saturday 28 December 2019

php - Laravel custom view helpers stop working if using namespace



I have followed some tutorials to create some global helper functions to use in blade views.



I have created ViewHelpers.php file in App\Helpers folder. This file contains the following code:




class ViewHelpers {


public static function bah()
{
echo 'blah';
}
}


Here is my service provider which loads my helpers (currently just one file):





use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {

public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename){
echo $filename; // for debugging - yes, I see it is getting called

require_once($filename);
}
}
}


I have added it to config\app.php in 'providers' section:



'App\Providers\HelperServiceProvider',



And now I call my helper in a blade view:



{{ViewHelpers::bah()}}


For now it works fine.



But if I change my ViewHelper namespace to this:





class ViewHelpers {

// omitted for brevity


my views fail with Class 'ViewHelpers' not found.



How do I make my views to see the ViewHelpers class even if it is in a different namespace? Where do I add use App\Helpers?




Another related question - can I make an alias for ViewHelpers class to make it look like, let's say, VH:bah() in my views?



And I'd prefer to do it in simple way, if possible (without Facades and what not) because these are just static helpers without any need for class instance and IoC.



I'm using Laravel 5.


Answer



You will get Class 'ViewHelpers' not found because there is no ViewHelpers, there is App\Helpers\ViewHelpers and you need to specify namespace (even in view).



You can register alias in config/app.php which will allow you to use VH::something():




'aliases' => [
// in the end just add:
'VH' => 'App\Helpers\ViewHelpers'
],


If your namespace is correct you do not even have to use providers - class will be loaded by Laravel.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...