3
votes

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:

<?php

class ViewHelpers {

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

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

<?php namespace App\Providers;

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:

<?php namespace App\Helpers;

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.

1
After you add the namespace, are you running composer dump-autoload?Chris
Yes, I did - it showed a messageGenerating autoload files. Maybe it won't pick up the file at all because I require_once in my HelperServiceProvider, and composer doesn't know about that file at all.JustAMartin
Why are you using require? Can't you use composer to bring in the stuff you need?Chris
@Chris Somehow I have a habit to use composer.json only for third party libraries. It just seems not a clean solution to use it for my application specific stuff, that's why I created HelperServiceProvider.JustAMartin

1 Answers

2
votes

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.